diff --git a/node_modules/resolve-pkg-maps/LICENSE b/node_modules/resolve-pkg-maps/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..51e4fd8646a1cfd17e90dd3b633f24eb8dbb01ac --- /dev/null +++ b/node_modules/resolve-pkg-maps/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Hiroki Osame + +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. diff --git a/node_modules/resolve-pkg-maps/README.md b/node_modules/resolve-pkg-maps/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2469b1b20cbc3933081514e56c4d290d4492c682 --- /dev/null +++ b/node_modules/resolve-pkg-maps/README.md @@ -0,0 +1,216 @@ +# resolve-pkg-maps + +Utils to resolve `package.json` subpath & conditional [`exports`](https://nodejs.org/api/packages.html#exports)/[`imports`](https://nodejs.org/api/packages.html#imports) in resolvers. + +Implements the [ESM resolution algorithm](https://nodejs.org/api/esm.html#resolver-algorithm-specification). Tested [against Node.js](/tests/) for accuracy. + +Support this project by ⭐️ starring and sharing it. [Follow me](https://github.com/privatenumber) to see what other cool projects I'm working on! ❤️ + +## Usage + +### Resolving `exports` + +_utils/package.json_ +```json5 +{ + // ... + "exports": { + "./reverse": { + "require": "./file.cjs", + "default": "./file.mjs" + } + }, + // ... +} +``` + +```ts +import { resolveExports } from 'resolve-pkg-maps' + +const [packageName, packageSubpath] = parseRequest('utils/reverse') + +const resolvedPaths: string[] = resolveExports( + getPackageJson(packageName).exports, + packageSubpath, + ['import', ...otherConditions] +) +// => ['./file.mjs'] +``` + +### Resolving `imports` + +_package.json_ +```json5 +{ + // ... + "imports": { + "#supports-color": { + "node": "./index.js", + "default": "./browser.js" + } + }, + // ... +} +``` + +```ts +import { resolveImports } from 'resolve-pkg-maps' + +const resolvedPaths: string[] = resolveImports( + getPackageJson('.').imports, + '#supports-color', + ['node', ...otherConditions] +) +// => ['./index.js'] +``` + +## API + +### resolveExports(exports, request, conditions) + +Returns: `string[]` + +Resolves the `request` based on `exports` and `conditions`. Returns an array of paths (e.g. in case a fallback array is matched). + +#### exports + +Type: +```ts +type Exports = PathOrMap | readonly PathOrMap[] + +type PathOrMap = string | PathConditionsMap + +type PathConditionsMap = { + [condition: string]: PathConditions | null +} +``` + +The [`exports` property](https://nodejs.org/api/packages.html#exports) value in `package.json`. + +#### request + +Type: `string` + +The package subpath to resolve. Assumes a normalized path is passed in (eg. [repeating slashes `//`](https://github.com/nodejs/node/issues/44316)). + +It _should not_ start with `/` or `./`. + +Example: if the full import path is `some-package/subpath/file`, the request is `subpath/file`. + + +#### conditions + +Type: `readonly string[]` + +An array of conditions to use when resolving the request. For reference, Node.js's default conditions are [`['node', 'import']`](https://nodejs.org/api/esm.html#:~:text=defaultConditions%20is%20the%20conditional%20environment%20name%20array%2C%20%5B%22node%22%2C%20%22import%22%5D.). + +The order of this array does not matter; the order of condition keys in the export map is what matters instead. + +Not all conditions in the array need to be met to resolve the request. It just needs enough to resolve to a path. + +--- + +### resolveImports(imports, request, conditions) + +Returns: `string[]` + +Resolves the `request` based on `imports` and `conditions`. Returns an array of paths (e.g. in case a fallback array is matched). + +#### imports + +Type: +```ts +type Imports = { + [condition: string]: PathOrMap | readonly PathOrMap[] | null +} + +type PathOrMap = string | Imports +``` + +The [`imports` property](https://nodejs.org/api/packages.html#imports) value in `package.json`. + + +#### request + +Type: `string` + +The request resolve. Assumes a normalized path is passed in (eg. [repeating slashes `//`](https://github.com/nodejs/node/issues/44316)). + +> **Note:** In Node.js, imports resolutions are limited to requests prefixed with `#`. However, this package does not enforce that requirement in case you want to add custom support for non-prefixed entries. + +#### conditions + +Type: `readonly string[]` + +An array of conditions to use when resolving the request. For reference, Node.js's default conditions are [`['node', 'import']`](https://nodejs.org/api/esm.html#:~:text=defaultConditions%20is%20the%20conditional%20environment%20name%20array%2C%20%5B%22node%22%2C%20%22import%22%5D.). + +The order of this array does not matter; the order of condition keys in the import map is what matters instead. + +Not all conditions in the array need to be met to resolve the request. It just needs enough to resolve to a path. + +--- + +### Errors + +#### `ERR_PACKAGE_PATH_NOT_EXPORTED` + - If the request is not exported by the export map + +#### `ERR_PACKAGE_IMPORT_NOT_DEFINED` + - If the request is not defined by the import map + +#### `ERR_INVALID_PACKAGE_CONFIG` + + - If an object contains properties that are both paths and conditions (e.g. start with and without `.`) + - If an object contains numeric properties + +#### `ERR_INVALID_PACKAGE_TARGET` + - If a resolved exports path is not a valid path (e.g. not relative or has protocol) + - If a resolved path includes `..` or `node_modules` + - If a resolved path is a type that cannot be parsed + +## FAQ + +### Why do the APIs return an array of paths? + +`exports`/`imports` supports passing in a [fallback array](https://github.com/jkrems/proposal-pkg-exports/#:~:text=Whenever%20there%20is,to%20new%20cases.) to provide fallback paths if the previous one is invalid: + +```json5 +{ + "exports": { + "./feature": [ + "./file.js", + "./fallback.js" + ] + } +} +``` + +Node.js's implementation [picks the first valid path (without attempting to resolve it)](https://github.com/nodejs/node/issues/44282#issuecomment-1220151715) and throws an error if it can't be resolved. Node.js's fallback array is designed for [forward compatibility with features](https://github.com/jkrems/proposal-pkg-exports/#:~:text=providing%20forwards%20compatiblitiy%20for%20new%20features) (e.g. protocols) that can be immediately/inexpensively validated: + +```json5 +{ + "exports": { + "./core-polyfill": ["std:core-module", "./core-polyfill.js"] + } +} +``` + +However, [Webpack](https://webpack.js.org/guides/package-exports/#alternatives) and [TypeScript](https://github.com/microsoft/TypeScript/blob/71e852922888337ef51a0e48416034a94a6c34d9/src/compiler/moduleSpecifiers.ts#L695) have deviated from this behavior and attempts to resolve the next path if a path cannot be resolved. + +By returning an array of matched paths instead of just the first one, the user can decide which behavior to adopt. + +### How is it different from [`resolve.exports`](https://github.com/lukeed/resolve.exports)? + +`resolve.exports` only resolves `exports`, whereas this package resolves both `exports` & `imports`. This comparison will only cover resolving `exports`. + +- Despite it's name, `resolve.exports` handles more than just `exports`. It takes in the entire `package.json` object to handle resolving `.` and [self-references](https://nodejs.org/api/packages.html#self-referencing-a-package-using-its-name). This package only accepts `exports`/`imports` maps from `package.json` and is scoped to only resolving what's defined in the maps. + +- `resolve.exports` accepts the full request (e.g. `foo/bar`), whereas this package only accepts the requested subpath (e.g. `bar`). + +- `resolve.exports` only returns the first result in a fallback array. This package returns an array of results for the user to decide how to handle it. + +- `resolve.exports` supports [subpath folder mapping](https://nodejs.org/docs/latest-v16.x/api/packages.html#subpath-folder-mappings) (deprecated in Node.js v16 & removed in v17) but seems to [have a bug](https://github.com/lukeed/resolve.exports/issues/7). This package does not support subpath folder mapping because Node.js has removed it in favor of using subpath patterns. + +- Neither resolvers rely on a file-system + +This package also addresses many of the bugs in `resolve.exports`, demonstrated in [this test](/tests/exports/compare-resolve.exports.ts). diff --git a/node_modules/resolve-pkg-maps/package.json b/node_modules/resolve-pkg-maps/package.json new file mode 100644 index 0000000000000000000000000000000000000000..720d98492299c177bb128be75e3442c91c3639a9 --- /dev/null +++ b/node_modules/resolve-pkg-maps/package.json @@ -0,0 +1,42 @@ +{ + "name": "resolve-pkg-maps", + "version": "1.0.0", + "description": "Resolve package.json exports & imports maps", + "keywords": [ + "node.js", + "package.json", + "exports", + "imports" + ], + "license": "MIT", + "repository": "privatenumber/resolve-pkg-maps", + "funding": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1", + "author": { + "name": "Hiroki Osame", + "email": "hiroki.osame@gmail.com" + }, + "type": "module", + "files": [ + "dist" + ], + "main": "./dist/index.cjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.cts", + "exports": { + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + }, + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + } + }, + "imports": { + "#resolve-pkg-maps": { + "types": "./src/index.ts", + "development": "./src/index.ts", + "default": "./dist/index.mjs" + } + } +} \ No newline at end of file diff --git a/node_modules/resolve-protobuf-schema/.travis.yml b/node_modules/resolve-protobuf-schema/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..87f8cd91a50887a0f337f649f5cccb10599f9c69 --- /dev/null +++ b/node_modules/resolve-protobuf-schema/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - "0.10" \ No newline at end of file diff --git a/node_modules/resolve-protobuf-schema/LICENSE b/node_modules/resolve-protobuf-schema/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8ff6bf68f98ea4d7748a1fa1e36e48c2043a249e --- /dev/null +++ b/node_modules/resolve-protobuf-schema/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Mathias Buus + +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. diff --git a/node_modules/resolve-protobuf-schema/README.md b/node_modules/resolve-protobuf-schema/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d4b424b0897305190610bf69543680d6c6dc0620 --- /dev/null +++ b/node_modules/resolve-protobuf-schema/README.md @@ -0,0 +1,49 @@ +# resolve-protobuf-schema + +Read a protobuf schema from the disk, parse it and resolve all imports + +``` +npm install resolve-protobuf-schema +``` + +[![build status](http://img.shields.io/travis/mafintosh/resolve-protobuf-schema.svg?style=flat)](http://travis-ci.org/mafintosh/resolve-protobuf-schema) + +## Usage + +Store the following example protobuf schema in `test.proto` + +``` +message Test { + optional string test = 1; +} +``` + +Then run + +``` js +var resolve = require('resolve-protobuf-schema') +console.log(resolve.sync('test.proto')) // prints the parsed schema +``` + +Schema imports will resolved as well + +``` +import "./test.proto" + +message AnotherTest { + optional string test = 1; +} +``` + +``` js +console.log(resolve.sync('./another-test.proto')) // will print a combined parsed schema +``` + +## API + +* `resolve(path, cb)` read and resolve a schema +* `resolve.sync(path)` sync version of `resolve` + +## License + +MIT diff --git a/node_modules/resolve-protobuf-schema/index.js b/node_modules/resolve-protobuf-schema/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7bc03abe75e608369aa38ffd7ea28b12b17cd118 --- /dev/null +++ b/node_modules/resolve-protobuf-schema/index.js @@ -0,0 +1,50 @@ +var schema = require('protocol-buffers-schema') +var fs = require('fs') +var path = require('path') + +var merge = function(a, b) { + a.messages = a.messages.concat(b.messages) + a.enums = a.enums.concat(b.enums) + return a +} + +var readSync = function(filename) { + if (!/\.proto$/i.test(filename) && !fs.existsSync(filename)) filename += '.proto' + + var sch = schema(fs.readFileSync(filename, 'utf-8')) + var imports = [].concat(sch.imports || []) + + imports.forEach(function(i) { + sch = merge(sch, readSync(path.resolve(path.dirname(filename), i))) + }) + + return sch +} + +var read = function(filename, cb) { + fs.exists(filename, function(exists) { + if (!exists && !/\.proto$/i.test(filename)) filename += '.proto' + + fs.readFile(filename, 'utf-8', function(err, proto) { + if (err) return cb(err) + + var sch = schema(proto) + var imports = [].concat(sch.imports || []) + + var loop = function() { + if (!imports.length) return cb(null, sch) + + read(path.resolve(path.dirname(filename), imports.shift()), function(err, ch) { + if (err) return cb(err) + sch = merge(sch, ch) + loop() + }) + } + + loop() + }) + }) +} + +module.exports = read +module.exports.sync = readSync \ No newline at end of file diff --git a/node_modules/resolve-protobuf-schema/package.json b/node_modules/resolve-protobuf-schema/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4f88e67699a907737641078d75249ffbc5aa4998 --- /dev/null +++ b/node_modules/resolve-protobuf-schema/package.json @@ -0,0 +1,25 @@ +{ + "name": "resolve-protobuf-schema", + "version": "2.1.0", + "description": "Read a protobuf schema from the disk, parse it and resolve all imports", + "main": "index.js", + "dependencies": { + "protocol-buffers-schema": "^3.3.1" + }, + "devDependencies": { + "tape": "^3.0.0" + }, + "scripts": { + "test": "tape test/index.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/resolve-protobuf-schema.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/resolve-protobuf-schema/issues" + }, + "homepage": "https://github.com/mafintosh/resolve-protobuf-schema" +} diff --git a/node_modules/resolve-protobuf-schema/test/a.proto b/node_modules/resolve-protobuf-schema/test/a.proto new file mode 100644 index 0000000000000000000000000000000000000000..9f34baf5189ba4dc29a5ff3bc395fa1f3cd78373 --- /dev/null +++ b/node_modules/resolve-protobuf-schema/test/a.proto @@ -0,0 +1,5 @@ +import "./b.proto"; + +message A { + optional string a = 1; +} \ No newline at end of file diff --git a/node_modules/resolve-protobuf-schema/test/b.proto b/node_modules/resolve-protobuf-schema/test/b.proto new file mode 100644 index 0000000000000000000000000000000000000000..a430c4e0ad4fbb33c446dbf431d928e9cb25ba83 --- /dev/null +++ b/node_modules/resolve-protobuf-schema/test/b.proto @@ -0,0 +1,5 @@ +import "./c.proto"; + +message B { + optional string b = 1; +} \ No newline at end of file diff --git a/node_modules/resolve-protobuf-schema/test/c.proto b/node_modules/resolve-protobuf-schema/test/c.proto new file mode 100644 index 0000000000000000000000000000000000000000..7c660c6c464e211603d3593a3401e48c5a4837a0 --- /dev/null +++ b/node_modules/resolve-protobuf-schema/test/c.proto @@ -0,0 +1,3 @@ +message C { + optional string c = 1; +} \ No newline at end of file diff --git a/node_modules/resolve-protobuf-schema/test/index.js b/node_modules/resolve-protobuf-schema/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e752c63210adff40e5f1f2c2126a0762435f6acf --- /dev/null +++ b/node_modules/resolve-protobuf-schema/test/index.js @@ -0,0 +1,49 @@ +var tape = require('tape') +var schema = require('../') + +var test = function(name, fn) { + tape(name, function(t) { + fn(t, schema) + }) + tape(name+' sync', function(t) { + fn(t, function(name, cb) { + cb(null, schema.sync(name)) + }) + }) +} + +test('c', function(t, schema) { + schema(__dirname+'/c.proto', function(err, sch) { + t.notOk(err, 'no err') + t.same(sch.messages.length, 1) + schema(__dirname+'/c', function(err, sch) { + t.notOk(err, 'no err') + t.same(sch.messages.length, 1) + t.end() + }) + }) +}) + +test('b imports c', function(t, schema) { + schema(__dirname+'/b.proto', function(err, sch) { + t.notOk(err, 'no err') + t.same(sch.messages.length, 2) + schema(__dirname+'/b', function(err, sch) { + t.notOk(err, 'no err') + t.same(sch.messages.length, 2) + t.end() + }) + }) +}) + +test('a imports b imports c', function(t, schema) { + schema(__dirname+'/a.proto', function(err, sch) { + t.notOk(err, 'no err') + t.same(sch.messages.length, 3) + schema(__dirname+'/a', function(err, sch) { + t.notOk(err, 'no err') + t.same(sch.messages.length, 3) + t.end() + }) + }) +}) \ No newline at end of file diff --git a/node_modules/resolve/test/core.js b/node_modules/resolve/test/core.js new file mode 100644 index 0000000000000000000000000000000000000000..a477adc5ce2a4464362d617a21604b367a8d9718 --- /dev/null +++ b/node_modules/resolve/test/core.js @@ -0,0 +1,88 @@ +var test = require('tape'); +var keys = require('object-keys'); +var semver = require('semver'); + +var resolve = require('../'); + +var brokenNode = semver.satisfies(process.version, '11.11 - 11.13'); + +test('core modules', function (t) { + t.test('isCore()', function (st) { + st.ok(resolve.isCore('fs')); + st.ok(resolve.isCore('net')); + st.ok(resolve.isCore('http')); + + st.ok(!resolve.isCore('seq')); + st.ok(!resolve.isCore('../')); + + st.ok(!resolve.isCore('toString')); + + st.end(); + }); + + t.test('core list', function (st) { + var cores = keys(resolve.core); + st.plan(cores.length); + + for (var i = 0; i < cores.length; ++i) { + var mod = cores[i]; + // note: this must be require, not require.resolve, due to https://github.com/nodejs/node/issues/43274 + var requireFunc = function () { require(mod); }; // eslint-disable-line no-loop-func + t.comment(mod + ': ' + resolve.core[mod]); + if (resolve.core[mod]) { + st.doesNotThrow(requireFunc, mod + ' supported; requiring does not throw'); + } else if (brokenNode) { + st.ok(true, 'this version of node is broken: attempting to require things that fail to resolve breaks "home_paths" tests'); + } else { + st.throws(requireFunc, mod + ' not supported; requiring throws'); + } + } + + st.end(); + }); + + t.test('core via repl module', { skip: !resolve.core.repl }, function (st) { + var libs = require('repl')._builtinLibs; // eslint-disable-line no-underscore-dangle + if (!libs) { + st.skip('module.builtinModules does not exist'); + return st.end(); + } + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + st.ok(resolve.core[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + } + st.end(); + }); + + t.test('core via builtinModules list', { skip: !resolve.core.module }, function (st) { + var libs = require('module').builtinModules; + if (!libs) { + st.skip('module.builtinModules does not exist'); + return st.end(); + } + var blacklist = [ + '_debug_agent', + 'v8/tools/tickprocessor-driver', + 'v8/tools/SourceMap', + 'v8/tools/tickprocessor', + 'v8/tools/profile' + ]; + for (var i = 0; i < libs.length; ++i) { + var mod = libs[i]; + if (blacklist.indexOf(mod) === -1) { + st.ok(resolve.core[mod], mod + ' is a core module'); + st.doesNotThrow( + function () { require(mod); }, // eslint-disable-line no-loop-func + 'requiring ' + mod + ' does not throw' + ); + } + } + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/resolve/test/default_paths.js b/node_modules/resolve/test/default_paths.js new file mode 100644 index 0000000000000000000000000000000000000000..a8c3d73f7f808e861cb6494b73d411739b41a2bc --- /dev/null +++ b/node_modules/resolve/test/default_paths.js @@ -0,0 +1,49 @@ +'use strict'; + +var path = require('path'); +var test = require('tape'); +var mockProperty = require('mock-property'); + +var homedirPath = require.resolve('../lib/homedir'); +var asyncPath = require.resolve('../async'); +var libAsyncPath = require.resolve('../lib/async'); +var syncPath = require.resolve('../sync'); +var libSyncPath = require.resolve('../lib/sync'); + +function mockNullHomedir(t) { + t.teardown(mockProperty(require.cache, homedirPath, { + value: { id: homedirPath, filename: homedirPath, loaded: true, exports: function () { return null; } } + })); +} + +test('async: null homedir does not throw', function (t) { + t.plan(2); + + mockNullHomedir(t); + t.teardown(mockProperty(require.cache, asyncPath, { 'delete': true })); + t.teardown(mockProperty(require.cache, libAsyncPath, { 'delete': true })); + + var resolve = require('../lib/async'); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./baz', { basedir: dir }, function (err, res) { + t.error(err, 'no error'); + t.equal(res, path.join(dir, 'baz', 'quux.js'), 'resolves correctly with null homedir'); + }); +}); + +test('sync: null homedir does not throw', function (t) { + mockNullHomedir(t); + t.teardown(mockProperty(require.cache, syncPath, { 'delete': true })); + t.teardown(mockProperty(require.cache, libSyncPath, { 'delete': true })); + + var resolveSync = require('../lib/sync'); + + var dir = path.join(__dirname, 'resolver'); + + var res = resolveSync('./baz', { basedir: dir }); + t.equal(res, path.join(dir, 'baz', 'quux.js'), 'resolves correctly with null homedir'); + + t.end(); +}); diff --git a/node_modules/resolve/test/dotdot.js b/node_modules/resolve/test/dotdot.js new file mode 100644 index 0000000000000000000000000000000000000000..30806659be2ef27d410722636d6f79c8f8e999b0 --- /dev/null +++ b/node_modules/resolve/test/dotdot.js @@ -0,0 +1,29 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('dotdot', function (t) { + t.plan(4); + var dir = path.join(__dirname, '/dotdot/abc'); + + resolve('..', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'dotdot/index.js')); + }); + + resolve('.', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('dotdot sync', function (t) { + t.plan(2); + var dir = path.join(__dirname, '/dotdot/abc'); + + var a = resolve.sync('..', { basedir: dir }); + t.equal(a, path.join(__dirname, 'dotdot/index.js')); + + var b = resolve.sync('.', { basedir: dir }); + t.equal(b, path.join(dir, 'index.js')); +}); diff --git a/node_modules/resolve/test/dotdot/abc/index.js b/node_modules/resolve/test/dotdot/abc/index.js new file mode 100644 index 0000000000000000000000000000000000000000..67f2534ebf90dcc4c2c1c13ce3ab52c41f4d2ed9 --- /dev/null +++ b/node_modules/resolve/test/dotdot/abc/index.js @@ -0,0 +1,2 @@ +var x = require('..'); +console.log(x); diff --git a/node_modules/resolve/test/dotdot/index.js b/node_modules/resolve/test/dotdot/index.js new file mode 100644 index 0000000000000000000000000000000000000000..643f9fcc6a6a7cf025dcc86559e83d00b993ed96 --- /dev/null +++ b/node_modules/resolve/test/dotdot/index.js @@ -0,0 +1 @@ +module.exports = 'whatever'; diff --git a/node_modules/resolve/test/faulty_basedir.js b/node_modules/resolve/test/faulty_basedir.js new file mode 100644 index 0000000000000000000000000000000000000000..5f2141a67267bceaf743ab292ca8e7bebb2b6bbc --- /dev/null +++ b/node_modules/resolve/test/faulty_basedir.js @@ -0,0 +1,29 @@ +var test = require('tape'); +var path = require('path'); +var resolve = require('../'); + +test('faulty basedir must produce error in windows', { skip: process.platform !== 'win32' }, function (t) { + t.plan(1); + + var resolverDir = 'C:\\a\\b\\c\\d'; + + resolve('tape/lib/test.js', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(!!err, true); + }); +}); + +test('non-existent basedir should not throw when preserveSymlinks is false', function (t) { + t.plan(2); + + var opts = { + basedir: path.join(path.sep, 'unreal', 'path', 'that', 'does', 'not', 'exist'), + preserveSymlinks: false + }; + + var module = './dotdot/abc'; + + resolve(module, opts, function (err, res) { + t.equal(err.code, 'MODULE_NOT_FOUND'); + t.equal(res, undefined); + }); +}); diff --git a/node_modules/resolve/test/filter.js b/node_modules/resolve/test/filter.js new file mode 100644 index 0000000000000000000000000000000000000000..8f8cccdb2f59f3ea03a27151da52f73ed9f068de --- /dev/null +++ b/node_modules/resolve/test/filter.js @@ -0,0 +1,34 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('filter', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + var packageFilterArgs; + resolve('./baz', { + basedir: dir, + packageFilter: function (pkg, pkgfile) { + pkg.main = 'doom'; // eslint-disable-line no-param-reassign + packageFilterArgs = [pkg, pkgfile]; + return pkg; + } + }, function (err, res, pkg) { + if (err) t.fail(err); + + t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works'); + + var packageData = packageFilterArgs[0]; + t.equal(pkg, packageData, 'first packageFilter argument is "pkg"'); + t.equal(packageData.main, 'doom', 'package "main" was altered'); + + var packageFile = packageFilterArgs[1]; + t.equal( + packageFile, + path.join(dir, 'baz/package.json'), + 'second packageFilter argument is "pkgfile"' + ); + + t.end(); + }); +}); diff --git a/node_modules/resolve/test/filter_sync.js b/node_modules/resolve/test/filter_sync.js new file mode 100644 index 0000000000000000000000000000000000000000..8a43b9818973dfba95a2389f27e966ff4f315343 --- /dev/null +++ b/node_modules/resolve/test/filter_sync.js @@ -0,0 +1,33 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('filter', function (t) { + var dir = path.join(__dirname, 'resolver'); + var packageFilterArgs; + var res = resolve.sync('./baz', { + basedir: dir, + // NOTE: in v2.x, this will be `pkg, pkgfile, dir`, but must remain "broken" here in v1.x for compatibility + packageFilter: function (pkg, /*pkgfile,*/ dir) { // eslint-disable-line spaced-comment + pkg.main = 'doom'; // eslint-disable-line no-param-reassign + packageFilterArgs = 'is 1.x' ? [pkg, dir] : [pkg, pkgfile, dir]; // eslint-disable-line no-constant-condition, no-undef + return pkg; + } + }); + + t.equal(res, path.join(dir, 'baz/doom.js'), 'changing the package "main" works'); + + var packageData = packageFilterArgs[0]; + t.equal(packageData.main, 'doom', 'package "main" was altered'); + + if (!'is 1.x') { // eslint-disable-line no-constant-condition + var packageFile = packageFilterArgs[1]; + t.equal(packageFile, path.join(dir, 'baz', 'package.json'), 'package.json path is correct'); + } + + var packageDir = packageFilterArgs['is 1.x' ? 1 : 2]; // eslint-disable-line no-constant-condition + // eslint-disable-next-line no-constant-condition + t.equal(packageDir, path.join(dir, 'baz'), ('is 1.x' ? 'second' : 'third') + ' packageFilter argument is "dir"'); + + t.end(); +}); diff --git a/node_modules/resolve/test/home_paths.js b/node_modules/resolve/test/home_paths.js new file mode 100644 index 0000000000000000000000000000000000000000..3b8c9b32c87bd73fb2a3ec42494d13faae1594e4 --- /dev/null +++ b/node_modules/resolve/test/home_paths.js @@ -0,0 +1,127 @@ +'use strict'; + +var fs = require('fs'); +var homedir = require('../lib/homedir'); +var path = require('path'); + +var test = require('tape'); +var mkdirp = require('mkdirp'); +var rimraf = require('rimraf'); +var mv = require('mv'); +var copyDir = require('copy-dir'); +var tmp = require('tmp'); + +var HOME = homedir(); + +var hnm = path.join(HOME, '.node_modules'); +var hnl = path.join(HOME, '.node_libraries'); + +var resolve = require('../async'); + +function makeDir(t, dir, cb) { + mkdirp(dir, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function cleanup() { + rimraf.sync(dir); + }); + cb(); + } + }); +} + +function makeTempDir(t, dir, cb) { + if (fs.existsSync(dir)) { + var tmpResult = tmp.dirSync(); + t.teardown(tmpResult.removeCallback); + var backup = path.join(tmpResult.name, path.basename(dir)); + mv(dir, backup, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function () { + mv(backup, dir, cb); + }); + makeDir(t, dir, cb); + } + }); + } else { + makeDir(t, dir, cb); + } +} + +test('homedir module paths', function (t) { + t.plan(7); + + makeTempDir(t, hnm, function (err) { + t.error(err, 'no error with HNM temp dir'); + if (err) { + return t.end(); + } + + var bazHNMDir = path.join(hnm, 'baz'); + var dotMainDir = path.join(hnm, 'dot_main'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNMDir); + copyDir.sync(path.join(__dirname, 'resolver/dot_main'), dotMainDir); + + var bazPkg = { name: 'baz', main: 'quux.js' }; + var dotMainPkg = { main: 'index' }; + + var bazHNMmain = path.join(bazHNMDir, 'quux.js'); + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + var dotMainMain = path.join(dotMainDir, 'index.js'); + t.equal(require.resolve('dot_main'), dotMainMain, 'sanity check: require.resolve finds `dot_main`'); + + makeTempDir(t, hnl, function (err) { + t.error(err, 'no error with HNL temp dir'); + if (err) { + return t.end(); + } + var bazHNLDir = path.join(hnl, 'baz'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNLDir); + + var dotSlashMainDir = path.join(hnl, 'dot_slash_main'); + var dotSlashMainMain = path.join(dotSlashMainDir, 'index.js'); + var dotSlashMainPkg = { main: 'index' }; + copyDir.sync(path.join(__dirname, 'resolver/dot_slash_main'), dotSlashMainDir); + + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + t.equal(require.resolve('dot_slash_main'), dotSlashMainMain, 'sanity check: require.resolve finds HNL `dot_slash_main`'); + + t.test('with temp dirs', function (st) { + st.plan(3); + + st.test('just in `$HOME/.node_modules`', function (s2t) { + s2t.plan(3); + + resolve('dot_main', function (err, res, pkg) { + s2t.error(err, 'no error resolving `dot_main`'); + s2t.equal(res, dotMainMain, '`dot_main` resolves in `$HOME/.node_modules`'); + s2t.deepEqual(pkg, dotMainPkg); + }); + }); + + st.test('just in `$HOME/.node_libraries`', function (s2t) { + s2t.plan(3); + + resolve('dot_slash_main', function (err, res, pkg) { + s2t.error(err, 'no error resolving `dot_slash_main`'); + s2t.equal(res, dotSlashMainMain, '`dot_slash_main` resolves in `$HOME/.node_libraries`'); + s2t.deepEqual(pkg, dotSlashMainPkg); + }); + }); + + st.test('in `$HOME/.node_libraries` and `$HOME/.node_modules`', function (s2t) { + s2t.plan(3); + + resolve('baz', function (err, res, pkg) { + s2t.error(err, 'no error resolving `baz`'); + s2t.equal(res, bazHNMmain, '`baz` resolves in `$HOME/.node_modules` when in both'); + s2t.deepEqual(pkg, bazPkg); + }); + }); + }); + }); + }); +}); diff --git a/node_modules/resolve/test/home_paths_sync.js b/node_modules/resolve/test/home_paths_sync.js new file mode 100644 index 0000000000000000000000000000000000000000..5d2c56fd35d0a3ad072c3549f12695c93654aaed --- /dev/null +++ b/node_modules/resolve/test/home_paths_sync.js @@ -0,0 +1,114 @@ +'use strict'; + +var fs = require('fs'); +var homedir = require('../lib/homedir'); +var path = require('path'); + +var test = require('tape'); +var mkdirp = require('mkdirp'); +var rimraf = require('rimraf'); +var mv = require('mv'); +var copyDir = require('copy-dir'); +var tmp = require('tmp'); + +var HOME = homedir(); + +var hnm = path.join(HOME, '.node_modules'); +var hnl = path.join(HOME, '.node_libraries'); + +var resolve = require('../sync'); + +function makeDir(t, dir, cb) { + mkdirp(dir, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function cleanup() { + rimraf.sync(dir); + }); + cb(); + } + }); +} + +function makeTempDir(t, dir, cb) { + if (fs.existsSync(dir)) { + var tmpResult = tmp.dirSync(); + t.teardown(tmpResult.removeCallback); + var backup = path.join(tmpResult.name, path.basename(dir)); + mv(dir, backup, function (err) { + if (err) { + cb(err); + } else { + t.teardown(function () { + mv(backup, dir, cb); + }); + makeDir(t, dir, cb); + } + }); + } else { + makeDir(t, dir, cb); + } +} + +test('homedir module paths', function (t) { + t.plan(7); + + makeTempDir(t, hnm, function (err) { + t.error(err, 'no error with HNM temp dir'); + if (err) { + return t.end(); + } + + var bazHNMDir = path.join(hnm, 'baz'); + var dotMainDir = path.join(hnm, 'dot_main'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNMDir); + copyDir.sync(path.join(__dirname, 'resolver/dot_main'), dotMainDir); + + var bazHNMmain = path.join(bazHNMDir, 'quux.js'); + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + var dotMainMain = path.join(dotMainDir, 'index.js'); + t.equal(require.resolve('dot_main'), dotMainMain, 'sanity check: require.resolve finds `dot_main`'); + + makeTempDir(t, hnl, function (err) { + t.error(err, 'no error with HNL temp dir'); + if (err) { + return t.end(); + } + var bazHNLDir = path.join(hnl, 'baz'); + copyDir.sync(path.join(__dirname, 'resolver/baz'), bazHNLDir); + + var dotSlashMainDir = path.join(hnl, 'dot_slash_main'); + var dotSlashMainMain = path.join(dotSlashMainDir, 'index.js'); + copyDir.sync(path.join(__dirname, 'resolver/dot_slash_main'), dotSlashMainDir); + + t.equal(require.resolve('baz'), bazHNMmain, 'sanity check: require.resolve finds HNM `baz`'); + t.equal(require.resolve('dot_slash_main'), dotSlashMainMain, 'sanity check: require.resolve finds HNL `dot_slash_main`'); + + t.test('with temp dirs', function (st) { + st.plan(3); + + st.test('just in `$HOME/.node_modules`', function (s2t) { + s2t.plan(1); + + var res = resolve('dot_main'); + s2t.equal(res, dotMainMain, '`dot_main` resolves in `$HOME/.node_modules`'); + }); + + st.test('just in `$HOME/.node_libraries`', function (s2t) { + s2t.plan(1); + + var res = resolve('dot_slash_main'); + s2t.equal(res, dotSlashMainMain, '`dot_slash_main` resolves in `$HOME/.node_libraries`'); + }); + + st.test('in `$HOME/.node_libraries` and `$HOME/.node_modules`', function (s2t) { + s2t.plan(1); + + var res = resolve('baz'); + s2t.equal(res, bazHNMmain, '`baz` resolves in `$HOME/.node_modules` when in both'); + }); + }); + }); + }); +}); diff --git a/node_modules/resolve/test/homedir.js b/node_modules/resolve/test/homedir.js new file mode 100644 index 0000000000000000000000000000000000000000..b64bce7250f2f8e1b3d44893f7ab03427875edbc --- /dev/null +++ b/node_modules/resolve/test/homedir.js @@ -0,0 +1,112 @@ +'use strict'; + +var os = require('os'); +var test = require('tape'); +var mockProperty = require('mock-property'); + +var envKeys = ['HOME', 'USERPROFILE', 'HOMEDRIVE', 'HOMEPATH', 'LOGNAME', 'USER', 'LNAME', 'USERNAME']; + +function mockEnv(t, key, value) { + var has = key in process.env; + var orig = process.env[key]; + if (arguments.length > 2) { + process.env[key] = value; + } else { + delete process.env[key]; + } + t.teardown(function () { + if (has) { + process.env[key] = orig; + } else { + delete process.env[key]; + } + }); +} + +function clearEnv(t) { + for (var i = 0; i < envKeys.length; i++) { + mockEnv(t, envKeys[i]); + } +} + +function getFallback(t) { + t.teardown(mockProperty(os, 'homedir', { value: undefined })); + + var homedirPath = require.resolve('../lib/homedir'); + t.teardown(mockProperty(require.cache, homedirPath, { 'delete': true })); + + return require('../lib/homedir'); +} + +test('homedir fallback', function (t) { + t.test('win32: HOMEDRIVE without HOMEPATH does not produce a false concatenation', function (st) { + clearEnv(st); + st.teardown(mockProperty(process, 'platform', { value: 'win32' })); + + var homedir = getFallback(st); + + mockEnv(st, 'HOMEDRIVE', 'C:'); + + st.equal(homedir(), null, 'returns null when only HOMEDRIVE is set'); + + st.end(); + }); + + t.test('win32: HOMEPATH without HOMEDRIVE does not produce a false concatenation', function (st) { + clearEnv(st); + st.teardown(mockProperty(process, 'platform', { value: 'win32' })); + + var homedir = getFallback(st); + + mockEnv(st, 'HOMEPATH', '\\Users\\foo'); + + st.equal(homedir(), null, 'returns null when only HOMEPATH is set'); + + st.end(); + }); + + t.test('win32: HOMEDRIVE + HOMEPATH both set returns concatenation', function (st) { + clearEnv(st); + st.teardown(mockProperty(process, 'platform', { value: 'win32' })); + + var homedir = getFallback(st); + + mockEnv(st, 'HOMEDRIVE', 'C:'); + mockEnv(st, 'HOMEPATH', '\\Users\\foo'); + + st.equal(homedir(), 'C:\\Users\\foo', 'returns concatenated drive and path'); + + st.end(); + }); + + t.test('win32: USERPROFILE takes precedence over HOMEDRIVE+HOMEPATH', function (st) { + clearEnv(st); + st.teardown(mockProperty(process, 'platform', { value: 'win32' })); + + var homedir = getFallback(st); + + mockEnv(st, 'USERPROFILE', 'C:\\Users\\bar'); + mockEnv(st, 'HOMEDRIVE', 'C:'); + mockEnv(st, 'HOMEPATH', '\\Users\\foo'); + + st.equal(homedir(), 'C:\\Users\\bar', 'returns USERPROFILE'); + + st.end(); + }); + + t.test('win32: falls back to HOME when HOMEDRIVE/HOMEPATH are partial', function (st) { + clearEnv(st); + st.teardown(mockProperty(process, 'platform', { value: 'win32' })); + + var homedir = getFallback(st); + + mockEnv(st, 'HOME', 'C:\\Users\\baz'); + mockEnv(st, 'HOMEDRIVE', 'C:'); + + st.equal(homedir(), 'C:\\Users\\baz', 'falls back to HOME'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/resolve/test/mock.js b/node_modules/resolve/test/mock.js new file mode 100644 index 0000000000000000000000000000000000000000..2b95e38841f160d739c36462f05fc30cf779d058 --- /dev/null +++ b/node_modules/resolve/test/mock.js @@ -0,0 +1,353 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('mock', function (t) { + t.plan(8); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('../baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('mock from package', function (t) { + t.plan(8); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, file)); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[file]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg && pkg.main, 'bar'); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/baz.js')); + t.equal(pkg && pkg.main, 'bar'); + }); + + resolve('baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module 'baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('../baz', opts('/foo/bar'), function (err, res) { + t.equal(err.message, "Cannot find module '../baz' from '" + path.resolve('/foo/bar') + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('mock package', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('bar', opts('/foo'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + t.equal(pkg && pkg.main, './baz.js'); + }); +}); + +test('mock package from package', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + resolve('bar', opts('/foo'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + t.equal(pkg && pkg.main, './baz.js'); + }); +}); + +test('symlinked', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + dirs[path.resolve('/foo/bar/symlinked')] = true; + + function opts(basedir) { + return { + preserveSymlinks: false, + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + var resolved = path.resolve(file); + + if (resolved.indexOf('symlinked') >= 0) { + cb(null, resolved); + return; + } + + var ext = path.extname(resolved); + + if (ext) { + var dir = path.dirname(resolved); + var base = path.basename(resolved); + cb(null, path.join(dir, 'symlinked', base)); + } else { + cb(null, path.join(resolved, 'symlinked')); + } + } + }; + } + + resolve('./baz', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/symlinked/baz.js')); + t.equal(pkg, undefined); + }); + + resolve('./baz.js', opts('/foo/bar'), function (err, res, pkg) { + if (err) return t.fail(err); + t.equal(res, path.resolve('/foo/bar/symlinked/baz.js')); + t.equal(pkg, undefined); + }); +}); + +test('readPackage', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop'; + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(files, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!dirs[path.resolve(dir)]); + }, + 'package': { main: 'bar' }, + readFile: function (file, cb) { + cb(null, files[path.resolve(file)]); + }, + realpath: function (file, cb) { + cb(null, file); + } + }; + } + + t.test('with readFile', function (st) { + st.plan(3); + + resolve('bar', opts('/foo'), function (err, res, pkg) { + st.error(err); + st.equal(res, path.resolve('/foo/node_modules/bar/baz.js')); + st.equal(pkg && pkg.main, './baz.js'); + }); + }); + + function readPackage(readFile, file, cb) { + var barPackage = path.join('bar', 'package.json'); + if (file.slice(-barPackage.length) === barPackage) { + cb(null, { main: './something-else.js' }); + } else { + cb(null, JSON.parse(files[path.resolve(file)])); + } + } + + t.test('with readPackage', function (st) { + st.plan(3); + + var options = opts('/foo'); + delete options.readFile; + options.readPackage = readPackage; + resolve('bar', options, function (err, res, pkg) { + st.error(err); + st.equal(res, path.resolve('/foo/node_modules/bar/something-else.js')); + st.equal(pkg && pkg.main, './something-else.js'); + }); + }); + + t.test('with readFile and readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + options.readPackage = readPackage; + resolve('bar', options, function (err) { + st.throws(function () { throw err; }, TypeError, 'errors when both readFile and readPackage are provided'); + }); + }); + + t.test('readPackage error in loadpkg does not invoke callback twice', function (st) { + st.plan(1); + + var callCount = 0; + var readPackageError = new Error('read package error'); + + function failReadPackage(rf, file, cb) { + cb(readPackageError); + } + + var relFiles = {}; + relFiles[path.resolve('/foo/bar/baz.js')] = 'beep'; + relFiles[path.resolve('/foo/bar/package.json')] = '{}'; + + var relDirs = {}; + relDirs[path.resolve('/foo/bar')] = true; + + resolve('./baz', { + basedir: path.resolve('/foo/bar'), + isFile: function (file, cb) { + cb(null, Object.prototype.hasOwnProperty.call(relFiles, path.resolve(file))); + }, + isDirectory: function (dir, cb) { + cb(null, !!relDirs[path.resolve(dir)]); + }, + readPackage: failReadPackage, + realpath: function (file, cb) { + cb(null, file); + } + }, function () { + callCount += 1; + }); + + setTimeout(function () { + st.equal(callCount, 1, 'callback is invoked exactly once'); + }, 50); + }); +}); diff --git a/node_modules/resolve/test/mock_sync.js b/node_modules/resolve/test/mock_sync.js new file mode 100644 index 0000000000000000000000000000000000000000..3456cab00383f64f262831b39bec083adcd75ae1 --- /dev/null +++ b/node_modules/resolve/test/mock_sync.js @@ -0,0 +1,234 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('mock', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + + t.equal( + resolve.sync('./baz', opts('/foo/bar')), + path.resolve('/foo/bar/baz.js') + ); + + t.equal( + resolve.sync('./baz.js', opts('/foo/bar')), + path.resolve('/foo/bar/baz.js') + ); + + t.throws(function () { + resolve.sync('baz', opts('/foo/bar')); + }); + + t.throws(function () { + resolve.sync('../baz', opts('/foo/bar')); + }); +}); + +test('mock package', function (t) { + t.plan(1); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + + t.equal( + resolve.sync('bar', opts('/foo')), + path.resolve('/foo/node_modules/bar/baz.js') + ); +}); + +test('symlinked', function (t) { + t.plan(2); + + var files = {}; + files[path.resolve('/foo/bar/baz.js')] = 'beep'; + files[path.resolve('/foo/bar/symlinked/baz.js')] = 'beep'; + + var dirs = {}; + dirs[path.resolve('/foo/bar')] = true; + dirs[path.resolve('/foo/bar/symlinked')] = true; + + function opts(basedir) { + return { + preserveSymlinks: false, + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + var resolved = path.resolve(file); + + if (resolved.indexOf('symlinked') >= 0) { + return resolved; + } + + var ext = path.extname(resolved); + + if (ext) { + var dir = path.dirname(resolved); + var base = path.basename(resolved); + return path.join(dir, 'symlinked', base); + } + return path.join(resolved, 'symlinked'); + } + }; + } + + t.equal( + resolve.sync('./baz', opts('/foo/bar')), + path.resolve('/foo/bar/symlinked/baz.js') + ); + + t.equal( + resolve.sync('./baz.js', opts('/foo/bar')), + path.resolve('/foo/bar/symlinked/baz.js') + ); +}); + +test('readPackageSync', function (t) { + t.plan(4); + + var files = {}; + files[path.resolve('/foo/node_modules/bar/something-else.js')] = 'beep'; + files[path.resolve('/foo/node_modules/bar/package.json')] = JSON.stringify({ + main: './baz.js' + }); + files[path.resolve('/foo/node_modules/bar/baz.js')] = 'boop'; + + var dirs = {}; + dirs[path.resolve('/foo')] = true; + dirs[path.resolve('/foo/node_modules')] = true; + + function opts(basedir, useReadPackage) { + return { + basedir: path.resolve(basedir), + isFile: function (file) { + return Object.prototype.hasOwnProperty.call(files, path.resolve(file)); + }, + isDirectory: function (dir) { + return !!dirs[path.resolve(dir)]; + }, + readFileSync: useReadPackage ? null : function (file) { + return files[path.resolve(file)]; + }, + realpathSync: function (file) { + return file; + } + }; + } + t.test('with readFile', function (st) { + st.plan(1); + + st.equal( + resolve.sync('bar', opts('/foo')), + path.resolve('/foo/node_modules/bar/baz.js') + ); + }); + + function readPackageSync(readFileSync, file) { + if (file.indexOf(path.join('bar', 'package.json')) >= 0) { + return { main: './something-else.js' }; + } + return JSON.parse(files[path.resolve(file)]); + } + + t.test('with readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + delete options.readFileSync; + options.readPackageSync = readPackageSync; + + st.equal( + resolve.sync('bar', options), + path.resolve('/foo/node_modules/bar/something-else.js') + ); + }); + + t.test('with readFile and readPackage', function (st) { + st.plan(1); + + var options = opts('/foo'); + options.readPackageSync = readPackageSync; + st.throws( + function () { resolve.sync('bar', options); }, + TypeError, + 'errors when both readFile and readPackage are provided' + ); + }); + + t.test('readPackageSync error propagates correctly', function (st) { + st.plan(1); + + var readPackageError = new Error('read package error'); + + function failReadPackageSync() { + throw readPackageError; + } + + var options = opts('/foo'); + delete options.readFileSync; + options.readPackageSync = failReadPackageSync; + + st.throws( + function () { resolve.sync('bar', options); }, + readPackageError, + 'readPackageSync error is thrown' + ); + }); +}); + diff --git a/node_modules/resolve/test/module_dir.js b/node_modules/resolve/test/module_dir.js new file mode 100644 index 0000000000000000000000000000000000000000..b50e5bb1751d69694deaae36d5f0bc6691498008 --- /dev/null +++ b/node_modules/resolve/test/module_dir.js @@ -0,0 +1,56 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('moduleDirectory strings', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'module_dir'); + var xopts = { + basedir: dir, + moduleDirectory: 'xmodules' + }; + resolve('aaa', xopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/xmodules/aaa/index.js')); + }); + + var yopts = { + basedir: dir, + moduleDirectory: 'ymodules' + }; + resolve('aaa', yopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/ymodules/aaa/index.js')); + }); +}); + +test('moduleDirectory array', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'module_dir'); + var aopts = { + basedir: dir, + moduleDirectory: ['xmodules', 'ymodules', 'zmodules'] + }; + resolve('aaa', aopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/xmodules/aaa/index.js')); + }); + + var bopts = { + basedir: dir, + moduleDirectory: ['zmodules', 'ymodules', 'xmodules'] + }; + resolve('aaa', bopts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/ymodules/aaa/index.js')); + }); + + var copts = { + basedir: dir, + moduleDirectory: ['xmodules', 'ymodules', 'zmodules'] + }; + resolve('bbb', copts, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, '/zmodules/bbb/main.js')); + }); +}); diff --git a/node_modules/resolve/test/module_dir/xmodules/aaa/index.js b/node_modules/resolve/test/module_dir/xmodules/aaa/index.js new file mode 100644 index 0000000000000000000000000000000000000000..dd7cf7b2d022daae3c3f7628fcfb2f8bf186efac --- /dev/null +++ b/node_modules/resolve/test/module_dir/xmodules/aaa/index.js @@ -0,0 +1 @@ +module.exports = function (x) { return x * 100; }; diff --git a/node_modules/resolve/test/module_dir/ymodules/aaa/index.js b/node_modules/resolve/test/module_dir/ymodules/aaa/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ef2d4d4bf76e61fdfe16ef406c9752c6435138f3 --- /dev/null +++ b/node_modules/resolve/test/module_dir/ymodules/aaa/index.js @@ -0,0 +1 @@ +module.exports = function (x) { return x + 100; }; diff --git a/node_modules/resolve/test/module_dir/zmodules/bbb/main.js b/node_modules/resolve/test/module_dir/zmodules/bbb/main.js new file mode 100644 index 0000000000000000000000000000000000000000..e8ba629936a7ad11134ac826edfad2379759c7cb --- /dev/null +++ b/node_modules/resolve/test/module_dir/zmodules/bbb/main.js @@ -0,0 +1 @@ +module.exports = function (n) { return n * 111; }; diff --git a/node_modules/resolve/test/module_dir/zmodules/bbb/package.json b/node_modules/resolve/test/module_dir/zmodules/bbb/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c13b8cf6acfd3344bc2c7969a31d930d933fdf22 --- /dev/null +++ b/node_modules/resolve/test/module_dir/zmodules/bbb/package.json @@ -0,0 +1,3 @@ +{ + "main": "main.js" +} diff --git a/node_modules/resolve/test/node-modules-paths.js b/node_modules/resolve/test/node-modules-paths.js new file mode 100644 index 0000000000000000000000000000000000000000..ed0a8b822d323c2616f20d63baa21c2ec638f704 --- /dev/null +++ b/node_modules/resolve/test/node-modules-paths.js @@ -0,0 +1,143 @@ +var test = require('tape'); +var path = require('path'); +var parse = path.parse || require('path-parse'); +var keys = require('object-keys'); + +var nodeModulesPaths = require('../lib/node-modules-paths'); + +function verifyDirs(t, start, dirs, moduleDirectories, paths) { + var moduleDirs = [].concat(moduleDirectories || 'node_modules'); + if (paths) { + for (var k = 0; k < paths.length; ++k) { + moduleDirs.push(path.basename(paths[k])); + } + } + + var foundModuleDirs = {}; + var uniqueDirs = {}; + var parsedDirs = {}; + for (var i = 0; i < dirs.length; ++i) { + var parsed = parse(dirs[i]); + if (!foundModuleDirs[parsed.base]) { foundModuleDirs[parsed.base] = 0; } + foundModuleDirs[parsed.base] += 1; + parsedDirs[parsed.dir] = true; + uniqueDirs[dirs[i]] = true; + } + t.equal(keys(parsedDirs).length >= start.split(path.sep).length, true, 'there are >= dirs than "start" has'); + var foundModuleDirNames = keys(foundModuleDirs); + t.deepEqual(foundModuleDirNames, moduleDirs, 'all desired module dirs were found'); + t.equal(keys(uniqueDirs).length, dirs.length, 'all dirs provided were unique'); + + var counts = {}; + for (var j = 0; j < foundModuleDirNames.length; ++j) { + counts[foundModuleDirs[j]] = true; + } + t.equal(keys(counts).length, 1, 'all found module directories had the same count'); +} + +test('node-modules-paths', function (t) { + t.test('no options', function (t) { + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start); + + verifyDirs(t, start, dirs); + + t.end(); + }); + + t.test('empty options', function (t) { + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, {}); + + verifyDirs(t, start, dirs); + + t.end(); + }); + + t.test('with paths=array option', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var dirs = nodeModulesPaths(start, { paths: paths }); + + verifyDirs(t, start, dirs, null, paths); + + t.end(); + }); + + t.test('with paths=function option', function (t) { + function paths(request, absoluteStart, getNodeModulesDirs, opts) { + return getNodeModulesDirs().concat(path.join(absoluteStart, 'not node modules', request)); + } + + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, { paths: paths }, 'pkg'); + + verifyDirs(t, start, dirs, null, [path.join(start, 'not node modules', 'pkg')]); + + t.end(); + }); + + t.test('with paths=function skipping node modules resolution', function (t) { + function paths(request, absoluteStart, getNodeModulesDirs, opts) { + return []; + } + var start = path.join(__dirname, 'resolver'); + var dirs = nodeModulesPaths(start, { paths: paths }); + t.deepEqual(dirs, [], 'no node_modules was computed'); + t.end(); + }); + + t.test('with moduleDirectory option', function (t) { + var start = path.join(__dirname, 'resolver'); + var moduleDirectory = 'not node modules'; + var dirs = nodeModulesPaths(start, { moduleDirectory: moduleDirectory }); + + verifyDirs(t, start, dirs, moduleDirectory); + + t.end(); + }); + + t.test('with 1 moduleDirectory and paths options', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var moduleDirectory = 'not node modules'; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectory }); + + verifyDirs(t, start, dirs, moduleDirectory, paths); + + t.end(); + }); + + t.test('with 1+ moduleDirectory and paths options', function (t) { + var start = path.join(__dirname, 'resolver'); + var paths = ['a', 'b']; + var moduleDirectories = ['not node modules', 'other modules']; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + verifyDirs(t, start, dirs, moduleDirectories, paths); + + t.end(); + }); + + t.test('combine paths correctly on Windows', function (t) { + var start = 'C:\\Users\\username\\myProject\\src'; + var paths = []; + var moduleDirectories = ['node_modules', start]; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir'); + + t.end(); + }); + + t.test('combine paths correctly on non-Windows', { skip: process.platform === 'win32' }, function (t) { + var start = '/Users/username/git/myProject/src'; + var paths = []; + var moduleDirectories = ['node_modules', '/Users/username/git/myProject/src']; + var dirs = nodeModulesPaths(start, { paths: paths, moduleDirectory: moduleDirectories }); + + t.equal(dirs.indexOf(path.resolve(start)) > -1, true, 'should contain start dir'); + + t.end(); + }); +}); diff --git a/node_modules/resolve/test/node_path.js b/node_modules/resolve/test/node_path.js new file mode 100644 index 0000000000000000000000000000000000000000..5ddd3101ba68837a696d4489be83582a6ac70190 --- /dev/null +++ b/node_modules/resolve/test/node_path.js @@ -0,0 +1,70 @@ +var fs = require('fs'); +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('$NODE_PATH', function (t) { + t.plan(8); + + function isDir(dir, cb) { + if (dir === '/node_path' || dir === 'node_path/x') { + return cb(null, true); + } + fs.stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); + } + + resolve('aaa', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/x/aaa/index.js'), 'aaa resolves'); + }); + + resolve('bbb', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/y/bbb/index.js'), 'bbb resolves'); + }); + + resolve('ccc', { + paths: [ + path.join(__dirname, '/node_path/x'), + path.join(__dirname, '/node_path/y') + ], + basedir: __dirname, + isDirectory: isDir + }, function (err, res) { + t.error(err); + t.equal(res, path.join(__dirname, '/node_path/x/ccc/index.js'), 'ccc resolves'); + }); + + // ensure that relative paths still resolve against the regular `node_modules` correctly + resolve('tap', { + paths: [ + 'node_path' + ], + basedir: path.join(__dirname, 'node_path/x'), + isDirectory: isDir + }, function (err, res) { + var root = require('tap/package.json').main; // eslint-disable-line global-require + t.error(err); + t.equal(res, path.resolve(__dirname, '..', 'node_modules/tap', root), 'tap resolves'); + }); +}); diff --git a/node_modules/resolve/test/node_path/x/aaa/index.js b/node_modules/resolve/test/node_path/x/aaa/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ad70d0bb03f6f433224a681f9055fe9d0a388dfc --- /dev/null +++ b/node_modules/resolve/test/node_path/x/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'A'; diff --git a/node_modules/resolve/test/node_path/x/ccc/index.js b/node_modules/resolve/test/node_path/x/ccc/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a64132e4c7e52cfea76744d826e99932e994c7c1 --- /dev/null +++ b/node_modules/resolve/test/node_path/x/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'C'; diff --git a/node_modules/resolve/test/node_path/y/bbb/index.js b/node_modules/resolve/test/node_path/y/bbb/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4d0f32e24368185d6f3c16445f88b902329025d6 --- /dev/null +++ b/node_modules/resolve/test/node_path/y/bbb/index.js @@ -0,0 +1 @@ +module.exports = 'B'; diff --git a/node_modules/resolve/test/node_path/y/ccc/index.js b/node_modules/resolve/test/node_path/y/ccc/index.js new file mode 100644 index 0000000000000000000000000000000000000000..793315e846687e1dd2bae012fc30676b2a421753 --- /dev/null +++ b/node_modules/resolve/test/node_path/y/ccc/index.js @@ -0,0 +1 @@ +module.exports = 'CY'; diff --git a/node_modules/resolve/test/nonstring.js b/node_modules/resolve/test/nonstring.js new file mode 100644 index 0000000000000000000000000000000000000000..ef63c40f9393dc63219d5e3debb7ed6db175c455 --- /dev/null +++ b/node_modules/resolve/test/nonstring.js @@ -0,0 +1,9 @@ +var test = require('tape'); +var resolve = require('../'); + +test('nonstring', function (t) { + t.plan(1); + resolve(555, function (err, res, pkg) { + t.ok(err); + }); +}); diff --git a/node_modules/resolve/test/pathfilter.js b/node_modules/resolve/test/pathfilter.js new file mode 100644 index 0000000000000000000000000000000000000000..02df3ffe8e8e29f8b567bacfaa1f6adaedebb1a1 --- /dev/null +++ b/node_modules/resolve/test/pathfilter.js @@ -0,0 +1,75 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +var resolverDir = path.join(__dirname, '/pathfilter/deep_ref'); + +function pathFilterFactory(t) { + return function (pkg, x, remainder) { + t.equal(pkg.version, '1.2.3'); + t.equal(x, path.join(resolverDir, 'node_modules/deep/ref')); + t.equal(remainder, 'ref'); + return 'alt'; + }; +} + +test('#62: deep module references and the pathFilter', function (t) { + t.test('deep/ref.js', function (st) { + st.plan(3); + + resolve('deep/ref', { basedir: resolverDir }, function (err, res, pkg) { + if (err) st.fail(err); + + st.equal(pkg.version, '1.2.3'); + st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js')); + }); + + var res = resolve.sync('deep/ref', { basedir: resolverDir }); + st.equal(res, path.join(resolverDir, 'node_modules/deep/ref.js')); + }); + + t.test('deep/deeper/ref', function (st) { + st.plan(4); + + resolve( + 'deep/deeper/ref', + { basedir: resolverDir }, + function (err, res, pkg) { + if (err) t.fail(err); + st.notEqual(pkg, undefined); + st.equal(pkg.version, '1.2.3'); + st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js')); + } + ); + + var res = resolve.sync( + 'deep/deeper/ref', + { basedir: resolverDir } + ); + st.equal(res, path.join(resolverDir, 'node_modules/deep/deeper/ref.js')); + }); + + t.test('deep/ref alt', function (st) { + st.plan(8); + + var pathFilter = pathFilterFactory(st); + + var res = resolve.sync( + 'deep/ref', + { basedir: resolverDir, pathFilter: pathFilter } + ); + st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js')); + + resolve( + 'deep/ref', + { basedir: resolverDir, pathFilter: pathFilter }, + function (err, res, pkg) { + if (err) st.fail(err); + st.equal(res, path.join(resolverDir, 'node_modules/deep/alt.js')); + st.end(); + } + ); + }); + + t.end(); +}); diff --git a/node_modules/resolve/test/pathfilter/deep_ref/main.js b/node_modules/resolve/test/pathfilter/deep_ref/main.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/pathfilter_sync.js b/node_modules/resolve/test/pathfilter_sync.js new file mode 100644 index 0000000000000000000000000000000000000000..b404d11dc6998e9f32feb2e205f4d4495da7fdf9 --- /dev/null +++ b/node_modules/resolve/test/pathfilter_sync.js @@ -0,0 +1,24 @@ +var test = require('tape'); +var path = require('path'); +var resolve = require('../'); + +test('synchronous pathfilter', function (t) { + var res; + var resolverDir = __dirname + '/pathfilter/deep_ref'; + function pathFilter(pkg, x, remainder) { + t.equal(pkg.version, '1.2.3'); + t.equal(x, path.join(resolverDir, 'node_modules', 'deep', 'ref')); + t.equal(remainder, 'ref'); + return 'alt'; + } + + res = resolve.sync('deep/ref', { basedir: resolverDir }); + t.equal(res, path.join(resolverDir, 'node_modules', 'deep', 'ref.js')); + + res = resolve.sync('deep/deeper/ref', { basedir: resolverDir }); + t.equal(res, path.join(resolverDir, 'node_modules', 'deep', 'deeper', 'ref.js')); + + res = resolve.sync('deep/ref', { basedir: resolverDir, pathFilter: pathFilter }); + t.equal(res, path.join(resolverDir, 'node_modules', 'deep', 'alt.js')); + t.end(); +}); diff --git a/node_modules/resolve/test/precedence.js b/node_modules/resolve/test/precedence.js new file mode 100644 index 0000000000000000000000000000000000000000..2febb598fbc06832ce5b076735cb9f79fb257c7c --- /dev/null +++ b/node_modules/resolve/test/precedence.js @@ -0,0 +1,23 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('precedence', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'precedence/aaa'); + + resolve('./', { basedir: dir }, function (err, res, pkg) { + t.ifError(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg.name, 'resolve'); + }); +}); + +test('./ should not load ${dir}.js', function (t) { // eslint-disable-line no-template-curly-in-string + t.plan(1); + var dir = path.join(__dirname, 'precedence/bbb'); + + resolve('./', { basedir: dir }, function (err, res, pkg) { + t.ok(err); + }); +}); diff --git a/node_modules/resolve/test/precedence/aaa.js b/node_modules/resolve/test/precedence/aaa.js new file mode 100644 index 0000000000000000000000000000000000000000..b83a3e7ad98d17536ebc574326276c0fe341b99a --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa.js @@ -0,0 +1 @@ +module.exports = 'wtf'; diff --git a/node_modules/resolve/test/precedence/aaa/index.js b/node_modules/resolve/test/precedence/aaa/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e0f8f6abf72f7fe517abf6c57fae219b831b1cc9 --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa/index.js @@ -0,0 +1 @@ +module.exports = 'okok'; diff --git a/node_modules/resolve/test/precedence/aaa/main.js b/node_modules/resolve/test/precedence/aaa/main.js new file mode 100644 index 0000000000000000000000000000000000000000..93542a965e0ea4fa1a548dcb4491e1defd73afe0 --- /dev/null +++ b/node_modules/resolve/test/precedence/aaa/main.js @@ -0,0 +1 @@ +console.log(require('./')); diff --git a/node_modules/resolve/test/precedence/bbb.js b/node_modules/resolve/test/precedence/bbb.js new file mode 100644 index 0000000000000000000000000000000000000000..2298f47fdd16dcc8375b62d1a15109a5833da926 --- /dev/null +++ b/node_modules/resolve/test/precedence/bbb.js @@ -0,0 +1 @@ +module.exports = '>_<'; diff --git a/node_modules/resolve/test/precedence/bbb/main.js b/node_modules/resolve/test/precedence/bbb/main.js new file mode 100644 index 0000000000000000000000000000000000000000..716b81d4bd463f66980f3cb44588b283bfb23edc --- /dev/null +++ b/node_modules/resolve/test/precedence/bbb/main.js @@ -0,0 +1 @@ +console.log(require('./')); // should throw diff --git a/node_modules/resolve/test/resolver.js b/node_modules/resolve/test/resolver.js new file mode 100644 index 0000000000000000000000000000000000000000..220fd3b7147322827560f4896fc016b10308bc48 --- /dev/null +++ b/node_modules/resolve/test/resolver.js @@ -0,0 +1,597 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); +var resolve = require('../'); +var async = require('../async'); + +test('`./async` entry point', function (t) { + t.equal(resolve, async, '`./async` entry point is the same as `main`'); + t.end(); +}); + +test('async foo', function (t) { + t.plan(12); + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo.js', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.name, 'resolve'); + }); + + resolve('./foo', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg && pkg.main, 'resolver'); + }); + + resolve('./foo.js', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + t.equal(pkg.main, 'resolver'); + }); + + resolve('./foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo.js')); + }); + + resolve('foo', { basedir: dir }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('foo', { basedir: dir, filename: path.join(dir, 'baz.js') }, function (err) { + t.equal(err.message, "Cannot find module 'foo' from '" + path.join(dir, 'baz.js') + "'"); + }); +}); + +test('bar', function (t) { + t.plan(6); + var dir = path.join(__dirname, 'resolver'); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg, undefined); + }); + + resolve('foo', { basedir: dir + '/bar', 'package': { main: 'bar' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'bar/node_modules/foo/index.js')); + t.equal(pkg.main, 'bar'); + }); +}); + +test('baz', function (t) { + t.plan(4); + var dir = path.join(__dirname, 'resolver'); + + resolve('./baz', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); + + resolve('./baz', { basedir: dir, 'package': { main: 'resolver' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'baz/quux.js')); + t.equal(pkg.main, 'quux.js'); + }); +}); + +test('biz', function (t) { + t.plan(24); + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + resolve('./grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('./grux', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'biz'); + }); + + resolve('./garply', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('./garply', { basedir: dir, 'package': { main: 'biz' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('tiv', { basedir: dir + '/grux' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/grux', 'package': { main: 'grux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, 'grux'); + }); + + resolve('tiv', { basedir: dir + '/garply' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg, undefined); + }); + + resolve('tiv', { basedir: dir + '/garply', 'package': { main: './lib' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'tiv/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('grux', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg, undefined); + }); + + resolve('grux', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'grux/index.js')); + t.equal(pkg.main, 'tiv'); + }); + + resolve('garply', { basedir: dir + '/tiv' }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); + + resolve('garply', { basedir: dir + '/tiv', 'package': { main: 'tiv' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'garply/lib/index.js')); + t.equal(pkg.main, './lib'); + }); +}); + +test('quux', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/quux'); + + resolve('./foo', { basedir: dir, 'package': { main: 'quux' } }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'foo/index.js')); + t.equal(pkg.main, 'quux'); + }); +}); + +test('normalize', function (t) { + t.plan(2); + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + resolve('../grux', { basedir: dir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + t.equal(pkg, undefined); + }); +}); + +test('cup', function (t) { + t.plan(5); + var dir = path.join(__dirname, 'resolver'); + + resolve('./cup', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup.coffee', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'cup.coffee')); + }); + + resolve('./cup', { basedir: dir, extensions: ['.js'] }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + // Test that filename is reported as the "from" value when passed. + resolve('./cup', { basedir: dir, extensions: ['.js'], filename: path.join(dir, 'cupboard.js') }, function (err, res) { + t.equal(err.message, "Cannot find module './cup' from '" + path.join(dir, 'cupboard.js') + "'"); + }); +}); + +test('mug', function (t) { + t.plan(3); + var dir = path.join(__dirname, 'resolver'); + + resolve('./mug', { basedir: dir }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'mug.js')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.coffee', '.js'] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(dir, '/mug.coffee')); + }); + + resolve('./mug', { basedir: dir, extensions: ['.js', '.coffee'] }, function (err, res) { + t.equal(res, path.join(dir, '/mug.js')); + }); +}); + +test('other path', function (t) { + t.plan(6); + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + resolve('root', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/root.js')); + }); + + resolve('lib/other-lib', { basedir: dir, paths: [otherDir] }, function (err, res) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'other_path/lib/other-lib.js')); + }); + + resolve('root', { basedir: dir }, function (err, res) { + t.equal(err.message, "Cannot find module 'root' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); + + resolve('zzz', { basedir: dir, paths: [otherDir] }, function (err, res) { + t.equal(err.message, "Cannot find module 'zzz' from '" + path.resolve(dir) + "'"); + t.equal(err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('path iterator', function (t) { + t.plan(2); + + var resolverDir = path.join(__dirname, 'resolver'); + + function exactIterator(x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + } + + resolve('baz', { packageIterator: exactIterator }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(resolverDir, 'baz/quux.js')); + t.equal(pkg && pkg.name, 'baz'); + }); +}); + +test('incorrect main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + resolve('./incorrect_main', { basedir: resolverDir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'index.js')); + }); +}); + +test('missing index', function (t) { + t.plan(2); + + var resolverDir = path.join(__dirname, 'resolver'); + resolve('./missing_index', { basedir: resolverDir }, function (err, res, pkg) { + t.ok(err instanceof Error); + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + }); +}); + +test('missing main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + + resolve('./missing_main', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + }); +}); + +test('null main', function (t) { + t.plan(1); + + var resolverDir = path.join(__dirname, 'resolver'); + + resolve('./null_main', { basedir: resolverDir }, function (err, res, pkg) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + }); +}); + +test('main: false', function (t) { + t.plan(2); + + var basedir = path.join(__dirname, 'resolver'); + var dir = path.join(basedir, 'false_main'); + resolve('./false_main', { basedir: basedir }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal( + res, + path.join(dir, 'index.js'), + '`"main": false`: resolves to `index.js`' + ); + t.deepEqual(pkg, { + name: 'false_main', + main: false + }); + }); +}); + +test('without basedir', function (t) { + t.plan(1); + + var dir = path.join(__dirname, 'resolver/without_basedir'); + var tester = require(path.join(dir, 'main.js')); // eslint-disable-line global-require + + tester(t, function (err, res, pkg) { + if (err) { + t.fail(err); + } else { + t.equal(res, path.join(dir, 'node_modules/mymodule.js')); + } + }); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./foo', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo.js')); + }); + + resolve('./foo/', { basedir: path.join(dir, 'same_names') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + t.plan(2); + + var dir = path.join(__dirname, 'resolver'); + + resolve('./', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); + + resolve('.', { basedir: path.join(dir, 'same_names/foo') }, function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'same_names/foo/index.js')); + }); +}); + +test('async: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.plan(1); + resolve('./' + testFile, function (err, res, pkg) { + if (err) t.fail(err); + st.equal(res, __filename, 'sanity check'); + }); + }); + + t.test('with a fake directory', function (st) { + st.plan(4); + + resolve('./' + testFile + '/blah', function (err, res, pkg) { + st.ok(err, 'there is an error'); + st.notOk(res, 'no result'); + + st.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + err && err.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + st.end(); + }); + }); + + t.end(); +}); + +test('async dot main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('async dot slash main', function (t) { + var start = new Date(); + t.plan(3); + resolve('./resolver/dot_slash_main', function (err, ret) { + t.notOk(err); + t.equal(ret, path.join(__dirname, 'resolver/dot_slash_main/index.js')); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); + }); +}); + +test('not a directory', function (t) { + t.plan(6); + var path = './foo'; + resolve(path, { basedir: __filename }, function (err, res, pkg) { + t.ok(err, 'a non-directory errors'); + t.equal(arguments.length, 1); + t.equal(res, undefined); + t.equal(pkg, undefined); + + t.equal(err && err.message, 'Cannot find module \'' + path + '\' from \'' + __filename + '\''); + t.equal(err && err.code, 'MODULE_NOT_FOUND'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('non-string "main" field in package.json', function (t) { + t.plan(5); + + var dir = path.join(__dirname, 'resolver'); + resolve('./invalid_main', { basedir: dir }, function (err, res, pkg) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + t.equal(res, undefined, 'res is undefined'); + t.equal(pkg, undefined, 'pkg is undefined'); + }); +}); + +test('browser field in package.json', function (t) { + t.plan(3); + + var dir = path.join(__dirname, 'resolver'); + resolve( + './browser_field', + { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }, + function (err, res, pkg) { + if (err) t.fail(err); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.equal(pkg && pkg.main, 'b'); + t.equal(pkg && pkg.browser, undefined); + } + ); +}); + +test('absolute paths', function (t) { + t.plan(4); + + var extensionless = __filename.slice(0, -path.extname(__filename).length); + + resolve(__filename, function (err, res) { + t.equal( + res, + __filename, + 'absolute path to this file resolves' + ); + }); + resolve(extensionless, function (err, res) { + t.equal( + res, + __filename, + 'extensionless absolute path to this file resolves' + ); + }); + resolve(__filename, { basedir: process.cwd() }, function (err, res) { + t.equal( + res, + __filename, + 'absolute path to this file with a basedir resolves' + ); + }); + resolve(extensionless, { basedir: process.cwd() }, function (err, res) { + t.equal( + res, + __filename, + 'extensionless absolute path to this file with a basedir resolves' + ); + }); +}); + +var malformedDir = path.join(__dirname, 'resolver/malformed_package_json'); +test('malformed package.json', { skip: !fs.existsSync(malformedDir) }, function (t) { + /* eslint operator-linebreak: ["error", "before"], function-paren-newline: "off" */ + t.plan( + (3 * 3) // 3 sets of 3 assertions in the final callback + + 2 // 1 readPackage call with malformed package.json + ); + + var basedir = malformedDir; + var expected = path.join(basedir, 'index.js'); + + resolve('./index.js', { basedir: basedir }, function (err, res, pkg) { + t.error(err, 'no error'); + t.equal(res, expected, 'malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'malformed package.json gives an undefined `pkg` argument'); + }); + + resolve( + './index.js', + { + basedir: basedir, + packageFilter: function (pkg, pkgfile, dir) { + t.fail('should not reach here'); + } + }, + function (err, res, pkg) { + t.error(err, 'with packageFilter: no error'); + t.equal(res, expected, 'with packageFilter: malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'with packageFilter: malformed package.json gives an undefined `pkg` argument'); + } + ); + + resolve( + './index.js', + { + basedir: basedir, + readPackage: function (readFile, pkgfile, cb) { + t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path'); + readFile(pkgfile, function (err, result) { + try { + cb(null, JSON.parse(result)); + } catch (e) { + t.ok(e instanceof SyntaxError, 'readPackage: malformed package.json parses as a syntax error'); + cb(null); + } + }); + } + }, + function (err, res, pkg) { + t.error(err, 'with readPackage: no error'); + t.equal(res, expected, 'with readPackage: malformed package.json is silently ignored'); + t.equal(pkg, undefined, 'with readPackage: malformed package.json gives an undefined `pkg` argument'); + } + ); +}); diff --git a/node_modules/resolve/test/resolver/baz/doom.js b/node_modules/resolve/test/resolver/baz/doom.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/resolver/baz/package.json b/node_modules/resolve/test/resolver/baz/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2f77720b8672a0e2ed8b49636775335884cb3ec0 --- /dev/null +++ b/node_modules/resolve/test/resolver/baz/package.json @@ -0,0 +1,4 @@ +{ + "name": "baz", + "main": "quux.js" +} diff --git a/node_modules/resolve/test/resolver/baz/quux.js b/node_modules/resolve/test/resolver/baz/quux.js new file mode 100644 index 0000000000000000000000000000000000000000..bd816eaba4ca3be8e4d68cfc0ae9f64b5aa712cc --- /dev/null +++ b/node_modules/resolve/test/resolver/baz/quux.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/browser_field/a.js b/node_modules/resolve/test/resolver/browser_field/a.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/resolver/browser_field/b.js b/node_modules/resolve/test/resolver/browser_field/b.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/resolver/browser_field/package.json b/node_modules/resolve/test/resolver/browser_field/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bf406f0830f8aab6aaec9e3f60f1623fbe6854e6 --- /dev/null +++ b/node_modules/resolve/test/resolver/browser_field/package.json @@ -0,0 +1,5 @@ +{ + "name": "browser_field", + "main": "a", + "browser": "b" +} diff --git a/node_modules/resolve/test/resolver/cup.coffee b/node_modules/resolve/test/resolver/cup.coffee new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/node_modules/resolve/test/resolver/cup.coffee @@ -0,0 +1 @@ + diff --git a/node_modules/resolve/test/resolver/dot_main/index.js b/node_modules/resolve/test/resolver/dot_main/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bd816eaba4ca3be8e4d68cfc0ae9f64b5aa712cc --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_main/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/dot_main/package.json b/node_modules/resolve/test/resolver/dot_main/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d7f4fc8079f60aaee820b293537b21d488a1bc31 --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "." +} diff --git a/node_modules/resolve/test/resolver/dot_slash_main/index.js b/node_modules/resolve/test/resolver/dot_slash_main/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bd816eaba4ca3be8e4d68cfc0ae9f64b5aa712cc --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_slash_main/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/dot_slash_main/package.json b/node_modules/resolve/test/resolver/dot_slash_main/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f51287b9d1e739a8827578a541e89f7e91450615 --- /dev/null +++ b/node_modules/resolve/test/resolver/dot_slash_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "./" +} diff --git a/node_modules/resolve/test/resolver/false_main/index.js b/node_modules/resolve/test/resolver/false_main/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/resolver/false_main/package.json b/node_modules/resolve/test/resolver/false_main/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a7416c0c7aa4a1df56419f92dcc7519836db8978 --- /dev/null +++ b/node_modules/resolve/test/resolver/false_main/package.json @@ -0,0 +1,4 @@ +{ + "name": "false_main", + "main": false +} diff --git a/node_modules/resolve/test/resolver/foo.js b/node_modules/resolve/test/resolver/foo.js new file mode 100644 index 0000000000000000000000000000000000000000..bd816eaba4ca3be8e4d68cfc0ae9f64b5aa712cc --- /dev/null +++ b/node_modules/resolve/test/resolver/foo.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/incorrect_main/index.js b/node_modules/resolve/test/resolver/incorrect_main/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bc1fb0a6f4ede17ec05e767ca8ccacbc3015ff70 --- /dev/null +++ b/node_modules/resolve/test/resolver/incorrect_main/index.js @@ -0,0 +1,2 @@ +// this is the actual main file 'index.js', not 'wrong.js' like the package.json would indicate +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/incorrect_main/package.json b/node_modules/resolve/test/resolver/incorrect_main/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b7188041763f8a94977f173a26c41fdbf5f2effb --- /dev/null +++ b/node_modules/resolve/test/resolver/incorrect_main/package.json @@ -0,0 +1,3 @@ +{ + "main": "wrong.js" +} diff --git a/node_modules/resolve/test/resolver/invalid_main/package.json b/node_modules/resolve/test/resolver/invalid_main/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0590748642ae2eadb17726ec3d1b501c94652277 --- /dev/null +++ b/node_modules/resolve/test/resolver/invalid_main/package.json @@ -0,0 +1,7 @@ +{ + "name": "invalid_main", + "main": [ + "why is this a thing", + "srsly omg wtf" + ] +} diff --git a/node_modules/resolve/test/resolver/mug.coffee b/node_modules/resolve/test/resolver/mug.coffee new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/resolver/mug.js b/node_modules/resolve/test/resolver/mug.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/resolver/multirepo/lerna.json b/node_modules/resolve/test/resolver/multirepo/lerna.json new file mode 100644 index 0000000000000000000000000000000000000000..d6707ca0cd64d48d212b90abe2e72f24b092572f --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/lerna.json @@ -0,0 +1,6 @@ +{ + "packages": [ + "packages/*" + ], + "version": "0.0.0" +} diff --git a/node_modules/resolve/test/resolver/multirepo/package.json b/node_modules/resolve/test/resolver/multirepo/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4391d392ea2761caea4d8286cc8ccc56cfa3e4a5 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/package.json @@ -0,0 +1,20 @@ +{ + "name": "ljharb-monorepo-symlink-test", + "private": true, + "version": "0.0.0", + "description": "", + "main": "index.js", + "scripts": { + "postinstall": "lerna bootstrap", + "test": "node packages/package-a" + }, + "author": "", + "license": "MIT", + "dependencies": { + "jquery": "^3.3.1", + "resolve": "../../../" + }, + "devDependencies": { + "lerna": "^3.4.3" + } +} diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js b/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8875a32df0ffc4eda94bb6c6dd9855ac604820c4 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-a/index.js @@ -0,0 +1,35 @@ +'use strict'; + +var assert = require('assert'); +var path = require('path'); +var resolve = require('resolve'); + +var basedir = __dirname + '/node_modules/@my-scope/package-b'; + +var expected = path.join(__dirname, '../../node_modules/jquery/dist/jquery.js'); + +/* + * preserveSymlinks === false + * will search NPM package from + * - packages/package-b/node_modules + * - packages/node_modules + * - node_modules + */ +assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: false }), expected); +assert.equal(resolve.sync('../../node_modules/jquery', { basedir: basedir, preserveSymlinks: false }), expected); + +/* + * preserveSymlinks === true + * will search NPM package from + * - packages/package-a/node_modules/@my-scope/packages/package-b/node_modules + * - packages/package-a/node_modules/@my-scope/packages/node_modules + * - packages/package-a/node_modules/@my-scope/node_modules + * - packages/package-a/node_modules/node_modules + * - packages/package-a/node_modules + * - packages/node_modules + * - node_modules + */ +assert.equal(resolve.sync('jquery', { basedir: basedir, preserveSymlinks: true }), expected); +assert.equal(resolve.sync('../../../../../node_modules/jquery', { basedir: basedir, preserveSymlinks: true }), expected); + +console.log(' * all monorepo paths successfully resolved through symlinks'); diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json b/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json new file mode 100644 index 0000000000000000000000000000000000000000..204de51e05878b3451223ba654c5e4a790ef1e51 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-a/package.json @@ -0,0 +1,14 @@ +{ + "name": "@my-scope/package-a", + "version": "0.0.0", + "private": true, + "description": "", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "echo \"Error: run tests from root\" && exit 1" + }, + "dependencies": { + "@my-scope/package-b": "^0.0.0" + } +} diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-b/index.js b/node_modules/resolve/test/resolver/multirepo/packages/package-b/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json b/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f57c3b5f5e454d3948e1a4bc5aec10fdcd79d8b5 --- /dev/null +++ b/node_modules/resolve/test/resolver/multirepo/packages/package-b/package.json @@ -0,0 +1,14 @@ +{ + "name": "@my-scope/package-b", + "private": true, + "version": "0.0.0", + "description": "", + "license": "MIT", + "main": "index.js", + "scripts": { + "test": "echo \"Error: run tests from root\" && exit 1" + }, + "dependencies": { + "@my-scope/package-a": "^0.0.0" + } +} diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js b/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js new file mode 100644 index 0000000000000000000000000000000000000000..fc2ef242be5eb7a4af7f514e01f916e321717601 --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/async.js @@ -0,0 +1,26 @@ +var a = require.resolve('buffer/').replace(process.cwd(), '$CWD'); +var b; +var c; + +function test() { + console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false')); + console.log(b, ': preserveSymlinks true'); + console.log(c, ': preserveSymlinks false'); + + if (a !== b && a !== c) { + throw 'async: no match'; + } + console.log('async: success! a matched either b or c\n'); +} + +require('resolve')('buffer/', { preserveSymlinks: true }, function (err, result) { + if (err) { throw err; } + b = result.replace(process.cwd(), '$CWD'); + if (b && c) { test(); } +}); +require('resolve')('buffer/', { preserveSymlinks: false }, function (err, result) { + if (err) { throw err; } + c = result.replace(process.cwd(), '$CWD'); + if (b && c) { test(); } +}); + diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json b/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json new file mode 100644 index 0000000000000000000000000000000000000000..acfe9e9517720ab5532c247052fadb214c5ffef3 --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/package.json @@ -0,0 +1,15 @@ +{ + "name": "mylib", + "version": "0.0.0", + "description": "", + "private": true, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "", + "license": "ISC", + "dependencies": { + "buffer": "*" + } +} diff --git a/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js b/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..3283efc2ec81f8d2a62be9a1fd28a192403ce549 --- /dev/null +++ b/node_modules/resolve/test/resolver/nested_symlinks/mylib/sync.js @@ -0,0 +1,12 @@ +var a = require.resolve('buffer/').replace(process.cwd(), '$CWD'); +var b = require('resolve').sync('buffer/', { preserveSymlinks: true }).replace(process.cwd(), '$CWD'); +var c = require('resolve').sync('buffer/', { preserveSymlinks: false }).replace(process.cwd(), '$CWD'); + +console.log(a, ': require.resolve, preserveSymlinks ' + (process.execArgv.indexOf('preserve-symlinks') > -1 ? 'true' : 'false')); +console.log(b, ': preserveSymlinks true'); +console.log(c, ': preserveSymlinks false'); + +if (a !== b && a !== c) { + throw 'sync: no match'; +} +console.log('sync: success! a matched either b or c\n'); diff --git a/node_modules/resolve/test/resolver/other_path/lib/other-lib.js b/node_modules/resolve/test/resolver/other_path/lib/other-lib.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/resolver/other_path/root.js b/node_modules/resolve/test/resolver/other_path/root.js new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/resolver/quux/foo/index.js b/node_modules/resolve/test/resolver/quux/foo/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bd816eaba4ca3be8e4d68cfc0ae9f64b5aa712cc --- /dev/null +++ b/node_modules/resolve/test/resolver/quux/foo/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/same_names/foo.js b/node_modules/resolve/test/resolver/same_names/foo.js new file mode 100644 index 0000000000000000000000000000000000000000..888cae37af95c51299d735439cf896dc4d5aaafc --- /dev/null +++ b/node_modules/resolve/test/resolver/same_names/foo.js @@ -0,0 +1 @@ +module.exports = 42; diff --git a/node_modules/resolve/test/resolver/same_names/foo/index.js b/node_modules/resolve/test/resolver/same_names/foo/index.js new file mode 100644 index 0000000000000000000000000000000000000000..bd816eaba4ca3be8e4d68cfc0ae9f64b5aa712cc --- /dev/null +++ b/node_modules/resolve/test/resolver/same_names/foo/index.js @@ -0,0 +1 @@ +module.exports = 1; diff --git a/node_modules/resolve/test/resolver/symlinked/_/symlink_target/.gitkeep b/node_modules/resolve/test/resolver/symlinked/_/symlink_target/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/node_modules/resolve/test/resolver/symlinked/package/bar.js b/node_modules/resolve/test/resolver/symlinked/package/bar.js new file mode 100644 index 0000000000000000000000000000000000000000..cb1c2c01e753b31f6e550e991a82022f7acf8638 --- /dev/null +++ b/node_modules/resolve/test/resolver/symlinked/package/bar.js @@ -0,0 +1 @@ +module.exports = 'bar'; diff --git a/node_modules/resolve/test/resolver/symlinked/package/package.json b/node_modules/resolve/test/resolver/symlinked/package/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8e1b585914a7b46cd21d5d8709ac08bc1fe84962 --- /dev/null +++ b/node_modules/resolve/test/resolver/symlinked/package/package.json @@ -0,0 +1,3 @@ +{ + "main": "bar.js" +} \ No newline at end of file diff --git a/node_modules/resolve/test/resolver/without_basedir/main.js b/node_modules/resolve/test/resolver/without_basedir/main.js new file mode 100644 index 0000000000000000000000000000000000000000..5b31975be69da5efea03fac676afa5f2199831be --- /dev/null +++ b/node_modules/resolve/test/resolver/without_basedir/main.js @@ -0,0 +1,5 @@ +var resolve = require('../../../'); + +module.exports = function (t, cb) { + resolve('mymodule', null, cb); +}; diff --git a/node_modules/resolve/test/resolver_sync.js b/node_modules/resolve/test/resolver_sync.js new file mode 100644 index 0000000000000000000000000000000000000000..2f5ed43f010eb02d169fdbaf6456f15dcb36279f --- /dev/null +++ b/node_modules/resolve/test/resolver_sync.js @@ -0,0 +1,730 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); + +var resolve = require('../'); +var sync = require('../sync'); + +var requireResolveSupportsPaths = require.resolve.length > 1 + && !(/^v12\.[012]\./).test(process.version); // broken in v12.0-12.2, see https://github.com/nodejs/node/issues/27794 + +var requireResolveDefaultPathsBroken = (/^v8\.9\.|^v9\.[01]\.0|^v9\.2\./).test(process.version); +// broken in node v8.9.x, v9.0, v9.1, v9.2.x. see https://github.com/nodejs/node/pull/17113 + +test('`./sync` entry point', function (t) { + t.equal(resolve.sync, sync, '`./sync` entry point is the same as `.sync` on `main`'); + t.end(); +}); + +test('foo', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./foo', { basedir: dir }), + path.join(dir, 'foo.js'), + './foo' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo', { basedir: dir }), + require.resolve('./foo', { paths: [dir] }), + './foo: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + path.join(dir, 'foo.js'), + './foo.js' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + require.resolve('./foo.js', { paths: [dir] }), + './foo.js: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo.js', { basedir: dir, filename: path.join(dir, 'bar.js') }), + path.join(dir, 'foo.js') + ); + + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }); + + // Test that filename is reported as the "from" value when passed. + t.throws( + function () { + resolve.sync('foo', { basedir: dir, filename: path.join(dir, 'bar.js') }); + }, + { + name: 'Error', + message: "Cannot find module 'foo' from '" + path.join(dir, 'bar.js') + "'" + } + ); + + t.end(); +}); + +test('bar', function (t) { + var dir = path.join(__dirname, 'resolver'); + + var basedir = path.join(dir, 'bar'); + + t.equal( + resolve.sync('foo', { basedir: basedir }), + path.join(dir, 'bar/node_modules/foo/index.js'), + 'foo in bar' + ); + if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) { + t.equal( + resolve.sync('foo', { basedir: basedir }), + require.resolve('foo', { paths: [basedir] }), + 'foo in bar: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('baz', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./baz', { basedir: dir }), + path.join(dir, 'baz/quux.js'), + './baz' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./baz', { basedir: dir }), + require.resolve('./baz', { paths: [dir] }), + './baz: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('biz', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + + t.equal( + resolve.sync('./grux', { basedir: dir }), + path.join(dir, 'grux/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./grux', { basedir: dir }), + require.resolve('./grux', { paths: [dir] }), + './grux: resolve.sync === require.resolve' + ); + } + + var tivDir = path.join(dir, 'grux'); + t.equal( + resolve.sync('tiv', { basedir: tivDir }), + path.join(dir, 'tiv/index.js') + ); + if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) { + t.equal( + resolve.sync('tiv', { basedir: tivDir }), + require.resolve('tiv', { paths: [tivDir] }), + 'tiv: resolve.sync === require.resolve' + ); + } + + var gruxDir = path.join(dir, 'tiv'); + t.equal( + resolve.sync('grux', { basedir: gruxDir }), + path.join(dir, 'grux/index.js') + ); + if (!requireResolveDefaultPathsBroken && requireResolveSupportsPaths) { + t.equal( + resolve.sync('grux', { basedir: gruxDir }), + require.resolve('grux', { paths: [gruxDir] }), + 'grux: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('normalize', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + + t.equal( + resolve.sync('../grux', { basedir: dir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('../grux', { basedir: dir }), + require.resolve('../grux', { paths: [dir] }), + '../grux: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('cup', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'cup.coffee'), + './cup -> ./cup.coffee' + ); + + t.equal( + resolve.sync('./cup.coffee', { basedir: dir }), + path.join(dir, 'cup.coffee'), + './cup.coffee' + ); + + t.throws(function () { + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js'] + }); + }); + + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./cup.coffee', { basedir: dir, extensions: ['.js', '.coffee'] }), + require.resolve('./cup.coffee', { paths: [dir] }), + './cup.coffee: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('mug', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./mug', { basedir: dir }), + path.join(dir, 'mug.js'), + './mug -> ./mug.js' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./mug', { basedir: dir }), + require.resolve('./mug', { paths: [dir] }), + './mug: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.coffee', '.js'] + }), + path.join(dir, 'mug.coffee'), + './mug -> ./mug.coffee' + ); + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'mug.js'), + './mug -> ./mug.js' + ); + + t.end(); +}); + +test('other path', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + t.equal( + resolve.sync('root', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/root.js') + ); + + t.equal( + resolve.sync('lib/other-lib', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/lib/other-lib.js') + ); + + t.throws(function () { + resolve.sync('root', { basedir: dir }); + }); + + t.throws(function () { + resolve.sync('zzz', { + basedir: dir, + paths: [otherDir] + }); + }); + + t.end(); +}); + +test('path iterator', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + function exactIterator(x, start, getPackageCandidates, opts) { + return [path.join(resolverDir, x)]; + } + + t.equal( + resolve.sync('baz', { packageIterator: exactIterator }), + path.join(resolverDir, 'baz/quux.js') + ); + + t.end(); +}); + +test('incorrect main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + path.join(dir, 'index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + require.resolve('./incorrect_main', { paths: [resolverDir] }), + './incorrect_main: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('missing index', function (t) { + t.plan(requireResolveSupportsPaths ? 2 : 1); + + var resolverDir = path.join(__dirname, 'resolver'); + try { + resolve.sync('./missing_index', { basedir: resolverDir }); + t.fail('did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + if (requireResolveSupportsPaths) { + try { + require.resolve('./missing_index', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + } +}); + +test('missing main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + try { + resolve.sync('./missing_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + if (requireResolveSupportsPaths) { + try { + resolve.sync('./missing_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + } + + t.end(); +}); + +test('null main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + + try { + resolve.sync('./null_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + if (requireResolveSupportsPaths) { + try { + resolve.sync('./null_main', { basedir: resolverDir }); + t.fail('require.resolve did not fail'); + } catch (err) { + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error has correct error code'); + } + } + + t.end(); +}); + +test('main: false', function (t) { + var basedir = path.join(__dirname, 'resolver'); + var dir = path.join(basedir, 'false_main'); + t.equal( + resolve.sync('./false_main', { basedir: basedir }), + path.join(dir, 'index.js'), + '`"main": false`: resolves to `index.js`' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./false_main', { basedir: basedir }), + require.resolve('./false_main', { paths: [basedir] }), + '`"main": false`: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +function stubStatSync(fn) { + var statSync = fs.statSync; + try { + fs.statSync = function () { + throw new EvalError('Unknown Error'); + }; + return fn(); + } finally { + fs.statSync = statSync; + } +} + +test('#79 - re-throw non ENOENT errors from stat', function (t) { + var dir = path.join(__dirname, 'resolver'); + + stubStatSync(function () { + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }, /Unknown Error/); + }); + + t.end(); +}); + +test('#52 - incorrectly resolves module-paths like "./someFolder/" when there is a file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + var basedir = path.join(dir, 'same_names'); + + t.equal( + resolve.sync('./foo', { basedir: basedir }), + path.join(dir, 'same_names/foo.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo', { basedir: basedir }), + require.resolve('./foo', { paths: [basedir] }), + './foo: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('./foo/', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js') + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./foo/', { basedir: basedir }), + require.resolve('./foo/', { paths: [basedir] }), + './foo/: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +test('#211 - incorrectly resolves module-paths like "." when from inside a folder with a sibling file of the same name', function (t) { + var dir = path.join(__dirname, 'resolver'); + var basedir = path.join(dir, 'same_names/foo'); + + t.equal( + resolve.sync('./', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js'), + './' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./', { basedir: basedir }), + require.resolve('./', { paths: [basedir] }), + './: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync('.', { basedir: basedir }), + path.join(dir, 'same_names/foo/index.js'), + '.' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('.', { basedir: basedir }), + require.resolve('.', { paths: [basedir] }), + '.: resolve.sync === require.resolve', + { todo: true } + ); + } + + t.end(); +}); + +test('sync: #121 - treating an existing file as a dir when no basedir', function (t) { + var testFile = path.basename(__filename); + + t.test('sanity check', function (st) { + st.equal( + resolve.sync('./' + testFile), + __filename, + 'sanity check' + ); + st.equal( + resolve.sync('./' + testFile), + require.resolve('./' + testFile), + 'sanity check: resolve.sync === require.resolve' + ); + + st.end(); + }); + + t.test('with a fake directory', function (st) { + function run() { return resolve.sync('./' + testFile + '/blah'); } + + st.throws(run, 'throws an error'); + + try { + run(); + } catch (e) { + st.equal(e.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + st.equal( + e.message, + 'Cannot find module \'./' + testFile + '/blah\' from \'' + __dirname + '\'', + 'can not find nonexistent module' + ); + } + + st.end(); + }); + + t.end(); +}); + +test('sync dot main', function (t) { + var start = new Date(); + + t.equal( + resolve.sync('./resolver/dot_main'), + path.join(__dirname, 'resolver/dot_main/index.js'), + './resolver/dot_main' + ); + t.equal( + resolve.sync('./resolver/dot_main'), + require.resolve('./resolver/dot_main'), + './resolver/dot_main: resolve.sync === require.resolve' + ); + + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + + t.end(); +}); + +test('sync dot slash main', function (t) { + var start = new Date(); + + t.equal( + resolve.sync('./resolver/dot_slash_main'), + path.join(__dirname, 'resolver/dot_slash_main/index.js') + ); + t.equal( + resolve.sync('./resolver/dot_slash_main'), + require.resolve('./resolver/dot_slash_main'), + './resolver/dot_slash_main: resolve.sync === require.resolve' + ); + + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + + t.end(); +}); + +test('not a directory', function (t) { + var path = './foo'; + try { + resolve.sync(path, { basedir: __filename }); + t.fail(); + } catch (err) { + t.ok(err, 'a non-directory errors'); + t.equal(err && err.message, 'Cannot find module \'' + path + "' from '" + __filename + "'"); + t.equal(err && err.code, 'MODULE_NOT_FOUND'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('non-string "main" field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + try { + var result = resolve.sync('./invalid_main', { basedir: dir }); + t.equal(result, undefined, 'result should not exist'); + t.fail('should not get here'); + } catch (err) { + t.ok(err, 'errors on non-string main'); + t.equal(err.message, 'package “invalid_main” `main` must be a string'); + t.equal(err.code, 'INVALID_PACKAGE_MAIN'); + } + t.end(); +}); + +test('browser field in package.json', function (t) { + var dir = path.join(__dirname, 'resolver'); + var res = resolve.sync('./browser_field', { + basedir: dir, + packageFilter: function packageFilter(pkg) { + if (pkg.browser) { + pkg.main = pkg.browser; // eslint-disable-line no-param-reassign + delete pkg.browser; // eslint-disable-line no-param-reassign + } + return pkg; + } + }); + t.equal(res, path.join(dir, 'browser_field', 'b.js')); + t.end(); +}); + +test('absolute paths', function (t) { + var extensionless = __filename.slice(0, -path.extname(__filename).length); + + t.equal( + resolve.sync(__filename), + __filename, + 'absolute path to this file resolves' + ); + t.equal( + resolve.sync(__filename), + require.resolve(__filename), + 'absolute path to this file: resolve.sync === require.resolve' + ); + + t.equal( + resolve.sync(extensionless), + __filename, + 'extensionless absolute path to this file resolves' + ); + t.equal( + resolve.sync(__filename), + require.resolve(__filename), + 'absolute path to this file: resolve.sync === require.resolve' + ); + + t.equal( + resolve.sync(__filename, { basedir: process.cwd() }), + __filename, + 'absolute path to this file with a basedir resolves' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync(__filename, { basedir: process.cwd() }), + require.resolve(__filename, { paths: [process.cwd()] }), + 'absolute path to this file + basedir: resolve.sync === require.resolve' + ); + } + + t.equal( + resolve.sync(extensionless, { basedir: process.cwd() }), + __filename, + 'extensionless absolute path to this file with a basedir resolves' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync(extensionless, { basedir: process.cwd() }), + require.resolve(extensionless, { paths: [process.cwd()] }), + 'extensionless absolute path to this file + basedir: resolve.sync === require.resolve' + ); + } + + t.end(); +}); + +var malformedDir = path.join(__dirname, 'resolver/malformed_package_json'); +test('malformed package.json', { skip: !fs.existsSync(malformedDir) }, function (t) { + t.plan(5 + (requireResolveSupportsPaths ? 1 : 0)); + + var basedir = malformedDir; + var expected = path.join(basedir, 'index.js'); + + t.equal( + resolve.sync('./index.js', { basedir: basedir }), + expected, + 'malformed package.json is silently ignored' + ); + if (requireResolveSupportsPaths) { + t.equal( + resolve.sync('./index.js', { basedir: basedir }), + require.resolve('./index.js', { paths: [basedir] }), + 'malformed package.json: resolve.sync === require.resolve' + ); + } + + var res1 = resolve.sync( + './index.js', + { + basedir: basedir, + packageFilter: function (pkg, pkgfile, dir) { + t.fail('should not reach here'); + } + } + ); + + t.equal( + res1, + expected, + 'with packageFilter: malformed package.json is silently ignored' + ); + + var res2 = resolve.sync( + './index.js', + { + basedir: basedir, + readPackageSync: function (readFileSync, pkgfile) { + t.equal(pkgfile, path.join(basedir, 'package.json'), 'readPackageSync: `pkgfile` is package.json path'); + var result = String(readFileSync(pkgfile)); + try { + return JSON.parse(result); + } catch (e) { + t.ok(e instanceof SyntaxError, 'readPackageSync: malformed package.json parses as a syntax error'); + } + } + } + ); + + t.equal( + res2, + expected, + 'with readPackageSync: malformed package.json is silently ignored' + ); +}); diff --git a/node_modules/resolve/test/shadowed_core.js b/node_modules/resolve/test/shadowed_core.js new file mode 100644 index 0000000000000000000000000000000000000000..3a5f4fcff728f305c2d3d17a416fea4cbfe31f6b --- /dev/null +++ b/node_modules/resolve/test/shadowed_core.js @@ -0,0 +1,54 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('shadowed core modules still return core module', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, 'util'); + }); +}); + +test('shadowed core modules still return core module [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, 'util'); +}); + +test('shadowed core modules return shadow when appending `/`', function (t) { + t.plan(2); + + resolve('util/', { basedir: path.join(__dirname, 'shadowed_core') }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow when appending `/` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util/', { basedir: path.join(__dirname, 'shadowed_core') }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false`', function (t) { + t.plan(2); + + resolve('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); + }); +}); + +test('shadowed core modules return shadow with `includeCoreModules: false` [sync]', function (t) { + t.plan(1); + + var res = resolve.sync('util', { basedir: path.join(__dirname, 'shadowed_core'), includeCoreModules: false }); + + t.equal(res, path.join(__dirname, 'shadowed_core/node_modules/util/index.js')); +}); diff --git a/node_modules/resolve/test/subdirs.js b/node_modules/resolve/test/subdirs.js new file mode 100644 index 0000000000000000000000000000000000000000..b7b8450a9ef231940eca37b8fe951310147a9470 --- /dev/null +++ b/node_modules/resolve/test/subdirs.js @@ -0,0 +1,13 @@ +var test = require('tape'); +var resolve = require('../'); +var path = require('path'); + +test('subdirs', function (t) { + t.plan(2); + + var dir = path.join(__dirname, '/subdirs'); + resolve('a/b/c/x.json', { basedir: dir }, function (err, res) { + t.ifError(err); + t.equal(res, path.join(dir, 'node_modules/a/b/c/x.json')); + }); +}); diff --git a/node_modules/resolve/test/symlinks.js b/node_modules/resolve/test/symlinks.js new file mode 100644 index 0000000000000000000000000000000000000000..35f881afb8c7e043567cf85953d9046c011cec3d --- /dev/null +++ b/node_modules/resolve/test/symlinks.js @@ -0,0 +1,176 @@ +var path = require('path'); +var fs = require('fs'); +var test = require('tape'); +var map = require('array.prototype.map'); +var resolve = require('../'); + +var symlinkDir = path.join(__dirname, 'resolver', 'symlinked', 'symlink'); +var packageDir = path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'package'); +var modADir = path.join(__dirname, 'symlinks', 'source', 'node_modules', 'mod-a'); +var symlinkModADir = path.join(__dirname, 'symlinks', 'dest', 'node_modules', 'mod-a'); +try { + fs.unlinkSync(symlinkDir); +} catch (err) {} +try { + fs.unlinkSync(packageDir); +} catch (err) {} +try { + fs.unlinkSync(modADir); +} catch (err) {} +try { + fs.unlinkSync(symlinkModADir); +} catch (err) {} + +try { + fs.symlinkSync('./_/symlink_target', symlinkDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, 'resolver', 'symlinked', '_', 'symlink_target') + '\\', symlinkDir, 'junction'); +} +try { + fs.symlinkSync('../../package', packageDir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'package') + '\\', packageDir, 'junction'); +} +try { + fs.symlinkSync('../../source/node_modules/mod-a', symlinkModADir, 'dir'); +} catch (err) { + // if fails then it is probably on Windows and lets try to create a junction + fs.symlinkSync(path.join(__dirname, '..', '..', 'source', 'node_modules', 'mod-a') + '\\', symlinkModADir, 'junction'); +} + +test('symlink', function (t) { + t.plan(2); + + resolve('foo', { basedir: symlinkDir, preserveSymlinks: false }, function (err, res, pkg) { + t.error(err); + t.equal(res, path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js')); + }); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.plan(4); + + resolve('foo', { basedir: symlinkDir }, function (err, res, pkg) { + t.ok(err, 'there is an error'); + t.notOk(res, 'no result'); + + t.equal(err && err.code, 'MODULE_NOT_FOUND', 'error code matches require.resolve'); + t.equal( + err && err.message, + 'Cannot find module \'foo\' from \'' + symlinkDir + '\'', + 'can not find nonexistent module' + ); + }); +}); + +test('sync symlink', function (t) { + var start = new Date(); + t.doesNotThrow(function () { + t.equal( + resolve.sync('foo', { basedir: symlinkDir, preserveSymlinks: false }), + path.join(__dirname, 'resolver', 'symlinked', '_', 'node_modules', 'foo.js') + ); + }); + t.ok(new Date() - start < 50, 'resolve.sync timedout'); + t.end(); +}); + +test('sync symlink when preserveSymlinks = true', function (t) { + t.throws(function () { + resolve.sync('foo', { basedir: symlinkDir }); + }, /Cannot find module 'foo'/); + t.end(); +}); + +test('sync symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + var fn = resolve.sync('package', { basedir: basedir, preserveSymlinks: false }); + + t.equal(fn, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + t.end(); +}); + +test('async symlink from node_modules to other dir when preserveSymlinks = false', function (t) { + t.plan(2); + var basedir = path.join(__dirname, 'resolver', 'symlinked', '_'); + resolve('package', { basedir: basedir, preserveSymlinks: false }, function (err, result) { + t.notOk(err, 'no error'); + t.equal(result, path.resolve(__dirname, 'resolver/symlinked/package/bar.js')); + }); +}); + +test('packageFilter', function (t) { + function relative(x) { + return path.relative(__dirname, x); + } + + function testPackageFilter(preserveSymlinks) { + return function (st) { + st.plan('is 1.x' ? 3 : 5); // eslint-disable-line no-constant-condition + + var destMain = 'symlinks/dest/node_modules/mod-a/index.js'; + var destPkg = 'symlinks/dest/node_modules/mod-a/package.json'; + var sourceMain = 'symlinks/source/node_modules/mod-a/index.js'; + var sourcePkg = 'symlinks/source/node_modules/mod-a/package.json'; + var destDir = path.join(__dirname, 'symlinks', 'dest'); + + /* eslint multiline-comment-style: 0 */ + /* v2.x will restore these tests + var packageFilterPath = []; + var actualPath = resolve.sync('mod-a', { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile, dir) { + packageFilterPath.push(pkgfile); + } + }); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'sync: actual path is correct' + ); + st.deepEqual( + map(packageFilterPath, relative), + map(preserveSymlinks ? [destPkg, destPkg] : [sourcePkg, sourcePkg], path.normalize), + 'sync: packageFilter pkgfile arg is correct' + ); + */ + + var asyncPackageFilterPath = []; + resolve( + 'mod-a', + { + basedir: destDir, + preserveSymlinks: preserveSymlinks, + packageFilter: function (pkg, pkgfile) { + asyncPackageFilterPath.push(pkgfile); + } + }, + function (err, actualPath) { + st.error(err, 'no error'); + st.equal( + relative(actualPath), + path.normalize(preserveSymlinks ? destMain : sourceMain), + 'async: actual path is correct' + ); + st.deepEqual( + map(asyncPackageFilterPath, relative), + map( + preserveSymlinks ? [destPkg, destPkg, destPkg] : [sourcePkg, sourcePkg, sourcePkg], + path.normalize + ), + 'async: packageFilter pkgfile arg is correct' + ); + } + ); + }; + } + + t.test('preserveSymlinks: false', testPackageFilter(false)); + + t.test('preserveSymlinks: true', testPackageFilter(true)); + + t.end(); +}); diff --git a/node_modules/restructure/LICENSE b/node_modules/restructure/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6291454829be6a266438f11110e7656581683f0c --- /dev/null +++ b/node_modules/restructure/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2015-present Devon Govett + +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. diff --git a/node_modules/restructure/README.md b/node_modules/restructure/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2203745214eee0cd90f6d2b867051f82c1a1fc5b --- /dev/null +++ b/node_modules/restructure/README.md @@ -0,0 +1,300 @@ +# Restructure + +[![Build Status](https://travis-ci.org/devongovett/restructure.svg?branch=master)](https://travis-ci.org/devongovett/restructure) +[![Coverage Status](https://coveralls.io/repos/devongovett/restructure/badge.png?branch=master)](https://coveralls.io/r/devongovett/restructure?branch=master) + +Restructure allows you to declaratively encode and decode binary data. +It supports a wide variety of types to enable you to express a multitude +of binary formats without writing any parsing code. + +Some of the supported features are C-like structures, versioned structures, +pointers, arrays of any type, strings of a large number of encodings, enums, +bitfields, and more. See the documentation below for more details. + +## Example + +This is just a small example of what Restructure can do. Check out the API documentation +below for more information. + +```javascript +import * as r from 'restructure'; + +let Person = new r.Struct({ + name: new r.String(r.uint8, 'utf8'), + age: r.uint8 +}); + +// decode a person from a buffer +let value = Person.fromBuffer(new Uint8Array([/* ... */])); // returns an object with the fields defined above + +// encode a person from an object +let buffer = Person.toBuffer({ + name: 'Devon', + age: 21 +}); +``` + +## API + +All of the following types support three standard methods: + +* `fromBuffer(buffer)` - decodes an instance of the type from the given Uint8Array +* `size(value)` - returns the amount of space the value would take if encoded +* `toBuffer(value)` - encodes the given value into a Uint8Array + +Restructure supports a wide variety of types, but if you need to write your own for +some custom use that cannot be represented by them, you can do so by just implementing +the above methods. Then you can use your type just as you would any other type, in structures +and whatnot. + +### Number Types + +The following built-in number types are available: + +```javascript +uint8, uint16, uint24, uint32, int8, int16, int24, int32, float, double, fixed16, fixed32 +``` + +Numbers are big-endian (network order) by default, but little-endian is supported, too: + +```javascript +uint16le, uint24le, uint32le, int16le, int24le, int32le, floatle, doublele, fixed16le, fixed32le +``` + +To avoid ambiguity, big-endian may be used explicitly: + +```javascript +uint16be, uint24be, uint32be, int16be, int24be, int32be, floatbe, doublebe, fixed16be, fixed32be +``` + +### Boolean + +Booleans are encoded as `0` or `1` using one of the above number types. + +```javascript +var bool = new r.Boolean(r.uint32); +``` + +### Reserved + +The `Reserved` type simply skips data in a structure, where there are reserved fields. +Encoding produces zeros. + +```javascript +// 10 reserved uint8s (default is 1) +var reserved = new r.Reserved(r.uint8, 10); +``` + +### Optional + +The `Optional` type only encodes or decodes when given condition is truthy. + +```javascript +// includes field +var optional = new r.Optional(r.uint8, true); + +// excludes field +var optional = new r.Optional(r.uint8, false); + +// determine whether field is to be included at runtime with a function +var optional = new r.Optional(r.uint8, function() { + return this.flags & 0x50; +}); +``` + +### Enum + +The `Enum` type maps a number to the value at that index in an array. + +```javascript +var color = new r.Enum(r.uint8, ['red', 'orange', 'yellow', 'green', 'blue', 'purple']); +``` + +### Bitfield + +The `Bitfield` type maps a number to an object with boolean keys mapping to each bit in that number, +as defined in an array. + +```javascript +var bitfield = new r.Bitfield(r.uint8, ['Jack', 'Kack', 'Lack', 'Mack', 'Nack', 'Oack', 'Pack', 'Quack']); +bitfield.decode(stream); + +var result = { + Jack: true, + Kack: false, + Lack: false, + Mack: true, + Nack: true, + Oack: false, + Pack: true, + Quack: true +}; + +bitfield.encode(stream, result); +``` + +### Buffer + +Extracts a slice of the buffer to a `Uint8Array`. The length can be a constant, or taken from +a previous field in the parent structure. + +```javascript +// fixed length +var buf = new r.Buffer(2); + +// length from parent structure +var struct = new r.Struct({ + bufLen: r.uint8, + buf: new r.Buffer('bufLen') +}); +``` + +### String + +A `String` maps a JavaScript string to and from binary encodings. The length, in bytes, can be a constant, +taken from a previous field in the parent structure, encoded using a number type immediately before the +string. + +Fully supported encodings include `'ascii'`, `'utf8'`, `'ucs2'`, `'utf16le'`, `'utf16be'`. Decoding is also possible +with any encoding supported by [TextDecoder](https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API/Encodings), +however encoding these is not supported. + +```javascript +// fixed length, ascii encoding by default +var str = new r.String(2); + +// length encoded as number before the string, utf8 encoding +var str = new r.String(r.uint8, 'utf8'); + +// length from parent structure +var struct = new r.Struct({ + len: r.uint8, + str: new r.String('len', 'utf16be') +}); + +// null-terminated string (also known as C string) +var str = new r.String(null, 'utf8'); +``` + +### Array + +An `Array` maps to and from a JavaScript array containing instances of a sub-type. The length can be a constant, +taken from a previous field in the parent structure, encoded using a number type immediately +before the string, or computed by a function. + +```javascript +// fixed length, containing numbers +var arr = new r.Array(r.uint16, 2); + +// length encoded as number before the array containing strings +var arr = new r.Array(new r.String(10), r.uint8); + +// length computed by a function +var arr = new r.Array(r.uint8, function() { return 5 }); + +// length from parent structure +var struct = new r.Struct({ + len: r.uint8, + arr: new r.Array(r.uint8, 'len') +}); + +// treat as amount of bytes instead (may be used in all the above scenarios) +var arr = new r.Array(r.uint16, 6, 'bytes'); +``` + +### LazyArray + +The `LazyArray` type extends from the `Array` type, and is useful for large arrays that you do not need to access sequentially. +It avoids decoding the entire array upfront, and instead only decodes and caches individual items as needed. It only works when +the elements inside the array have a fixed size. + +Instead of returning a JavaScript array, the `LazyArray` type returns a custom object that can be used to access the elements. + +```javascript +var arr = new r.LazyArray(r.uint16, 2048); +var res = arr.decode(stream); + +// get a single element +var el = res.get(2); + +// convert to a normal array (decode all elements) +var array = res.toArray(); +``` + +### Struct + +A `Struct` maps to and from JavaScript objects, containing keys of various previously discussed types. Sub structures, +arrays of structures, and pointers to other types (discussed below) are supported. + +```javascript +var Person = new r.Struct({ + name: new r.String(r.uint8, 'utf8'), + age: r.uint8 +}); +``` + +### VersionedStruct + +A `VersionedStruct` is a `Struct` that has multiple versions. The version is typically encoded at +the beginning of the structure, or as a field in a parent structure. There is an optional `header` +common to all versions, and separate fields listed for each version number. + +```javascript +// the version is read as a uint8 in this example +// you could also get the version from a key on the parent struct +var Person = new r.VersionedStruct(r.uint8, { + // optional header common to all versions + header: { + name: new r.String(r.uint8, 'utf8') + }, + 0: { + age: r.uint8 + }, + 1: { + hairColor: r.Enum(r.uint8, ['black', 'brown', 'blonde']) + } +}); +``` + +### Pointer + +Pointers map an address or offset encoded as a number, to a value encoded elsewhere in the buffer. +There are a few options you can use: `type`, `relativeTo`, `allowNull`, and `nullValue`. +The `type` option has these possible values: + +* `local` (default) - the encoded offset is relative to the start of the containing structure +* `immediate` - the encoded offset is relative to the position of the pointer itself +* `parent` - the encoded offset is relative to the parent structure of the immediate container +* `global` - the encoded offset is global to the start of the file + +The `relativeTo` option accepts a function callback that should return the field on the containing structure which the encoded offset is relative to. The callback is called with the context as parameter. +By default, pointers are relative to the start of the containing structure (`local`). + +The `allowNull` option lets you specify whether zero offsets are allowed or should produce `null`. This is +set to `true` by default. The `nullValue` option is related, and lets you override the encoded value that +represents `null`. By default, the `nullValue` is zero. + +The `lazy` option allows lazy decoding of the pointer's value by defining a getter on the parent object. +This only works when the pointer is contained within a Struct, but can be used to speed up decoding +quite a bit when not all of the data is needed right away. + +```javascript +var Address = new r.Struct({ + street: new r.String(r.uint8), + zip: new r.String(5) +}); + +var Person = new r.Struct({ + name: new r.String(r.uint8, 'utf8'), + age: r.uint8, + ptrStart: r.uint8, + address: new r.Pointer(r.uint8, Address) +}); +``` + +If the type of a pointer is set to 'void', it is not decoded and the computed address in the buffer +is simply returned. To encode a void pointer, create a `new r.VoidPointer(type, value)`. + +## License + +MIT diff --git a/node_modules/restructure/index.js b/node_modules/restructure/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3dd10859981fcf55b65dffbd7911a0b6a63c78de --- /dev/null +++ b/node_modules/restructure/index.js @@ -0,0 +1,17 @@ +export {EncodeStream} from './src/EncodeStream.js'; +export {DecodeStream} from './src/DecodeStream.js'; +export {Array} from './src/Array.js'; +export {LazyArray} from './src/LazyArray.js'; +export {Bitfield} from './src/Bitfield.js'; +export {Boolean} from './src/Boolean.js'; +export {Buffer} from './src/Buffer.js'; +export {Enum} from './src/Enum.js'; +export {Optional} from './src/Optional.js'; +export {Reserved} from './src/Reserved.js'; +export {String} from './src/String.js'; +export {Struct} from './src/Struct.js'; +export {VersionedStruct} from './src/VersionedStruct.js'; + +export * from './src/utils.js'; +export * from './src/Number.js'; +export * from './src/Pointer.js'; diff --git a/node_modules/restructure/package.json b/node_modules/restructure/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0c247563694c31235258064a23fae7f6ac45c873 --- /dev/null +++ b/node_modules/restructure/package.json @@ -0,0 +1,41 @@ +{ + "name": "restructure", + "version": "3.0.2", + "description": "Declaratively encode and decode binary data", + "type": "module", + "main": "./dist/main.cjs", + "module": "./index.js", + "source": "./index.js", + "exports": { + "import": "./index.js", + "require": "./dist/main.cjs" + }, + "targets": { + "module": false + }, + "devDependencies": { + "mocha": "^10.0.0", + "parcel": "^2.6.1" + }, + "scripts": { + "test": "mocha", + "build": "parcel build", + "prepublishOnly": "parcel build" + }, + "repository": { + "type": "git", + "url": "git://github.com/devongovett/restructure.git" + }, + "keywords": [ + "binary", + "struct", + "encode", + "decode" + ], + "author": "Devon Govett ", + "license": "MIT", + "bugs": { + "url": "https://github.com/devongovett/restructure/issues" + }, + "homepage": "https://github.com/devongovett/restructure" +} diff --git a/node_modules/restructure/src/Array.js b/node_modules/restructure/src/Array.js new file mode 100644 index 0000000000000000000000000000000000000000..150c991625b58e4eeeca1d9e171b9609b6afa724 --- /dev/null +++ b/node_modules/restructure/src/Array.js @@ -0,0 +1,106 @@ +import {Base} from './Base.js'; +import {Number as NumberT} from './Number.js'; +import * as utils from './utils.js'; + +class ArrayT extends Base { + constructor(type, length, lengthType = 'count') { + super(); + this.type = type; + this.length = length; + this.lengthType = lengthType; + } + + decode(stream, parent) { + let length; + const { pos } = stream; + + const res = []; + let ctx = parent; + + if (this.length != null) { + length = utils.resolveLength(this.length, stream, parent); + } + + if (this.length instanceof NumberT) { + // define hidden properties + Object.defineProperties(res, { + parent: { value: parent }, + _startOffset: { value: pos }, + _currentOffset: { value: 0, writable: true }, + _length: { value: length } + }); + + ctx = res; + } + + if ((length == null) || (this.lengthType === 'bytes')) { + const target = (length != null) ? + stream.pos + length + : (parent != null ? parent._length : undefined) ? + parent._startOffset + parent._length + : + stream.length; + + while (stream.pos < target) { + res.push(this.type.decode(stream, ctx)); + } + + } else { + for (let i = 0, end = length; i < end; i++) { + res.push(this.type.decode(stream, ctx)); + } + } + + return res; + } + + size(array, ctx, includePointers = true) { + if (!array) { + return this.type.size(null, ctx) * utils.resolveLength(this.length, null, ctx); + } + + let size = 0; + if (this.length instanceof NumberT) { + size += this.length.size(); + ctx = {parent: ctx, pointerSize: 0}; + } + + for (let item of array) { + size += this.type.size(item, ctx); + } + + if (ctx && includePointers && this.length instanceof NumberT) { + size += ctx.pointerSize; + } + + return size; + } + + encode(stream, array, parent) { + let ctx = parent; + if (this.length instanceof NumberT) { + ctx = { + pointers: [], + startOffset: stream.pos, + parent + }; + + ctx.pointerOffset = stream.pos + this.size(array, ctx, false); + this.length.encode(stream, array.length); + } + + for (let item of array) { + this.type.encode(stream, item, ctx); + } + + if (this.length instanceof NumberT) { + let i = 0; + while (i < ctx.pointers.length) { + const ptr = ctx.pointers[i++]; + ptr.type.encode(stream, ptr.val, ptr.parent); + } + } + } +} + +export {ArrayT as Array}; diff --git a/node_modules/restructure/src/Base.js b/node_modules/restructure/src/Base.js new file mode 100644 index 0000000000000000000000000000000000000000..c76a39b0a53c553afcc7dbf62cd421d01e15222e --- /dev/null +++ b/node_modules/restructure/src/Base.js @@ -0,0 +1,17 @@ +import {DecodeStream} from './DecodeStream.js'; +import {EncodeStream} from './EncodeStream.js'; + +export class Base { + fromBuffer(buffer) { + let stream = new DecodeStream(buffer); + return this.decode(stream); + } + + toBuffer(value) { + let size = this.size(value); + let buffer = new Uint8Array(size); + let stream = new EncodeStream(buffer); + this.encode(stream, value); + return buffer; + } +} diff --git a/node_modules/restructure/src/Bitfield.js b/node_modules/restructure/src/Bitfield.js new file mode 100644 index 0000000000000000000000000000000000000000..1ae529a1a564ab79faef5d0712791997b4377435 --- /dev/null +++ b/node_modules/restructure/src/Bitfield.js @@ -0,0 +1,39 @@ +import {Base} from './Base.js'; + +export class Bitfield extends Base { + constructor(type, flags = []) { + super(); + this.type = type; + this.flags = flags; + } + + decode(stream) { + const val = this.type.decode(stream); + + const res = {}; + for (let i = 0; i < this.flags.length; i++) { + const flag = this.flags[i]; + if (flag != null) { + res[flag] = !!(val & (1 << i)); + } + } + + return res; + } + + size() { + return this.type.size(); + } + + encode(stream, keys) { + let val = 0; + for (let i = 0; i < this.flags.length; i++) { + const flag = this.flags[i]; + if (flag != null) { + if (keys[flag]) { val |= (1 << i); } + } + } + + return this.type.encode(stream, val); + } +} diff --git a/node_modules/restructure/src/Boolean.js b/node_modules/restructure/src/Boolean.js new file mode 100644 index 0000000000000000000000000000000000000000..e7ad576d92d46df05a918f64e463a09aa4098e81 --- /dev/null +++ b/node_modules/restructure/src/Boolean.js @@ -0,0 +1,22 @@ +import {Base} from './Base.js'; + +export class BooleanT extends Base { + constructor(type) { + super(); + this.type = type; + } + + decode(stream, parent) { + return !!this.type.decode(stream, parent); + } + + size(val, parent) { + return this.type.size(val, parent); + } + + encode(stream, val, parent) { + return this.type.encode(stream, +val, parent); + } +} + +export {BooleanT as Boolean}; diff --git a/node_modules/restructure/src/Buffer.js b/node_modules/restructure/src/Buffer.js new file mode 100644 index 0000000000000000000000000000000000000000..8fc69f93e5a37cfec97e8e11a90eed223420d083 --- /dev/null +++ b/node_modules/restructure/src/Buffer.js @@ -0,0 +1,38 @@ +import {Base} from './Base.js'; +import {Number as NumberT} from './Number.js'; +import * as utils from './utils.js'; + +export class BufferT extends Base { + constructor(length) { + super(); + this.length = length; + } + + decode(stream, parent) { + const length = utils.resolveLength(this.length, stream, parent); + return stream.readBuffer(length); + } + + size(val, parent) { + if (!val) { + return utils.resolveLength(this.length, null, parent); + } + + let len = val.length; + if (this.length instanceof NumberT) { + len += this.length.size(); + } + + return len; + } + + encode(stream, buf, parent) { + if (this.length instanceof NumberT) { + this.length.encode(stream, buf.length); + } + + return stream.writeBuffer(buf); + } +} + +export {BufferT as Buffer}; diff --git a/node_modules/restructure/src/DecodeStream.js b/node_modules/restructure/src/DecodeStream.js new file mode 100644 index 0000000000000000000000000000000000000000..226ffa1272d2758c10d2d9f9af01dd2dfa647575 --- /dev/null +++ b/node_modules/restructure/src/DecodeStream.js @@ -0,0 +1,85 @@ +// Node back-compat. +const ENCODING_MAPPING = { + utf16le: 'utf-16le', + ucs2: 'utf-16le', + utf16be: 'utf-16be' +} + +export class DecodeStream { + constructor(buffer) { + this.buffer = buffer; + this.view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + this.pos = 0; + this.length = this.buffer.length; + } + + readString(length, encoding = 'ascii') { + encoding = ENCODING_MAPPING[encoding] || encoding; + + let buf = this.readBuffer(length); + try { + let decoder = new TextDecoder(encoding); + return decoder.decode(buf); + } catch (err) { + return buf; + } + } + + readBuffer(length) { + return this.buffer.slice(this.pos, (this.pos += length)); + } + + readUInt24BE() { + return (this.readUInt16BE() << 8) + this.readUInt8(); + } + + readUInt24LE() { + return this.readUInt16LE() + (this.readUInt8() << 16); + } + + readInt24BE() { + return (this.readInt16BE() << 8) + this.readUInt8(); + } + + readInt24LE() { + return this.readUInt16LE() + (this.readInt8() << 16); + } +} + +DecodeStream.TYPES = { + UInt8: 1, + UInt16: 2, + UInt24: 3, + UInt32: 4, + Int8: 1, + Int16: 2, + Int24: 3, + Int32: 4, + Float: 4, + Double: 8 +}; + +for (let key of Object.getOwnPropertyNames(DataView.prototype)) { + if (key.slice(0, 3) === 'get') { + let type = key.slice(3).replace('Ui', 'UI'); + if (type === 'Float32') { + type = 'Float'; + } else if (type === 'Float64') { + type = 'Double'; + } + let bytes = DecodeStream.TYPES[type]; + DecodeStream.prototype['read' + type + (bytes === 1 ? '' : 'BE')] = function () { + const ret = this.view[key](this.pos, false); + this.pos += bytes; + return ret; + }; + + if (bytes !== 1) { + DecodeStream.prototype['read' + type + 'LE'] = function () { + const ret = this.view[key](this.pos, true); + this.pos += bytes; + return ret; + }; + } + } +} diff --git a/node_modules/restructure/src/EncodeStream.js b/node_modules/restructure/src/EncodeStream.js new file mode 100644 index 0000000000000000000000000000000000000000..64fb4cbc1bba6cbc1552b1512853b54565950d54 --- /dev/null +++ b/node_modules/restructure/src/EncodeStream.js @@ -0,0 +1,129 @@ +import {DecodeStream} from './DecodeStream.js'; + +const textEncoder = new TextEncoder(); +const isBigEndian = new Uint8Array(new Uint16Array([0x1234]).buffer)[0] == 0x12; + +export class EncodeStream { + constructor(buffer) { + this.buffer = buffer; + this.view = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength); + this.pos = 0; + } + + writeBuffer(buffer) { + this.buffer.set(buffer, this.pos); + this.pos += buffer.length; + } + + writeString(string, encoding = 'ascii') { + let buf; + switch (encoding) { + case 'utf16le': + case 'utf16-le': + case 'ucs2': // node treats this the same as utf16. + buf = stringToUtf16(string, isBigEndian); + break; + + case 'utf16be': + case 'utf16-be': + buf = stringToUtf16(string, !isBigEndian); + break; + + case 'utf8': + buf = textEncoder.encode(string); + break; + + case 'ascii': + buf = stringToAscii(string); + break; + + default: + throw new Error(`Unsupported encoding: ${encoding}`); + } + + this.writeBuffer(buf); + } + + writeUInt24BE(val) { + this.buffer[this.pos++] = (val >>> 16) & 0xff; + this.buffer[this.pos++] = (val >>> 8) & 0xff; + this.buffer[this.pos++] = val & 0xff; + } + + writeUInt24LE(val) { + this.buffer[this.pos++] = val & 0xff; + this.buffer[this.pos++] = (val >>> 8) & 0xff; + this.buffer[this.pos++] = (val >>> 16) & 0xff; + } + + writeInt24BE(val) { + if (val >= 0) { + this.writeUInt24BE(val); + } else { + this.writeUInt24BE(val + 0xffffff + 1); + } + } + + writeInt24LE(val) { + if (val >= 0) { + this.writeUInt24LE(val); + } else { + this.writeUInt24LE(val + 0xffffff + 1); + } + } + + fill(val, length) { + if (length < this.buffer.length) { + this.buffer.fill(val, this.pos, this.pos + length); + this.pos += length; + } else { + const buf = new Uint8Array(length); + buf.fill(val); + this.writeBuffer(buf); + } + } +} + +function stringToUtf16(string, swap) { + let buf = new Uint16Array(string.length); + for (let i = 0; i < string.length; i++) { + let code = string.charCodeAt(i); + if (swap) { + code = (code >> 8) | ((code & 0xff) << 8); + } + buf[i] = code; + } + return new Uint8Array(buf.buffer); +} + +function stringToAscii(string) { + let buf = new Uint8Array(string.length); + for (let i = 0; i < string.length; i++) { + // Match node.js behavior - encoding allows 8-bit rather than 7-bit. + buf[i] = string.charCodeAt(i); + } + return buf; +} + +for (let key of Object.getOwnPropertyNames(DataView.prototype)) { + if (key.slice(0, 3) === 'set') { + let type = key.slice(3).replace('Ui', 'UI'); + if (type === 'Float32') { + type = 'Float'; + } else if (type === 'Float64') { + type = 'Double'; + } + let bytes = DecodeStream.TYPES[type]; + EncodeStream.prototype['write' + type + (bytes === 1 ? '' : 'BE')] = function (value) { + this.view[key](this.pos, value, false); + this.pos += bytes; + }; + + if (bytes !== 1) { + EncodeStream.prototype['write' + type + 'LE'] = function (value) { + this.view[key](this.pos, value, true); + this.pos += bytes; + }; + } + } +} diff --git a/node_modules/restructure/src/Enum.js b/node_modules/restructure/src/Enum.js new file mode 100644 index 0000000000000000000000000000000000000000..b61d0743be3544632643498ad4f2b45e07100aee --- /dev/null +++ b/node_modules/restructure/src/Enum.js @@ -0,0 +1,27 @@ +import {Base} from './Base.js'; + +export class Enum extends Base { + constructor(type, options = []) { + super(); + this.type = type; + this.options = options; + } + + decode(stream) { + const index = this.type.decode(stream); + return this.options[index] || index; + } + + size() { + return this.type.size(); + } + + encode(stream, val) { + const index = this.options.indexOf(val); + if (index === -1) { + throw new Error(`Unknown option in enum: ${val}`); + } + + return this.type.encode(stream, index); + } +} diff --git a/node_modules/restructure/src/LazyArray.js b/node_modules/restructure/src/LazyArray.js new file mode 100644 index 0000000000000000000000000000000000000000..d378fffcf5b31653507a60f05676b3365e28e2a1 --- /dev/null +++ b/node_modules/restructure/src/LazyArray.js @@ -0,0 +1,74 @@ +import {Array as ArrayT} from './Array.js'; +import {Number as NumberT} from './Number.js'; +import * as utils from './utils.js'; + +export class LazyArray extends ArrayT { + decode(stream, parent) { + const { pos } = stream; + const length = utils.resolveLength(this.length, stream, parent); + + if (this.length instanceof NumberT) { + parent = { + parent, + _startOffset: pos, + _currentOffset: 0, + _length: length + }; + } + + const res = new LazyArrayValue(this.type, length, stream, parent); + + stream.pos += length * this.type.size(null, parent); + return res; + } + + size(val, ctx) { + if (val instanceof LazyArrayValue) { + val = val.toArray(); + } + + return super.size(val, ctx); + } + + encode(stream, val, ctx) { + if (val instanceof LazyArrayValue) { + val = val.toArray(); + } + + return super.encode(stream, val, ctx); + } +} + +class LazyArrayValue { + constructor(type, length, stream, ctx) { + this.type = type; + this.length = length; + this.stream = stream; + this.ctx = ctx; + this.base = this.stream.pos; + this.items = []; + } + + get(index) { + if ((index < 0) || (index >= this.length)) { + return undefined; + } + + if (this.items[index] == null) { + const { pos } = this.stream; + this.stream.pos = this.base + (this.type.size(null, this.ctx) * index); + this.items[index] = this.type.decode(this.stream, this.ctx); + this.stream.pos = pos; + } + + return this.items[index]; + } + + toArray() { + const result = []; + for (let i = 0, end = this.length; i < end; i++) { + result.push(this.get(i)); + } + return result; + } +} diff --git a/node_modules/restructure/src/Number.js b/node_modules/restructure/src/Number.js new file mode 100644 index 0000000000000000000000000000000000000000..da7e875e7faa586062ed436a483f80c81d1e0af1 --- /dev/null +++ b/node_modules/restructure/src/Number.js @@ -0,0 +1,77 @@ +import {DecodeStream} from './DecodeStream.js'; +import {Base} from './Base.js'; + +class NumberT extends Base { + constructor(type, endian = 'BE') { + super(); + this.type = type; + this.endian = endian; + this.fn = this.type; + if (this.type[this.type.length - 1] !== '8') { + this.fn += this.endian; + } + } + + size() { + return DecodeStream.TYPES[this.type]; + } + + decode(stream) { + return stream[`read${this.fn}`](); + } + + encode(stream, val) { + return stream[`write${this.fn}`](val); + } +} + +export {NumberT as Number}; + +export const uint8 = new NumberT('UInt8'); +export const uint16be = new NumberT('UInt16', 'BE'); +export const uint16 = uint16be; +export const uint16le = new NumberT('UInt16', 'LE'); +export const uint24be = new NumberT('UInt24', 'BE'); +export const uint24 = uint24be; +export const uint24le = new NumberT('UInt24', 'LE'); +export const uint32be = new NumberT('UInt32', 'BE'); +export const uint32 = uint32be; +export const uint32le = new NumberT('UInt32', 'LE'); +export const int8 = new NumberT('Int8'); +export const int16be = new NumberT('Int16', 'BE'); +export const int16 = int16be; +export const int16le = new NumberT('Int16', 'LE'); +export const int24be = new NumberT('Int24', 'BE'); +export const int24 = int24be; +export const int24le = new NumberT('Int24', 'LE'); +export const int32be = new NumberT('Int32', 'BE'); +export const int32 = int32be; +export const int32le = new NumberT('Int32', 'LE'); +export const floatbe = new NumberT('Float', 'BE'); +export const float = floatbe; +export const floatle = new NumberT('Float', 'LE'); +export const doublebe = new NumberT('Double', 'BE'); +export const double = doublebe; +export const doublele = new NumberT('Double', 'LE'); + +export class Fixed extends NumberT { + constructor(size, endian, fracBits = size >> 1) { + super(`Int${size}`, endian); + this._point = 1 << fracBits; + } + + decode(stream) { + return super.decode(stream) / this._point; + } + + encode(stream, val) { + return super.encode(stream, (val * this._point) | 0); + } +} + +export const fixed16be = new Fixed(16, 'BE'); +export const fixed16 = fixed16be; +export const fixed16le = new Fixed(16, 'LE'); +export const fixed32be = new Fixed(32, 'BE'); +export const fixed32 = fixed32be; +export const fixed32le = new Fixed(32, 'LE'); diff --git a/node_modules/restructure/src/Optional.js b/node_modules/restructure/src/Optional.js new file mode 100644 index 0000000000000000000000000000000000000000..3aa69280f91300005012c7e7b88d08d1524dffb4 --- /dev/null +++ b/node_modules/restructure/src/Optional.js @@ -0,0 +1,44 @@ +import {Base} from './Base.js'; + +export class Optional extends Base { + constructor(type, condition = true) { + super(); + this.type = type; + this.condition = condition; + } + + decode(stream, parent) { + let { condition } = this; + if (typeof condition === 'function') { + condition = condition.call(parent, parent); + } + + if (condition) { + return this.type.decode(stream, parent); + } + } + + size(val, parent) { + let { condition } = this; + if (typeof condition === 'function') { + condition = condition.call(parent, parent); + } + + if (condition) { + return this.type.size(val, parent); + } else { + return 0; + } + } + + encode(stream, val, parent) { + let { condition } = this; + if (typeof condition === 'function') { + condition = condition.call(parent, parent); + } + + if (condition) { + return this.type.encode(stream, val, parent); + } + } +} diff --git a/node_modules/restructure/src/Pointer.js b/node_modules/restructure/src/Pointer.js new file mode 100644 index 0000000000000000000000000000000000000000..31b1ed2fe53cf3655b664737f9b5d0bdd7af56a1 --- /dev/null +++ b/node_modules/restructure/src/Pointer.js @@ -0,0 +1,167 @@ +import * as utils from './utils.js'; +import {Base} from './Base.js'; + +export class Pointer extends Base { + constructor(offsetType, type, options = {}) { + super(); + this.offsetType = offsetType; + this.type = type; + this.options = options; + if (this.type === 'void') { this.type = null; } + if (this.options.type == null) { this.options.type = 'local'; } + if (this.options.allowNull == null) { this.options.allowNull = true; } + if (this.options.nullValue == null) { this.options.nullValue = 0; } + if (this.options.lazy == null) { this.options.lazy = false; } + if (this.options.relativeTo) { + if (typeof this.options.relativeTo !== 'function') { + throw new Error('relativeTo option must be a function'); + } + this.relativeToGetter = options.relativeTo; + } + } + + decode(stream, ctx) { + const offset = this.offsetType.decode(stream, ctx); + + // handle NULL pointers + if ((offset === this.options.nullValue) && this.options.allowNull) { + return null; + } + + let relative; + switch (this.options.type) { + case 'local': relative = ctx._startOffset; break; + case 'immediate': relative = stream.pos - this.offsetType.size(); break; + case 'parent': relative = ctx.parent._startOffset; break; + default: + var c = ctx; + while (c.parent) { + c = c.parent; + } + + relative = c._startOffset || 0; + } + + if (this.options.relativeTo) { + relative += this.relativeToGetter(ctx); + } + + const ptr = offset + relative; + + if (this.type != null) { + let val = null; + const decodeValue = () => { + if (val != null) { return val; } + + const { pos } = stream; + stream.pos = ptr; + val = this.type.decode(stream, ctx); + stream.pos = pos; + return val; + }; + + // If this is a lazy pointer, define a getter to decode only when needed. + // This obviously only works when the pointer is contained by a Struct. + if (this.options.lazy) { + return new utils.PropertyDescriptor({ + get: decodeValue}); + } + + return decodeValue(); + } else { + return ptr; + } + } + + size(val, ctx) { + const parent = ctx; + switch (this.options.type) { + case 'local': case 'immediate': + break; + case 'parent': + ctx = ctx.parent; + break; + default: // global + while (ctx.parent) { + ctx = ctx.parent; + } + } + + let { type } = this; + if (type == null) { + if (!(val instanceof VoidPointer)) { + throw new Error("Must be a VoidPointer"); + } + + ({ type } = val); + val = val.value; + } + + if (val && ctx) { + // Must be written as two separate lines rather than += in case `type.size` mutates ctx.pointerSize. + let size = type.size(val, parent); + ctx.pointerSize += size; + } + + return this.offsetType.size(); + } + + encode(stream, val, ctx) { + let relative; + const parent = ctx; + if ((val == null)) { + this.offsetType.encode(stream, this.options.nullValue); + return; + } + + switch (this.options.type) { + case 'local': + relative = ctx.startOffset; + break; + case 'immediate': + relative = stream.pos + this.offsetType.size(val, parent); + break; + case 'parent': + ctx = ctx.parent; + relative = ctx.startOffset; + break; + default: // global + relative = 0; + while (ctx.parent) { + ctx = ctx.parent; + } + } + + if (this.options.relativeTo) { + relative += this.relativeToGetter(parent.val); + } + + this.offsetType.encode(stream, ctx.pointerOffset - relative); + + let { type } = this; + if (type == null) { + if (!(val instanceof VoidPointer)) { + throw new Error("Must be a VoidPointer"); + } + + ({ type } = val); + val = val.value; + } + + ctx.pointers.push({ + type, + val, + parent + }); + + return ctx.pointerOffset += type.size(val, parent); + } +} + +// A pointer whose type is determined at decode time +export class VoidPointer { + constructor(type, value) { + this.type = type; + this.value = value; + } +} diff --git a/node_modules/restructure/src/Reserved.js b/node_modules/restructure/src/Reserved.js new file mode 100644 index 0000000000000000000000000000000000000000..c198cd9f51eed5e59f0cde47574cab7801ec5be4 --- /dev/null +++ b/node_modules/restructure/src/Reserved.js @@ -0,0 +1,23 @@ +import {Base} from './Base.js'; +import * as utils from './utils.js'; + +export class Reserved extends Base { + constructor(type, count = 1) { + super(); + this.type = type; + this.count = count; + } + decode(stream, parent) { + stream.pos += this.size(null, parent); + return undefined; + } + + size(data, parent) { + const count = utils.resolveLength(this.count, null, parent); + return this.type.size() * count; + } + + encode(stream, val, parent) { + return stream.fill(0, this.size(val, parent)); + } +} diff --git a/node_modules/restructure/src/String.js b/node_modules/restructure/src/String.js new file mode 100644 index 0000000000000000000000000000000000000000..a066b12b00eb86d16cf48fff07e463691615f527 --- /dev/null +++ b/node_modules/restructure/src/String.js @@ -0,0 +1,155 @@ +import {Base} from './Base.js'; +import {Number as NumberT} from './Number.js'; +import * as utils from './utils.js'; + +class StringT extends Base { + constructor(length, encoding = 'ascii') { + super(); + this.length = length; + this.encoding = encoding; + } + + decode(stream, parent) { + let length, pos; + + let { encoding } = this; + if (typeof encoding === 'function') { + encoding = encoding.call(parent, parent) || 'ascii'; + } + let width = encodingWidth(encoding); + + if (this.length != null) { + length = utils.resolveLength(this.length, stream, parent); + } else { + let buffer; + ({buffer, length, pos} = stream); + + while ((pos < length - width + 1) && + (buffer[pos] !== 0x00 || + (width === 2 && buffer[pos+1] !== 0x00) + )) { + pos += width; + } + + length = pos - stream.pos; + } + + + const string = stream.readString(length, encoding); + + if ((this.length == null) && (stream.pos < stream.length)) { + stream.pos+=width; + } + + return string; + } + + size(val, parent) { + // Use the defined value if no value was given + if (val === undefined || val === null) { + return utils.resolveLength(this.length, null, parent); + } + + let { encoding } = this; + if (typeof encoding === 'function') { + encoding = encoding.call(parent != null ? parent.val : undefined, parent != null ? parent.val : undefined) || 'ascii'; + } + + if (encoding === 'utf16be') { + encoding = 'utf16le'; + } + + let size = byteLength(val, encoding); + if (this.length instanceof NumberT) { + size += this.length.size(); + } + + if ((this.length == null)) { + size += encodingWidth(encoding); + } + + return size; + } + + encode(stream, val, parent) { + let { encoding } = this; + if (typeof encoding === 'function') { + encoding = encoding.call(parent != null ? parent.val : undefined, parent != null ? parent.val : undefined) || 'ascii'; + } + + if (this.length instanceof NumberT) { + this.length.encode(stream, byteLength(val, encoding)); + } + + stream.writeString(val, encoding); + + if ((this.length == null)) { + return encodingWidth(encoding) == 2 ? + stream.writeUInt16LE(0x0000) : + stream.writeUInt8(0x00); + } + } +} + +function encodingWidth(encoding) { + switch(encoding) { + case 'ascii': + case 'utf8': // utf8 is a byte-based encoding for zero-term string + return 1; + case 'utf16le': + case 'utf16-le': + case 'utf-16be': + case 'utf-16le': + case 'utf16be': + case 'utf16-be': + case 'ucs2': + return 2; + default: + //TODO: assume all other encodings are 1-byters + //throw new Error('Unknown encoding ' + encoding); + return 1; + } +} + +function byteLength(string, encoding) { + switch (encoding) { + case 'ascii': + return string.length; + case 'utf8': + let len = 0; + for (let i = 0; i < string.length; i++) { + let c = string.charCodeAt(i); + + if (c >= 0xd800 && c <= 0xdbff && i < string.length - 1) { + let c2 = string.charCodeAt(++i); + if ((c2 & 0xfc00) === 0xdc00) { + c = ((c & 0x3ff) << 10) + (c2 & 0x3ff) + 0x10000; + } else { + // unmatched surrogate. + i--; + } + } + + if ((c & 0xffffff80) === 0) { + len++; + } else if ((c & 0xfffff800) === 0) { + len += 2; + } else if ((c & 0xffff0000) === 0) { + len += 3; + } else if ((c & 0xffe00000) === 0) { + len += 4; + } + } + return len; + case 'utf16le': + case 'utf16-le': + case 'utf16be': + case 'utf16-be': + case 'ucs2': + return string.length * 2; + default: + throw new Error('Unknown encoding ' + encoding); + } +} + +export {StringT as String}; diff --git a/node_modules/restructure/src/Struct.js b/node_modules/restructure/src/Struct.js new file mode 100644 index 0000000000000000000000000000000000000000..335eaf151570cd8ebb9ba665fa8a9c3dc7f312b4 --- /dev/null +++ b/node_modules/restructure/src/Struct.js @@ -0,0 +1,113 @@ +import {Base} from './Base.js'; +import * as utils from './utils.js'; + +export class Struct extends Base { + constructor(fields = {}) { + super(); + this.fields = fields; + } + + decode(stream, parent, length = 0) { + const res = this._setup(stream, parent, length); + this._parseFields(stream, res, this.fields); + + if (this.process != null) { + this.process.call(res, stream); + } + return res; + } + + _setup(stream, parent, length) { + const res = {}; + + // define hidden properties + Object.defineProperties(res, { + parent: { value: parent }, + _startOffset: { value: stream.pos }, + _currentOffset: { value: 0, writable: true }, + _length: { value: length } + }); + + return res; + } + + _parseFields(stream, res, fields) { + for (let key in fields) { + var val; + const type = fields[key]; + if (typeof type === 'function') { + val = type.call(res, res); + } else { + val = type.decode(stream, res); + } + + if (val !== undefined) { + if (val instanceof utils.PropertyDescriptor) { + Object.defineProperty(res, key, val); + } else { + res[key] = val; + } + } + + res._currentOffset = stream.pos - res._startOffset; + } + + } + + size(val, parent, includePointers = true) { + if (val == null) { val = {}; } + const ctx = { + parent, + val, + pointerSize: 0 + }; + + if (this.preEncode != null) { + this.preEncode.call(val); + } + + let size = 0; + for (let key in this.fields) { + const type = this.fields[key]; + if (type.size != null) { + size += type.size(val[key], ctx); + } + } + + if (includePointers) { + size += ctx.pointerSize; + } + + return size; + } + + encode(stream, val, parent) { + let type; + if (this.preEncode != null) { + this.preEncode.call(val, stream); + } + + const ctx = { + pointers: [], + startOffset: stream.pos, + parent, + val, + pointerSize: 0 + }; + + ctx.pointerOffset = stream.pos + this.size(val, ctx, false); + + for (let key in this.fields) { + type = this.fields[key]; + if (type.encode != null) { + type.encode(stream, val[key], ctx); + } + } + + let i = 0; + while (i < ctx.pointers.length) { + const ptr = ctx.pointers[i++]; + ptr.type.encode(stream, ptr.val, ptr.parent); + } + } +} diff --git a/node_modules/restructure/src/VersionedStruct.js b/node_modules/restructure/src/VersionedStruct.js new file mode 100644 index 0000000000000000000000000000000000000000..36730fe40d8d77c427c839dbba75cc01cc9bb8d6 --- /dev/null +++ b/node_modules/restructure/src/VersionedStruct.js @@ -0,0 +1,139 @@ +import {Struct} from './Struct.js'; + +const getPath = (object, pathArray) => { + return pathArray.reduce((prevObj, key) => prevObj && prevObj[key], object); +}; + +export class VersionedStruct extends Struct { + constructor(type, versions = {}) { + super(); + this.type = type; + this.versions = versions; + if (typeof type === 'string') { + this.versionPath = type.split('.'); + } + } + + decode(stream, parent, length = 0) { + const res = this._setup(stream, parent, length); + + if (typeof this.type === 'string') { + res.version = getPath(parent, this.versionPath); + } else { + res.version = this.type.decode(stream); + } + + if (this.versions.header) { + this._parseFields(stream, res, this.versions.header); + } + + const fields = this.versions[res.version]; + if ((fields == null)) { + throw new Error(`Unknown version ${res.version}`); + } + + if (fields instanceof VersionedStruct) { + return fields.decode(stream, parent); + } + + this._parseFields(stream, res, fields); + + if (this.process != null) { + this.process.call(res, stream); + } + return res; + } + + size(val, parent, includePointers = true) { + let key, type; + if (!val) { + throw new Error('Not a fixed size'); + } + + if (this.preEncode != null) { + this.preEncode.call(val); + } + + const ctx = { + parent, + val, + pointerSize: 0 + }; + + let size = 0; + if (typeof this.type !== 'string') { + size += this.type.size(val.version, ctx); + } + + if (this.versions.header) { + for (key in this.versions.header) { + type = this.versions.header[key]; + if (type.size != null) { + size += type.size(val[key], ctx); + } + } + } + + const fields = this.versions[val.version]; + if ((fields == null)) { + throw new Error(`Unknown version ${val.version}`); + } + + for (key in fields) { + type = fields[key]; + if (type.size != null) { + size += type.size(val[key], ctx); + } + } + + if (includePointers) { + size += ctx.pointerSize; + } + + return size; + } + + encode(stream, val, parent) { + let key, type; + if (this.preEncode != null) { + this.preEncode.call(val, stream); + } + + const ctx = { + pointers: [], + startOffset: stream.pos, + parent, + val, + pointerSize: 0 + }; + + ctx.pointerOffset = stream.pos + this.size(val, ctx, false); + + if (typeof this.type !== 'string') { + this.type.encode(stream, val.version); + } + + if (this.versions.header) { + for (key in this.versions.header) { + type = this.versions.header[key]; + if (type.encode != null) { + type.encode(stream, val[key], ctx); + } + } + } + + const fields = this.versions[val.version]; + for (key in fields) { + type = fields[key]; + if (type.encode != null) { + type.encode(stream, val[key], ctx); + } + } + + let i = 0; + while (i < ctx.pointers.length) { + const ptr = ctx.pointers[i++]; + ptr.type.encode(stream, ptr.val, ptr.parent); + } + } +} diff --git a/node_modules/restructure/src/utils.js b/node_modules/restructure/src/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..08744ec4abda986e8585211ec497d003e622a1d7 --- /dev/null +++ b/node_modules/restructure/src/utils.js @@ -0,0 +1,35 @@ +import {Number as NumberT} from './Number.js'; + +export function resolveLength(length, stream, parent) { + let res; + if (typeof length === 'number') { + res = length; + + } else if (typeof length === 'function') { + res = length.call(parent, parent); + + } else if (parent && (typeof length === 'string')) { + res = parent[length]; + + } else if (stream && length instanceof NumberT) { + res = length.decode(stream); + } + + if (isNaN(res)) { + throw new Error('Not a fixed size'); + } + + return res; +}; + +export class PropertyDescriptor { + constructor(opts = {}) { + this.enumerable = true; + this.configurable = true; + + for (let key in opts) { + const val = opts[key]; + this[key] = val; + } + } +} diff --git a/node_modules/restructure/test/Array.js b/node_modules/restructure/test/Array.js new file mode 100644 index 0000000000000000000000000000000000000000..bdf5fac5df30a808b052bb7d41fd6473dd70e051 --- /dev/null +++ b/node_modules/restructure/test/Array.js @@ -0,0 +1,103 @@ +import assert from 'assert'; +import {Array as ArrayT, Pointer, uint8, uint16, DecodeStream, EncodeStream} from 'restructure'; + +describe('Array', function() { + describe('decode', function() { + it('should decode fixed length', function() { + const buffer = new Uint8Array([1, 2, 3, 4, 5]); + const array = new ArrayT(uint8, 4); + assert.deepEqual(array.fromBuffer(buffer), [1, 2, 3, 4]); + }); + + it('should decode fixed amount of bytes', function() { + const buffer = new Uint8Array([1, 2, 3, 4, 5]); + const array = new ArrayT(uint16, 4, 'bytes'); + assert.deepEqual(array.fromBuffer(buffer), [258, 772]); + }); + + it('should decode length from parent key', function() { + const stream = new DecodeStream(new Uint8Array([1, 2, 3, 4, 5])); + const array = new ArrayT(uint8, 'len'); + assert.deepEqual(array.decode(stream, {len: 4}), [1, 2, 3, 4]); + }); + + it('should decode amount of bytes from parent key', function() { + const stream = new DecodeStream(new Uint8Array([1, 2, 3, 4, 5])); + const array = new ArrayT(uint16, 'len', 'bytes'); + assert.deepEqual(array.decode(stream, {len: 4}), [258, 772]); + }); + + it('should decode length as number before array', function() { + const buffer = new Uint8Array([4, 1, 2, 3, 4, 5]); + const array = new ArrayT(uint8, uint8); + assert.deepEqual(array.fromBuffer(buffer), [1, 2, 3, 4]); + }); + + it('should decode amount of bytes as number before array', function() { + const buffer = new Uint8Array([4, 1, 2, 3, 4, 5]); + const array = new ArrayT(uint16, uint8, 'bytes'); + assert.deepEqual(array.fromBuffer(buffer), [258, 772]); + }); + + it('should decode length from function', function() { + const buffer = new Uint8Array([1, 2, 3, 4, 5]); + const array = new ArrayT(uint8, function() { return 4; }); + assert.deepEqual(array.fromBuffer(buffer), [1, 2, 3, 4]); + }); + + it('should decode amount of bytes from function', function() { + const buffer = new Uint8Array([1, 2, 3, 4, 5]); + const array = new ArrayT(uint16, (function() { return 4; }), 'bytes'); + assert.deepEqual(array.fromBuffer(buffer), [258, 772]); + }); + + it('should decode to the end of the parent if no length is given', function() { + const stream = new DecodeStream(new Uint8Array([1, 2, 3, 4, 5])); + const array = new ArrayT(uint8); + assert.deepEqual(array.decode(stream, {_length: 4, _startOffset: 0}), [1, 2, 3, 4]); + }); + + it('should decode to the end of the stream if no parent and length is given', function() { + const buffer = new Uint8Array([1, 2, 3, 4]); + const array = new ArrayT(uint8); + assert.deepEqual(array.fromBuffer(buffer), [1, 2, 3, 4]); + }); + }); + + describe('size', function() { + it('should use array length', function() { + const array = new ArrayT(uint8, 10); + assert.equal(array.size([1, 2, 3, 4]), 4); + }); + + it('should add size of length field before string', function() { + const array = new ArrayT(uint8, uint8); + assert.equal(array.size([1, 2, 3, 4]), 5); + }); + + it('should use defined length if no value given', function() { + const array = new ArrayT(uint8, 10); + assert.equal(array.size(), 10); + }); + }); + + describe('encode', function() { + it('should encode using array length', function() { + const array = new ArrayT(uint8, 10); + const buffer = array.toBuffer([1, 2, 3, 4]); + assert.deepEqual(buffer, new Uint8Array([1, 2, 3, 4])); + }); + + it('should encode length as number before array', function() { + const array = new ArrayT(uint8, uint8); + const buffer = array.toBuffer([1, 2, 3, 4]); + assert.deepEqual(buffer, new Uint8Array([4, 1, 2, 3, 4])); + }); + + it('should add pointers after array if length is encoded at start', function() { + const array = new ArrayT(new Pointer(uint8, uint8), uint8); + const buffer = array.toBuffer([1, 2, 3, 4]); + assert.deepEqual(buffer, new Uint8Array([4, 5, 6, 7, 8, 1, 2, 3, 4])); + }); + }); +}); diff --git a/node_modules/restructure/test/Bitfield.js b/node_modules/restructure/test/Bitfield.js new file mode 100644 index 0000000000000000000000000000000000000000..6cef0f81fcc189285325231b58ebd765d13f63f2 --- /dev/null +++ b/node_modules/restructure/test/Bitfield.js @@ -0,0 +1,29 @@ +import assert from 'assert'; +import {Bitfield, uint8, DecodeStream, EncodeStream} from 'restructure'; + +describe('Bitfield', function() { + const bitfield = new Bitfield(uint8, ['Jack', 'Kack', 'Lack', 'Mack', 'Nack', 'Oack', 'Pack', 'Quack']); + const JACK = 1 << 0; + const KACK = 1 << 1; + const LACK = 1 << 2; + const MACK = 1 << 3; + const NACK = 1 << 4; + const OACK = 1 << 5; + const PACK = 1 << 6; + const QUACK = 1 << 7; + + it('should have the right size', () => assert.equal(bitfield.size(), 1)); + + it('should decode', function() { + const buffer = new Uint8Array([JACK | MACK | PACK | NACK | QUACK]); + assert.deepEqual( + bitfield.fromBuffer(buffer), + {Jack: true, Kack: false, Lack: false, Mack: true, Nack: true, Oack: false, Pack: true, Quack: true} + ); + }); + + it('should encode', function() { + let buffer = bitfield.toBuffer({Jack: true, Kack: false, Lack: false, Mack: true, Nack: true, Oack: false, Pack: true, Quack: true}); + assert.deepEqual(buffer, Buffer.from([JACK | MACK | PACK | NACK | QUACK])); + }); +}); diff --git a/node_modules/restructure/test/Boolean.js b/node_modules/restructure/test/Boolean.js new file mode 100644 index 0000000000000000000000000000000000000000..7a9096f3685e7fcc6bc257d109aab04b2e8eee46 --- /dev/null +++ b/node_modules/restructure/test/Boolean.js @@ -0,0 +1,39 @@ +import assert from 'assert'; +import {Boolean, uint8, DecodeStream, EncodeStream} from 'restructure'; + +describe('Boolean', function() { + describe('decode', function() { + it('should decode 0 as false', function() { + const buffer = new Uint8Array([0]); + const boolean = new Boolean(uint8); + assert.deepEqual(boolean.fromBuffer(buffer), false); + }); + + it('should decode 1 as true', function() { + const buffer = new Uint8Array([1]); + const boolean = new Boolean(uint8); + assert.deepEqual(boolean.fromBuffer(buffer), true); + }); + }); + + describe('size', () => + it('should return given type size', function() { + const boolean = new Boolean(uint8); + assert.deepEqual(boolean.size(), 1); + }) + ); + + describe('encode', function() { + it('should encode false as 0', function() { + const boolean = new Boolean(uint8); + const buffer = boolean.toBuffer(false); + assert.deepEqual(buffer, Buffer.from([0])); + }); + + it('should encode true as 1', function() { + const boolean = new Boolean(uint8); + const buffer = boolean.toBuffer(true); + assert.deepEqual(buffer, Buffer.from([1])); + }); + }); +}); diff --git a/node_modules/restructure/test/Buffer.js b/node_modules/restructure/test/Buffer.js new file mode 100644 index 0000000000000000000000000000000000000000..70f453644e21e3b295eb2fd8b9fa7ba2bdb45245 --- /dev/null +++ b/node_modules/restructure/test/Buffer.js @@ -0,0 +1,45 @@ +import assert from 'assert'; +import {Buffer as BufferT, uint8, DecodeStream, EncodeStream} from 'restructure'; + +describe('Buffer', function() { + describe('decode', function() { + it('should decode', function() { + const buffer = new Uint8Array([0xab, 0xff]); + const buf = new BufferT(2); + assert.deepEqual(buf.fromBuffer(buffer), new Uint8Array([0xab, 0xff])); + }); + + it('should decode with parent key length', function() { + const stream = new DecodeStream(new Uint8Array([0xab, 0xff, 0x1f, 0xb6])); + const buf = new BufferT('len'); + assert.deepEqual(buf.decode(stream, {len: 3}), new Uint8Array([0xab, 0xff, 0x1f])); + assert.deepEqual(buf.decode(stream, {len: 1}), new Uint8Array([0xb6])); + }); +}); + + describe('size', function() { + it('should return size', function() { + const buf = new BufferT(2); + assert.equal(buf.size(new Uint8Array([0xab, 0xff])), 2); + }); + + it('should use defined length if no value given', function() { + const array = new BufferT(10); + assert.equal(array.size(), 10); + }); + }); + + describe('encode', function() { + it('should encode', function() { + const buf = new BufferT(2); + const buffer = buf.toBuffer(new Uint8Array([0xab, 0xff])); + assert.deepEqual(buffer, new Uint8Array([0xab, 0xff])); + }); + + it('should encode length before buffer', function() { + const buf = new BufferT(uint8); + const buffer = buf.toBuffer(new Uint8Array([0xab, 0xff])); + assert.deepEqual(buffer, new Uint8Array([2, 0xab, 0xff])); + }); + }); +}); diff --git a/node_modules/restructure/test/DecodeStream.js b/node_modules/restructure/test/DecodeStream.js new file mode 100644 index 0000000000000000000000000000000000000000..52f0b63be69d40811c0c44708a7ade7e51476e89 --- /dev/null +++ b/node_modules/restructure/test/DecodeStream.js @@ -0,0 +1,101 @@ +import {DecodeStream} from 'restructure'; +import assert from 'assert'; + +describe('DecodeStream', function() { + it('should read a buffer', function() { + const buf = new Uint8Array([1,2,3]); + const stream = new DecodeStream(buf); + assert.deepEqual(stream.readBuffer(buf.length), new Uint8Array([1,2,3])); + }); + + it('should readUInt16BE', function() { + const buf = new Uint8Array([0xab, 0xcd]); + const stream = new DecodeStream(buf); + assert.deepEqual(stream.readUInt16BE(), 0xabcd); + }); + + it('should readUInt16LE', function() { + const buf = new Uint8Array([0xab, 0xcd]); + const stream = new DecodeStream(buf); + assert.deepEqual(stream.readUInt16LE(), 0xcdab); + }); + + it('should readUInt24BE', function() { + const buf = new Uint8Array([0xab, 0xcd, 0xef]); + const stream = new DecodeStream(buf); + assert.deepEqual(stream.readUInt24BE(), 0xabcdef); + }); + + it('should readUInt24LE', function() { + const buf = new Uint8Array([0xab, 0xcd, 0xef]); + const stream = new DecodeStream(buf); + assert.deepEqual(stream.readUInt24LE(), 0xefcdab); + }); + + it('should readInt24BE', function() { + const buf = new Uint8Array([0xff, 0xab, 0x24]); + const stream = new DecodeStream(buf); + assert.deepEqual(stream.readInt24BE(), -21724); + }); + + it('should readInt24LE', function() { + const buf = new Uint8Array([0x24, 0xab, 0xff]); + const stream = new DecodeStream(buf); + assert.deepEqual(stream.readInt24LE(), -21724); + }); + + describe('readString', function() { + it('should decode ascii by default', function() { + const buf = Buffer.from('some text', 'ascii'); + const stream = new DecodeStream(buf); + assert.equal(stream.readString(buf.length), 'some text'); + }); + + it('should decode ascii', function() { + const buf = Buffer.from('some text', 'ascii'); + const stream = new DecodeStream(buf); + assert.equal(stream.readString(buf.length, 'ascii'), 'some text'); + }); + + it('should decode utf8', function() { + const buf = Buffer.from('unicode! 👍', 'utf8'); + const stream = new DecodeStream(buf); + assert.equal(stream.readString(buf.length, 'utf8'), 'unicode! 👍'); + }); + + it('should decode utf16le', function() { + const buf = Buffer.from('unicode! 👍', 'utf16le'); + const stream = new DecodeStream(buf); + assert.equal(stream.readString(buf.length, 'utf16le'), 'unicode! 👍'); + }); + + it('should decode ucs2', function() { + const buf = Buffer.from('unicode! 👍', 'ucs2'); + const stream = new DecodeStream(buf); + assert.equal(stream.readString(buf.length, 'ucs2'), 'unicode! 👍'); + }); + + it('should decode utf16be', function() { + const buf = Buffer.from('unicode! 👍', 'utf16le'); + for (let i = 0, end = buf.length - 1; i < end; i += 2) { + const byte = buf[i]; + buf[i] = buf[i + 1]; + buf[i + 1] = byte; + } + + const stream = new DecodeStream(buf); + assert.equal(stream.readString(buf.length, 'utf16be'), 'unicode! 👍'); + }); + + it('should decode macroman', function() { + const buf = new Uint8Array([0x8a, 0x63, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x64, 0x20, 0x63, 0x68, 0x87, 0x72, 0x61, 0x63, 0x74, 0x65, 0x72, 0x73]); + const stream = new DecodeStream(buf); + assert.equal(stream.readString(buf.length, 'mac'), 'äccented cháracters'); + }); + + it('should return a buffer for unsupported encodings', function() { + const stream = new DecodeStream(new Uint8Array([1, 2, 3])); + assert.deepEqual(stream.readString(3, 'unsupported'), new Uint8Array([1, 2, 3])); + }); +}); +}); diff --git a/node_modules/restructure/test/EncodeStream.js b/node_modules/restructure/test/EncodeStream.js new file mode 100644 index 0000000000000000000000000000000000000000..ecdd6c74e8c5656c19dcca991492f37c9405aaee --- /dev/null +++ b/node_modules/restructure/test/EncodeStream.js @@ -0,0 +1,104 @@ +import {EncodeStream} from 'restructure'; +import assert from 'assert'; + +describe('EncodeStream', function() { + it('should write a buffer', function() { + const stream = new EncodeStream(new Uint8Array(3)); + stream.writeBuffer(new Uint8Array([1,2,3])); + assert.deepEqual(stream.buffer, new Uint8Array([1,2,3])); + }); + + it('should writeUInt16BE', function() { + const stream = new EncodeStream(new Uint8Array(2)); + stream.writeUInt16BE(0xabcd); + assert.deepEqual(stream.buffer, new Uint8Array([0xab, 0xcd])); + }); + + it('should writeUInt16LE', function() { + const stream = new EncodeStream(new Uint8Array(2)); + stream.writeUInt16LE(0xcdab); + assert.deepEqual(stream.buffer, new Uint8Array([0xab, 0xcd])); + }); + + it('should writeUInt24BE', function() { + const stream = new EncodeStream(new Uint8Array(3)); + stream.writeUInt24BE(0xabcdef); + assert.deepEqual(stream.buffer, new Uint8Array([0xab, 0xcd, 0xef])); + }); + + it('should writeUInt24LE', function() { + const stream = new EncodeStream(new Uint8Array(3)); + stream.writeUInt24LE(0xabcdef); + assert.deepEqual(stream.buffer, new Uint8Array([0xef, 0xcd, 0xab])); + }); + + it('should writeInt24BE', function() { + const stream = new EncodeStream(new Uint8Array(6)); + stream.writeInt24BE(-21724); + stream.writeInt24BE(0xabcdef); + assert.deepEqual(stream.buffer, new Uint8Array([0xff, 0xab, 0x24, 0xab, 0xcd, 0xef])); + }); + + it('should writeInt24LE', function() { + const stream = new EncodeStream(new Uint8Array(6)); + stream.writeInt24LE(-21724); + stream.writeInt24LE(0xabcdef); + assert.deepEqual(stream.buffer, new Uint8Array([0x24, 0xab, 0xff, 0xef, 0xcd, 0xab])); + }); + + it('should fill', function() { + const stream = new EncodeStream(new Uint8Array(5)); + stream.fill(10, 5); + assert.deepEqual(stream.buffer, new Uint8Array([10, 10, 10, 10, 10])); + }); + + describe('writeString', function() { + it('should encode ascii by default', function() { + const expected = Buffer.from('some text', 'ascii'); + const stream = new EncodeStream(new Uint8Array(expected.length)); + stream.writeString('some text'); + assert.deepEqual(stream.buffer, expected); + }); + + it('should encode ascii', function() { + const expected = Buffer.from('some text', 'ascii'); + const stream = new EncodeStream(new Uint8Array(expected.length)); + stream.writeString('some text', 'ascii'); + assert.deepEqual(stream.buffer, expected); + }); + + it('should encode utf8', function() { + const expected = Buffer.from('unicode! 👍', 'utf8'); + const stream = new EncodeStream(new Uint8Array(expected.length)); + stream.writeString('unicode! 👍', 'utf8'); + assert.deepEqual(stream.buffer, expected); + }); + + it('should encode utf16le', function() { + const expected = Buffer.from('unicode! 👍', 'utf16le'); + const stream = new EncodeStream(new Uint8Array(expected.length)); + stream.writeString('unicode! 👍', 'utf16le'); + assert.deepEqual(stream.buffer, expected); + }); + + it('should encode ucs2', function() { + const expected = Buffer.from('unicode! 👍', 'ucs2'); + const stream = new EncodeStream(new Uint8Array(expected.length)); + stream.writeString('unicode! 👍', 'ucs2'); + assert.deepEqual(stream.buffer, expected); + }); + + it('should encode utf16be', function() { + const expected = Buffer.from('unicode! 👍', 'utf16le'); + for (let i = 0, end = expected.length - 1; i < end; i += 2) { + const byte = expected[i]; + expected[i] = expected[i + 1]; + expected[i + 1] = byte; + } + + const stream = new EncodeStream(new Uint8Array(expected.length)); + stream.writeString('unicode! 👍', 'utf16be'); + assert.deepEqual(stream.buffer, expected); + }); + }); +}); diff --git a/node_modules/restructure/test/Enum.js b/node_modules/restructure/test/Enum.js new file mode 100644 index 0000000000000000000000000000000000000000..2febf136e09b27fc136c7eb386bf79fc90bad561 --- /dev/null +++ b/node_modules/restructure/test/Enum.js @@ -0,0 +1,24 @@ +import assert from 'assert'; +import {Enum, uint8, DecodeStream, EncodeStream} from 'restructure'; + +describe('Enum', function() { + const e = new Enum(uint8, ['foo', 'bar', 'baz']); + it('should have the right size', () => assert.equal(e.size(), 1)); + + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([1, 2, 0])); + assert.equal(e.decode(stream), 'bar'); + assert.equal(e.decode(stream), 'baz'); + assert.equal(e.decode(stream), 'foo'); + }); + + it('should encode', function() { + assert.deepEqual(e.toBuffer('bar'), new Uint8Array([1])); + assert.deepEqual(e.toBuffer('baz'), new Uint8Array([2])); + assert.deepEqual(e.toBuffer('foo'), new Uint8Array([0])); + }); + + it('should throw on unknown option', function() { + return assert.throws(() => e.toBuffer('unknown')); + }); +}); diff --git a/node_modules/restructure/test/LazyArray.js b/node_modules/restructure/test/LazyArray.js new file mode 100644 index 0000000000000000000000000000000000000000..73f1e223ba519bff4ac44640b0e9ba967bf62dfe --- /dev/null +++ b/node_modules/restructure/test/LazyArray.js @@ -0,0 +1,59 @@ +import assert from 'assert'; +import {LazyArray, Pointer, uint8, uint16, DecodeStream, EncodeStream} from 'restructure'; + +describe('LazyArray', function() { + describe('decode', function() { + it('should decode items lazily', function() { + const stream = new DecodeStream(new Uint8Array([1, 2, 3, 4, 5])); + const array = new LazyArray(uint8, 4); + + const arr = array.decode(stream); + assert(!(arr instanceof Array)); + assert.equal(arr.length, 4); + assert.equal(stream.pos, 4); + + assert.equal(arr.get(0), 1); + assert.equal(arr.get(1), 2); + assert.equal(arr.get(2), 3); + assert.equal(arr.get(3), 4); + + assert.equal(arr.get(-1), null); + assert.equal(arr.get(5), null); + }); + + it('should be able to convert to an array', function() { + const stream = new DecodeStream(new Uint8Array([1, 2, 3, 4, 5])); + const array = new LazyArray(uint8, 4); + + const arr = array.decode(stream); + assert.deepEqual(arr.toArray(), [1, 2, 3, 4]); + }); + + it('should decode length as number before array', function() { + const stream = new DecodeStream(new Uint8Array([4, 1, 2, 3, 4, 5])); + const array = new LazyArray(uint8, uint8); + const arr = array.decode(stream); + + assert.deepEqual(arr.toArray(), [1, 2, 3, 4]); + }); + }); + + describe('size', () => + it('should work with LazyArrays', function() { + const stream = new DecodeStream(new Uint8Array([1, 2, 3, 4, 5])); + const array = new LazyArray(uint8, 4); + const arr = array.decode(stream); + + assert.equal(array.size(arr), 4); + }) + ); + + describe('encode', () => + it('should work with LazyArrays', function() { + const array = new LazyArray(uint8, 4); + const arr = array.fromBuffer(new Uint8Array([1, 2, 3, 4, 5])); + const buffer = array.toBuffer(arr); + assert.deepEqual(buffer, new Uint8Array([1, 2, 3, 4])); + }) + ); +}); diff --git a/node_modules/restructure/test/Number.js b/node_modules/restructure/test/Number.js new file mode 100644 index 0000000000000000000000000000000000000000..6c74fa9c8bd3b5c3d6e5148f4edfb96011ffca2c --- /dev/null +++ b/node_modules/restructure/test/Number.js @@ -0,0 +1,356 @@ +import { + uint8, + uint16, uint16be, uint16le, + uint24, uint24be, uint24le, + uint32, uint32be, uint32le, + int8, + int16, int16be, int16le, + int24, int24be, int24le, + int32, int32be, int32le, + float, floatbe, floatle, + double, doublebe, doublele, + fixed16, fixed16be, fixed16le, + fixed32, fixed32be, fixed32le, + DecodeStream, EncodeStream +} from 'restructure'; +import assert from 'assert'; + +describe('Number', function() { + describe('uint8', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xab, 0xff])); + assert.equal(uint8.decode(stream), 0xab); + assert.equal(uint8.decode(stream), 0xff); + }); + + it('should have a size', () => assert.equal(uint8.size(), 1)); + + it('should encode', function() { + assert.deepEqual(uint8.toBuffer(0xab), new Uint8Array([0xab])); + assert.deepEqual(uint8.toBuffer(0xff), new Uint8Array([0xff])); + }); + }); + + describe('uint16', () => + it('is an alias for uint16be', () => assert.deepEqual(uint16, uint16be)) + ); + + describe('uint16be', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xab, 0xff])); + assert.equal(uint16be.decode(stream), 0xabff); + }); + + it('should have a size', () => assert.equal(uint16be.size(), 2)); + + it('should encode', function() { + assert.deepEqual(uint16be.toBuffer(0xabff), new Uint8Array([0xab, 0xff])); + }); + }); + + describe('uint16le', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xff, 0xab])); + assert.equal(uint16le.decode(stream), 0xabff); + }); + + it('should have a size', () => assert.equal(uint16le.size(), 2)); + + it('should encode', function() { + assert.deepEqual(uint16le.toBuffer(0xabff), new Uint8Array([0xff, 0xab])); + }); + }); + + describe('uint24', () => + it('is an alias for uint24be', () => assert.deepEqual(uint24, uint24be)) + ); + + describe('uint24be', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xff, 0xab, 0x24])); + assert.equal(uint24be.decode(stream), 0xffab24); + }); + + it('should have a size', () => assert.equal(uint24be.size(), 3)); + + it('should encode', function() { + assert.deepEqual(uint24be.toBuffer(0xffab24), new Uint8Array([0xff, 0xab, 0x24])); + }); + }); + + describe('uint24le', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0x24, 0xab, 0xff])); + assert.equal(uint24le.decode(stream), 0xffab24); + }); + + it('should have a size', () => assert.equal(uint24le.size(), 3)); + + it('should encode', function() { + assert.deepEqual(uint24le.toBuffer(0xffab24), new Uint8Array([0x24, 0xab, 0xff])); + }); + }); + + describe('uint32', () => + it('is an alias for uint32be', () => assert.deepEqual(uint32, uint32be)) + ); + + describe('uint32be', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xff, 0xab, 0x24, 0xbf])); + assert.equal(uint32be.decode(stream), 0xffab24bf); + }); + + it('should have a size', () => assert.equal(uint32be.size(), 4)); + + it('should encode', function() { + assert.deepEqual(uint32be.toBuffer(0xffab24bf), new Uint8Array([0xff, 0xab, 0x24, 0xbf])); + }); + }); + + describe('uint32le', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xbf, 0x24, 0xab, 0xff])); + assert.equal(uint32le.decode(stream), 0xffab24bf); + }); + + it('should have a size', () => assert.equal(uint32le.size(), 4)); + + it('should encode', function() { + assert.deepEqual(uint32le.toBuffer(0xffab24bf), new Uint8Array([0xbf, 0x24, 0xab, 0xff])); + }); + }); + + describe('int8', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0x7f, 0xff])); + assert.equal(int8.decode(stream), 127); + assert.equal(int8.decode(stream), -1); + }); + + it('should have a size', () => assert.equal(int8.size(), 1)); + + it('should encode', function() { + assert.deepEqual(uint8.toBuffer(127), new Uint8Array([0x7f])); + assert.deepEqual(uint8.toBuffer(-1), new Uint8Array([0xff])); + }); + }); + + describe('int16', () => + it('is an alias for int16be', () => assert.deepEqual(int16, int16be)) + ); + + describe('int16be', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xff, 0xab])); + assert.equal(int16be.decode(stream), -85); + }); + + it('should have a size', () => assert.equal(int16be.size(), 2)); + + it('should encode', function() { + assert.deepEqual(int16be.toBuffer(-85), new Uint8Array([0xff, 0xab])); + }); + }); + + describe('int16le', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xab, 0xff])); + assert.equal(int16le.decode(stream), -85); + }); + + it('should have a size', () => assert.equal(int16le.size(), 2)); + + it('should encode', function() { + assert.deepEqual(int16le.toBuffer(-85), new Uint8Array([0xab, 0xff])); + }); + }); + + describe('int24', () => + it('is an alias for int24be', () => assert.deepEqual(int24, int24be)) + ); + + describe('int24be', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xff, 0xab, 0x24])); + assert.equal(int24be.decode(stream), -21724); + }); + + it('should have a size', () => assert.equal(int24be.size(), 3)); + + it('should encode', function() { + assert.deepEqual(int24be.toBuffer(-21724), new Uint8Array([0xff, 0xab, 0x24])); + }); + }); + + describe('int24le', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0x24, 0xab, 0xff])); + assert.equal(int24le.decode(stream), -21724); + }); + + it('should have a size', () => assert.equal(int24le.size(), 3)); + + it('should encode', function() { + assert.deepEqual(int24le.toBuffer(-21724), new Uint8Array([0x24, 0xab, 0xff])); + }); + }); + + describe('int32', () => + it('is an alias for int32be', () => assert.deepEqual(int32, int32be)) + ); + + describe('int32be', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xff, 0xab, 0x24, 0xbf])); + assert.equal(int32be.decode(stream), -5561153); + }); + + it('should have a size', () => assert.equal(int32be.size(), 4)); + + it('should encode', function() { + assert.deepEqual(int32be.toBuffer(-5561153), new Uint8Array([0xff, 0xab, 0x24, 0xbf])); + }); + }); + + describe('int32le', function() { + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0xbf, 0x24, 0xab, 0xff])); + assert.equal(int32le.decode(stream), -5561153); + }); + + it('should have a size', () => assert.equal(int32le.size(), 4)); + + it('should encode', function() { + assert.deepEqual(int32le.toBuffer(-5561153), new Uint8Array([0xbf, 0x24, 0xab, 0xff])); + }); + }); + + describe('float', () => + it('is an alias for floatbe', () => assert.deepEqual(float, floatbe)) + ); + + describe('floatbe', function() { + it('should decode', function() { + const value = floatbe.fromBuffer(new Uint8Array([0x43, 0x7a, 0x8c, 0xcd])); + assert(value >= 250.55 - 0.005); + assert(value <= 250.55 + 0.005); + }); + + it('should have a size', () => assert.equal(floatbe.size(), 4)); + + it('should encode', function() { + assert.deepEqual(floatbe.toBuffer(250.55), new Uint8Array([0x43, 0x7a, 0x8c, 0xcd])); + }); + }); + + describe('floatle', function() { + it('should decode', function() { + const value = floatle.fromBuffer(new Uint8Array([0xcd, 0x8c, 0x7a, 0x43])); + assert(value >= 250.55 - 0.005); + assert(value <= 250.55 + 0.005); + }); + + it('should have a size', () => assert.equal(floatle.size(), 4)); + + it('should encode', function() { + assert.deepEqual(floatle.toBuffer(250.55), new Uint8Array([0xcd, 0x8c, 0x7a, 0x43])); + }); + }); + + describe('double', () => + it('is an alias for doublebe', () => assert.deepEqual(double, doublebe)) + ); + + describe('doublebe', function() { + it('should decode', function() { + const value = doublebe.fromBuffer(new Uint8Array([0x40, 0x93, 0x4a, 0x3d, 0x70, 0xa3, 0xd7, 0x0a])); + assert(value >= 1234.56 - 0.005); + assert(value <= 1234.56 + 0.005); + }); + + it('should have a size', () => assert.equal(doublebe.size(), 8)); + + it('should encode', function() { + assert.deepEqual(doublebe.toBuffer(1234.56), new Uint8Array([0x40, 0x93, 0x4a, 0x3d, 0x70, 0xa3, 0xd7, 0x0a])); + }); + }); + + describe('doublele', function() { + it('should decode', function() { + const value = doublele.fromBuffer(new Uint8Array([0x0a, 0xd7, 0xa3, 0x70, 0x3d, 0x4a, 0x93, 0x40])); + assert(value >= 1234.56 - 0.005); + assert(value <= 1234.56 + 0.005); + }); + + it('should have a size', () => assert.equal(doublele.size(), 8)); + + it('should encode', function() { + assert.deepEqual(doublele.toBuffer(1234.56), new Uint8Array([0x0a, 0xd7, 0xa3, 0x70, 0x3d, 0x4a, 0x93, 0x40])); + }); + }); + + describe('fixed16', () => + it('is an alias for fixed16be', () => assert.deepEqual(fixed16, fixed16be)) + ); + + describe('fixed16be', function() { + it('should decode', function() { + const value = fixed16be.fromBuffer(new Uint8Array([0x19, 0x57])); + assert(value >= 25.34 - 0.005); + assert(value <= 25.34 + 0.005); + }); + + it('should have a size', () => assert.equal(fixed16be.size(), 2)); + + it('should encode', function() { + assert.deepEqual(fixed16be.toBuffer(25.34), new Uint8Array([0x19, 0x57])); + }); + }); + + describe('fixed16le', function() { + it('should decode', function() { + const value = fixed16le.fromBuffer(new Uint8Array([0x57, 0x19])); + assert(value >= 25.34 - 0.005); + assert(value <= 25.34 + 0.005); + }); + + it('should have a size', () => assert.equal(fixed16le.size(), 2)); + + it('should encode', function() { + assert.deepEqual(fixed16le.toBuffer(25.34), new Uint8Array([0x57, 0x19])); + }); + }); + + describe('fixed32', () => + it('is an alias for fixed32be', () => assert.deepEqual(fixed32, fixed32be)) + ); + + describe('fixed32be', function() { + it('should decode', function() { + const value = fixed32be.fromBuffer(new Uint8Array([0x00, 0xfa, 0x8c, 0xcc])); + assert(value >= 250.55 - 0.005); + assert(value <= 250.55 + 0.005); + }); + + it('should have a size', () => assert.equal(fixed32be.size(), 4)); + + it('should encode', function() { + assert.deepEqual(fixed32be.toBuffer(250.55), new Uint8Array([0x00, 0xfa, 0x8c, 0xcc])); + }); + }); + + describe('fixed32le', function() { + it('should decode', function() { + const value = fixed32le.fromBuffer(new Uint8Array([0xcc, 0x8c, 0xfa, 0x00])); + assert(value >= 250.55 - 0.005); + assert(value <= 250.55 + 0.005); + }); + + it('should have a size', () => assert.equal(fixed32le.size(), 4)); + + it('should encode', function() { + assert.deepEqual(fixed32le.toBuffer(250.55), new Uint8Array([0xcc, 0x8c, 0xfa, 0x00])); + }); + }); +}); diff --git a/node_modules/restructure/test/Optional.js b/node_modules/restructure/test/Optional.js new file mode 100644 index 0000000000000000000000000000000000000000..78b5a769fb22e2c0ec76787c4f1def2ffd90fca3 --- /dev/null +++ b/node_modules/restructure/test/Optional.js @@ -0,0 +1,100 @@ +import assert from 'assert'; +import {Optional, uint8, DecodeStream, EncodeStream} from 'restructure'; + +describe('Optional', function() { + describe('decode', function() { + it('should not decode when condition is falsy', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const optional = new Optional(uint8, false); + assert.equal(optional.decode(stream), null); + assert.equal(stream.pos, 0); + }); + + it('should not decode when condition is a function and falsy', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const optional = new Optional(uint8, function() { return false; }); + assert.equal(optional.decode(stream), null); + assert.equal(stream.pos, 0); + }); + + it('should decode when condition is omitted', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const optional = new Optional(uint8); + assert(optional.decode(stream) != null); + assert.equal(stream.pos, 1); + }); + + it('should decode when condition is truthy', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const optional = new Optional(uint8, true); + assert(optional.decode(stream) != null); + assert.equal(stream.pos, 1); + }); + + it('should decode when condition is a function and truthy', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const optional = new Optional(uint8, function() { return true; }); + assert(optional.decode(stream) != null); + assert.equal(stream.pos, 1); + }); + }); + + describe('size', function() { + it('should return 0 when condition is falsy', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const optional = new Optional(uint8, false); + assert.equal(optional.size(), 0); + }); + + it('should return 0 when condition is a function and falsy', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const optional = new Optional(uint8, function() { return false; }); + assert.equal(optional.size(), 0); + }); + + it('should return given type size when condition is omitted', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const optional = new Optional(uint8); + assert.equal(optional.size(), 1); + }); + + it('should return given type size when condition is truthy', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const optional = new Optional(uint8, true); + assert.equal(optional.size(), 1); + }); + + it('should return given type size when condition is a function and truthy', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const optional = new Optional(uint8, function() { return true; }); + assert.equal(optional.size(), 1); + }); + }); + + describe('encode', function() { + it('should not encode when condition is falsy', function() { + const optional = new Optional(uint8, false); + assert.deepEqual(optional.toBuffer(128), new Uint8Array(0)); + }); + + it('should not encode when condition is a function and falsy', function() { + const optional = new Optional(uint8, function() { return false; }); + assert.deepEqual(optional.toBuffer(128), new Uint8Array(0)); + }); + + it('should encode when condition is omitted', function() { + const optional = new Optional(uint8); + assert.deepEqual(optional.toBuffer(128), new Uint8Array([128])); + }); + + it('should encode when condition is truthy', function() { + const optional = new Optional(uint8, true); + assert.deepEqual(optional.toBuffer(128), new Uint8Array([128])); + }); + + it('should encode when condition is a function and truthy', function() { + const optional = new Optional(uint8, function() { return true; }); + assert.deepEqual(optional.toBuffer(128), new Uint8Array([128])); + }); + }); +}); diff --git a/node_modules/restructure/test/Pointer.js b/node_modules/restructure/test/Pointer.js new file mode 100644 index 0000000000000000000000000000000000000000..7716a8088228ec70b9305fe14d3e7fea64c1dc84 --- /dev/null +++ b/node_modules/restructure/test/Pointer.js @@ -0,0 +1,289 @@ +import assert from 'assert'; +import {Pointer, VoidPointer, uint8, DecodeStream, EncodeStream, Struct} from 'restructure'; + +describe('Pointer', function() { + describe('decode', function() { + it('should handle null pointers', function() { + const stream = new DecodeStream(new Uint8Array([0])); + const pointer = new Pointer(uint8, uint8); + return assert.equal(pointer.decode(stream, {_startOffset: 50}), null); + }); + + it('should use local offsets from start of parent by default', function() { + const stream = new DecodeStream(new Uint8Array([1, 53])); + const pointer = new Pointer(uint8, uint8); + assert.equal(pointer.decode(stream, {_startOffset: 0}), 53); + }); + + it('should support immediate offsets', function() { + const stream = new DecodeStream(new Uint8Array([1, 53])); + const pointer = new Pointer(uint8, uint8, {type: 'immediate'}); + assert.equal(pointer.decode(stream), 53); + }); + + it('should support offsets relative to the parent', function() { + const stream = new DecodeStream(new Uint8Array([0, 0, 1, 53])); + stream.pos = 2; + const pointer = new Pointer(uint8, uint8, {type: 'parent'}); + assert.equal(pointer.decode(stream, {parent: {_startOffset: 2}}), 53); + }); + + it('should support global offsets', function() { + const stream = new DecodeStream(new Uint8Array([1, 2, 4, 0, 0, 0, 53])); + const pointer = new Pointer(uint8, uint8, {type: 'global'}); + stream.pos = 2; + assert.equal(pointer.decode(stream, {parent: {parent: {_startOffset: 2}}}), 53); + }); + + it('should support offsets relative to a property on the parent', function() { + const stream = new DecodeStream(new Uint8Array([1, 0, 0, 0, 0, 53])); + const pointer = new Pointer(uint8, uint8, {relativeTo: ctx => ctx.parent.ptr}); + assert.equal(pointer.decode(stream, {_startOffset: 0, parent: {ptr: 4}}), 53); + }); + + it('should throw when passing a non function relativeTo option', function() { + return assert.throws(() => new Pointer(uint8, uint8, {relativeTo: 'parent.ptr'})); + }); + + it('should support returning pointer if there is no decode type', function() { + const stream = new DecodeStream(new Uint8Array([4])); + const pointer = new Pointer(uint8, 'void'); + assert.equal(pointer.decode(stream, {_startOffset: 0}), 4); + }); + + it('should support decoding pointers lazily', function() { + const stream = new DecodeStream(new Uint8Array([1, 53])); + const struct = new Struct({ + ptr: new Pointer(uint8, uint8, {lazy: true})}); + + const res = struct.decode(stream); + assert.equal(typeof Object.getOwnPropertyDescriptor(res, 'ptr').get, 'function'); + assert.equal(Object.getOwnPropertyDescriptor(res, 'ptr').enumerable, true); + assert.equal(res.ptr, 53); + }); + }); + + describe('size', function() { + it('should add to local pointerSize', function() { + const pointer = new Pointer(uint8, uint8); + const ctx = {pointerSize: 0}; + assert.equal(pointer.size(10, ctx), 1); + assert.equal(ctx.pointerSize, 1); + }); + + it('should add to immediate pointerSize', function() { + const pointer = new Pointer(uint8, uint8, {type: 'immediate'}); + const ctx = {pointerSize: 0}; + assert.equal(pointer.size(10, ctx), 1); + assert.equal(ctx.pointerSize, 1); + }); + + it('should add to parent pointerSize', function() { + const pointer = new Pointer(uint8, uint8, {type: 'parent'}); + const ctx = {parent: {pointerSize: 0}}; + assert.equal(pointer.size(10, ctx), 1); + assert.equal(ctx.parent.pointerSize, 1); + }); + + it('should add to global pointerSize', function() { + const pointer = new Pointer(uint8, uint8, {type: 'global'}); + const ctx = {parent: {parent: {parent: {pointerSize: 0}}}}; + assert.equal(pointer.size(10, ctx), 1); + assert.equal(ctx.parent.parent.parent.pointerSize, 1); + }); + + it('should handle void pointers', function() { + const pointer = new Pointer(uint8, 'void'); + const ctx = {pointerSize: 0}; + assert.equal(pointer.size(new VoidPointer(uint8, 50), ctx), 1); + assert.equal(ctx.pointerSize, 1); + }); + + it('should throw if no type and not a void pointer', function() { + const pointer = new Pointer(uint8, 'void'); + const ctx = {pointerSize: 0}; + assert.throws(() => pointer.size(30, ctx)); + }); + + it('should return a fixed size without a value', function() { + const pointer = new Pointer(uint8, uint8); + assert.equal(pointer.size(), 1); + }); + }); + + describe('encode', function() { + it('should handle null pointers', function() { + const ptr = new Pointer(uint8, uint8); + const ctx = { + pointerSize: 0, + startOffset: 0, + pointerOffset: 0, + pointers: [] + }; + + const stream = new EncodeStream(new Uint8Array(ptr.size(null))); + ptr.encode(stream, null, ctx); + assert.equal(ctx.pointerSize, 0); + + assert.deepEqual(stream.buffer, new Uint8Array([0])); + }); + + it('should handle local offsets', function() { + const ptr = new Pointer(uint8, uint8); + const ctx = { + pointerSize: 0, + startOffset: 0, + pointerOffset: 1, + pointers: [] + }; + + const stream = new EncodeStream(new Uint8Array(ptr.size(10))); + ptr.encode(stream, 10, ctx); + assert.equal(ctx.pointerOffset, 2); + assert.deepEqual(ctx.pointers, [ + { type: uint8, val: 10, parent: ctx } + ]); + + assert.deepEqual(stream.buffer, new Uint8Array([1])); + }); + + it('should handle immediate offsets', function() { + const ptr = new Pointer(uint8, uint8, {type: 'immediate'}); + const ctx = { + pointerSize: 0, + startOffset: 0, + pointerOffset: 1, + pointers: [] + }; + + const stream = new EncodeStream(new Uint8Array(ptr.size(10))); + ptr.encode(stream, 10, ctx); + assert.equal(ctx.pointerOffset, 2); + assert.deepEqual(ctx.pointers, [ + { type: uint8, val: 10, parent: ctx } + ]); + + assert.deepEqual(stream.buffer, new Uint8Array([0])); + }); + + it('should handle immediate offsets', function() { + const ptr = new Pointer(uint8, uint8, {type: 'immediate'}); + const ctx = { + pointerSize: 0, + startOffset: 0, + pointerOffset: 1, + pointers: [] + }; + + const stream = new EncodeStream(new Uint8Array(ptr.size(10))); + ptr.encode(stream, 10, ctx); + assert.equal(ctx.pointerOffset, 2); + assert.deepEqual(ctx.pointers, [ + { type: uint8, val: 10, parent: ctx } + ]); + + assert.deepEqual(stream.buffer, new Uint8Array([0])); + }); + + it('should handle offsets relative to parent', function() { + const ptr = new Pointer(uint8, uint8, {type: 'parent'}); + const ctx = { + parent: { + pointerSize: 0, + startOffset: 3, + pointerOffset: 5, + pointers: [] + } + }; + + const stream = new EncodeStream(new Uint8Array(ptr.size(10, {parent: {...ctx.parent}}))); + ptr.encode(stream, 10, ctx); + assert.equal(ctx.parent.pointerOffset, 6); + assert.deepEqual(ctx.parent.pointers, [ + { type: uint8, val: 10, parent: ctx } + ]); + + assert.deepEqual(stream.buffer, new Uint8Array([2])); + }); + + it('should handle global offsets', function() { + const ptr = new Pointer(uint8, uint8, {type: 'global'}); + const ctx = { + parent: { + parent: { + parent: { + pointerSize: 0, + startOffset: 3, + pointerOffset: 5, + pointers: [] + } + } + } + }; + + const stream = new EncodeStream(new Uint8Array(ptr.size(10, JSON.parse(JSON.stringify(ctx))))); + ptr.encode(stream, 10, ctx); + assert.equal(ctx.parent.parent.parent.pointerOffset, 6); + assert.deepEqual(ctx.parent.parent.parent.pointers, [ + { type: uint8, val: 10, parent: ctx } + ]); + + assert.deepEqual(stream.buffer, new Uint8Array([5])); + }); + + it('should support offsets relative to a property on the parent', function() { + const ptr = new Pointer(uint8, uint8, {relativeTo: ctx => ctx.ptr}); + const ctx = { + pointerSize: 0, + startOffset: 0, + pointerOffset: 10, + pointers: [], + val: { + ptr: 4 + } + }; + + const stream = new EncodeStream(new Uint8Array(ptr.size(10, {...ctx}))); + ptr.encode(stream, 10, ctx); + assert.equal(ctx.pointerOffset, 11); + assert.deepEqual(ctx.pointers, [ + { type: uint8, val: 10, parent: ctx } + ]); + + assert.deepEqual(stream.buffer, new Uint8Array([6])); + }); + + it('should support void pointers', function() { + const ptr = new Pointer(uint8, 'void'); + const ctx = { + pointerSize: 0, + startOffset: 0, + pointerOffset: 1, + pointers: [] + }; + + const val = new VoidPointer(uint8, 55); + const stream = new EncodeStream(new Uint8Array(ptr.size(val, {...ctx}))); + ptr.encode(stream, val, ctx); + assert.equal(ctx.pointerOffset, 2); + assert.deepEqual(ctx.pointers, [ + { type: uint8, val: 55, parent: ctx } + ]); + + assert.deepEqual(stream.buffer, new Uint8Array([1])); + }); + + it('should throw if not a void pointer instance', function() { + const ptr = new Pointer(uint8, 'void'); + const ctx = { + pointerSize: 0, + startOffset: 0, + pointerOffset: 1, + pointers: [] + }; + + const stream = new EncodeStream(new Uint8Array(0)); + assert.throws(() => ptr.encode(stream, 44, ctx)); + }); + }); +}); diff --git a/node_modules/restructure/test/Reserved.js b/node_modules/restructure/test/Reserved.js new file mode 100644 index 0000000000000000000000000000000000000000..3c7847fcb48debc30afd3dfdddeb011f6db6c4e1 --- /dev/null +++ b/node_modules/restructure/test/Reserved.js @@ -0,0 +1,26 @@ +import assert from 'assert'; +import {Reserved, uint8, uint16, DecodeStream, EncodeStream} from 'restructure'; + +describe('Reserved', function() { + it('should have a default count of 1', function() { + const reserved = new Reserved(uint8); + assert.equal(reserved.size(), 1); + }); + + it('should allow custom counts and types', function() { + const reserved = new Reserved(uint16, 10); + assert.equal(reserved.size(), 20); + }); + + it('should decode', function() { + const stream = new DecodeStream(new Uint8Array([0, 0])); + const reserved = new Reserved(uint16); + assert.equal(reserved.decode(stream), null); + assert.equal(stream.pos, 2); + }); + + it('should encode', function() { + const reserved = new Reserved(uint16); + assert.deepEqual(reserved.toBuffer(), new Uint8Array([0, 0])); + }); +}); diff --git a/node_modules/restructure/test/String.js b/node_modules/restructure/test/String.js new file mode 100644 index 0000000000000000000000000000000000000000..a5bbe147bb6cff13a64ca0e7264799bb1ed26f12 --- /dev/null +++ b/node_modules/restructure/test/String.js @@ -0,0 +1,151 @@ +import assert from 'assert'; +import {String as StringT, uint16le, uint8, DecodeStream, Struct} from 'restructure'; + +describe('String', function() { + describe('decode', function() { + it('should decode fixed length', function() { + const string = new StringT(7); + assert.equal(string.fromBuffer(Buffer.from('testing')), 'testing'); + }); + + it('should decode length from parent key', function() { + const stream = new DecodeStream(Buffer.from('testing')); + const string = new StringT('len'); + assert.equal(string.decode(stream, {len: 7}), 'testing'); + }); + + it('should decode length as number before string', function() { + const string = new StringT(uint8); + assert.equal(string.fromBuffer(Buffer.from('\x07testing')), 'testing'); + }); + + it('should decode utf8', function() { + const string = new StringT(4, 'utf8'); + assert.equal(string.fromBuffer(Buffer.from('🍻')), '🍻'); + }); + + it('should decode encoding computed from function', function() { + const string = new StringT(4, function() { return 'utf8'; }); + assert.equal(string.fromBuffer(Buffer.from('🍻')), '🍻'); + }); + + it('should decode null-terminated string and read past terminator', function() { + const stream = new DecodeStream(Buffer.from('🍻\x00')); + const string = new StringT(null, 'utf8'); + assert.equal(string.decode(stream), '🍻'); + assert.equal(stream.pos, 5); + }); + + it('should decode remainder of buffer when null-byte missing', function() { + const string = new StringT(null, 'utf8'); + assert.equal(string.fromBuffer(Buffer.from('🍻')), '🍻'); + }); + + it('should decode two-byte null-terminated string for utf16le', function() { + const stream = new DecodeStream(Buffer.from('🍻\x00', 'utf16le')); + const string = new StringT(null, 'utf16le'); + assert.equal(string.decode(stream), '🍻'); + assert.equal(stream.pos, 6); + }); + + it('should decode remainder of buffer when null-byte missing, utf16le', function() { + const string = new StringT(null, 'utf16le'); + assert.equal(string.fromBuffer(Buffer.from('🍻', 'utf16le')), '🍻'); + }); + + it('should decode x-mac-roman', function() { + const string = new StringT(null, 'x-mac-roman'); + const buf = new Uint8Array([0x8a, 0x63, 0x63, 0x65, 0x6e, 0x74, 0x65, 0x64, 0x20, 0x63, 0x68, 0x87, 0x72, 0x61, 0x63, 0x74, 0x65, 0x72, 0x73]); + assert.equal(string.fromBuffer(buf), 'äccented cháracters'); + }) + }); + + describe('size', function() { + it('should use string length', function() { + const string = new StringT(7); + assert.equal(string.size('testing'), 7); + }); + + it('should use correct encoding', function() { + const string = new StringT(10, 'utf8'); + assert.equal(string.size('🍻'), 4); + }); + + it('should use encoding from function', function() { + const string = new StringT(10, function() { return 'utf8'; }); + assert.equal(string.size('🍻'), 4); + }); + + it('should add size of length field before string', function() { + const string = new StringT(uint8, 'utf8'); + assert.equal(string.size('🍻'), 5); + }); + + it('should work with utf16be encoding', function() { + const string = new StringT(10, 'utf16be'); + assert.equal(string.size('🍻'), 4); + }); + + it('should take null-byte into account', function() { + const string = new StringT(null, 'utf8'); + assert.equal(string.size('🍻'), 5); + }); + + it('should take null-byte into account, utf16le', function() { + const string = new StringT(null, 'utf16le'); + assert.equal(string.size('🍻'), 6); + }); + + it('should use defined length if no value given', function() { + const array = new StringT(10); + assert.equal(array.size(), 10); + }); + }); + + describe('encode', function() { + it('should encode using string length', function() { + const string = new StringT(7); + assert.deepEqual(string.toBuffer('testing'), Buffer.from('testing')); + }); + + it('should encode length as number before string', function() { + const string = new StringT(uint8); + assert.deepEqual(string.toBuffer('testing'), Buffer.from('\x07testing')); + }); + + it('should encode length as number before string utf8', function() { + const string = new StringT(uint8, 'utf8'); + assert.deepEqual(string.toBuffer('testing 😜'), Buffer.from('\x0ctesting 😜', 'utf8')); + }); + + it('should encode utf8', function() { + const string = new StringT(4, 'utf8'); + assert.deepEqual(string.toBuffer('🍻'), Buffer.from('🍻')); + }); + + it('should encode encoding computed from function', function() { + const string = new StringT(4, function() { return 'utf8'; }); + assert.deepEqual(string.toBuffer('🍻'), Buffer.from('🍻')); + }); + + it('should encode null-terminated string', function() { + const string = new StringT(null, 'utf8'); + assert.deepEqual(string.toBuffer('🍻'), Buffer.from('🍻\x00')); + }); + + it('should encode using string length, utf16le', function() { + const string = new StringT(16, 'utf16le'); + assert.deepEqual(string.toBuffer('testing'), Buffer.from('testing', 'utf16le')); + }); + + it('should encode length as number before string utf16le', function() { + const string = new StringT(uint16le, 'utf16le'); + assert.deepEqual(string.toBuffer('testing 😜'), Buffer.from('\u0014testing 😜', 'utf16le')); + }); + + it('should encode two-byte null-terminated string for UTF-16', function() { + const string = new StringT(null, 'utf16le'); + assert.deepEqual(string.toBuffer('🍻'), Buffer.from('🍻\x00', 'utf16le')); + }); + }); +}); diff --git a/node_modules/restructure/test/Struct.js b/node_modules/restructure/test/Struct.js new file mode 100644 index 0000000000000000000000000000000000000000..60fde09117a62de62094f12924b785e9db15b8e2 --- /dev/null +++ b/node_modules/restructure/test/Struct.js @@ -0,0 +1,146 @@ +import assert from 'assert'; +import {Struct, String as StringT, Pointer, uint8, DecodeStream, EncodeStream} from 'restructure'; + +describe('Struct', function() { + describe('decode', function() { + it('should decode into an object', function() { + const struct = new Struct({ + name: new StringT(uint8), + age: uint8 + }); + + assert.deepEqual(struct.fromBuffer(Buffer.from('\x05devon\x15')), { + name: 'devon', + age: 21 + }); + }); + + it('should support process hook', function() { + const struct = new Struct({ + name: new StringT(uint8), + age: uint8 + }); + + struct.process = function() { + return this.canDrink = this.age >= 21; + }; + + assert.deepEqual(struct.fromBuffer(Buffer.from('\x05devon\x20')), { + name: 'devon', + age: 32, + canDrink: true + }); + }); + + it('should support function keys', function() { + const struct = new Struct({ + name: new StringT(uint8), + age: uint8, + canDrink() { return this.age >= 21; } + }); + + assert.deepEqual(struct.fromBuffer(Buffer.from('\x05devon\x20')), { + name: 'devon', + age: 32, + canDrink: true + }); + }); + }); + + describe('size', function() { + it('should compute the correct size', function() { + const struct = new Struct({ + name: new StringT(uint8), + age: uint8 + }); + + assert.equal(struct.size({name: 'devon', age: 21}), 7); + }); + + it('should compute the correct size with pointers', function() { + const struct = new Struct({ + name: new StringT(uint8), + age: uint8, + ptr: new Pointer(uint8, new StringT(uint8)) + }); + + const size = struct.size({ + name: 'devon', + age: 21, + ptr: 'hello' + }); + + assert.equal(size, 14); + }); + + it('should get the correct size when no value is given', function() { + const struct = new Struct({ + name: new StringT(4), + age: uint8 + }); + + assert.equal(struct.size(), 5); + }); + + it('should throw when getting non-fixed length size and no value is given', function() { + const struct = new Struct({ + name: new StringT(uint8), + age: uint8 + }); + + assert.throws(() => struct.size(), /not a fixed size/i); + }); + }); + + describe('encode', function() { + it('should encode objects to buffers', function() { + const struct = new Struct({ + name: new StringT(uint8), + age: uint8 + }); + + const buf = struct.toBuffer({ + name: 'devon', + age: 21 + }); + + assert.deepEqual(buf, Buffer.from('\x05devon\x15')); + }); + + it('should support preEncode hook', function() { + const struct = new Struct({ + nameLength: uint8, + name: new StringT('nameLength'), + age: uint8 + }); + + struct.preEncode = function() { + return this.nameLength = this.name.length; + }; + + const buf = struct.toBuffer({ + name: 'devon', + age: 21 + }); + + assert.deepEqual(buf, Buffer.from('\x05devon\x15')); + }); + + it('should encode pointer data after structure', function() { + const struct = new Struct({ + name: new StringT(uint8), + age: uint8, + ptr: new Pointer(uint8, new StringT(uint8)) + }); + + const buf = struct.toBuffer({ + name: 'devon', + age: 21, + ptr: 'hello' + }); + + assert.deepEqual(buf, Buffer.from('\x05devon\x15\x08\x05hello')); + }); + }); +}); + diff --git a/node_modules/restructure/test/VersionedStruct.js b/node_modules/restructure/test/VersionedStruct.js new file mode 100644 index 0000000000000000000000000000000000000000..86e0a7c8fb2d8b9cc27a3422abe99abf88c9c1e7 --- /dev/null +++ b/node_modules/restructure/test/VersionedStruct.js @@ -0,0 +1,495 @@ +import assert from 'assert'; +import {VersionedStruct, String as StringT, Pointer, uint8, DecodeStream, EncodeStream} from 'restructure'; + +describe('VersionedStruct', function() { + describe('decode', function() { + it('should get version from number type', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + gender: uint8 + } + } + ); + + let stream = new DecodeStream(Buffer.from('\x00\x05devon\x15')); + assert.deepEqual(struct.decode(stream), { + version: 0, + name: 'devon', + age: 21 + }); + + stream = new DecodeStream(Buffer.from('\x01\x0adevon 👍\x15\x00', 'utf8')); + assert.deepEqual(struct.decode(stream), { + version: 1, + name: 'devon 👍', + age: 21, + gender: 0 + }); + }); + + it('should throw for unknown version', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + gender: uint8 + } + } + ); + + const stream = new DecodeStream(Buffer.from('\x05\x05devon\x15')); + return assert.throws(() => struct.decode(stream)); + }); + + it('should support common header block', function() { + const struct = new VersionedStruct(uint8, { + header: { + age: uint8, + alive: uint8 + }, + 0: { + name: new StringT(uint8, 'ascii') + }, + 1: { + name: new StringT(uint8, 'utf8'), + gender: uint8 + } + } + ); + + let stream = new DecodeStream(Buffer.from('\x00\x15\x01\x05devon')); + assert.deepEqual(struct.decode(stream), { + version: 0, + age: 21, + alive: 1, + name: 'devon' + }); + + stream = new DecodeStream(Buffer.from('\x01\x15\x01\x0adevon 👍\x00', 'utf8')); + assert.deepEqual(struct.decode(stream), { + version: 1, + age: 21, + alive: 1, + name: 'devon 👍', + gender: 0 + }); + }); + + it('should support parent version key', function() { + const struct = new VersionedStruct('version', { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + gender: uint8 + } + } + ); + + let stream = new DecodeStream(Buffer.from('\x05devon\x15')); + assert.deepEqual(struct.decode(stream, {version: 0}), { + version: 0, + name: 'devon', + age: 21 + }); + + stream = new DecodeStream(Buffer.from('\x0adevon 👍\x15\x00', 'utf8')); + assert.deepEqual(struct.decode(stream, {version: 1}), { + version: 1, + name: 'devon 👍', + age: 21, + gender: 0 + }); + }); + + it('should support parent version nested key', function() { + const struct = new VersionedStruct('obj.version', { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + gender: uint8 + } + } + ); + + let stream = new DecodeStream(Buffer.from('\x05devon\x15')); + assert.deepEqual(struct.decode(stream, {obj: {version: 0}}), { + version: 0, + name: 'devon', + age: 21 + }); + + stream = new DecodeStream(Buffer.from('\x0adevon 👍\x15\x00', 'utf8')); + assert.deepEqual(struct.decode(stream, {obj: {version: 1}}), { + version: 1, + name: 'devon 👍', + age: 21, + gender: 0 + }); + }); + + it('should support sub versioned structs', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8) + }, + 1: { + name: new StringT(uint8), + isDesert: uint8 + } + } + ) + } + ); + + let stream = new DecodeStream(Buffer.from('\x00\x05devon\x15')); + assert.deepEqual(struct.decode(stream, {version: 0}), { + version: 0, + name: 'devon', + age: 21 + }); + + stream = new DecodeStream(Buffer.from('\x01\x00\x05pasta')); + assert.deepEqual(struct.decode(stream, {version: 0}), { + version: 0, + name: 'pasta' + }); + + stream = new DecodeStream(Buffer.from('\x01\x01\x09ice cream\x01')); + assert.deepEqual(struct.decode(stream, {version: 0}), { + version: 1, + name: 'ice cream', + isDesert: 1 + }); + }); + + it('should support process hook', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + gender: uint8 + } + } + ); + + struct.process = function() { + return this.processed = true; + }; + + const stream = new DecodeStream(Buffer.from('\x00\x05devon\x15')); + assert.deepEqual(struct.decode(stream), { + version: 0, + name: 'devon', + age: 21, + processed: true + }); + }); + }); + + describe('size', function() { + it('should compute the correct size', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + gender: uint8 + } + } + ); + + let size = struct.size({ + version: 0, + name: 'devon', + age: 21 + }); + + assert.equal(size, 8); + + size = struct.size({ + version: 1, + name: 'devon 👍', + age: 21, + gender: 0 + }); + + assert.equal(size, 14); + }); + + it('should throw for unknown version', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + gender: uint8 + } + } + ); + + assert.throws(() => + struct.size({ + version: 5, + name: 'devon', + age: 21 + }) + ); + }); + + it('should support common header block', function() { + const struct = new VersionedStruct(uint8, { + header: { + age: uint8, + alive: uint8 + }, + 0: { + name: new StringT(uint8, 'ascii') + }, + 1: { + name: new StringT(uint8, 'utf8'), + gender: uint8 + } + } + ); + + let size = struct.size({ + version: 0, + age: 21, + alive: 1, + name: 'devon' + }); + + assert.equal(size, 9); + + size = struct.size({ + version: 1, + age: 21, + alive: 1, + name: 'devon 👍', + gender: 0 + }); + + assert.equal(size, 15); + }); + + it('should compute the correct size with pointers', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + ptr: new Pointer(uint8, new StringT(uint8)) + } + } + ); + + const size = struct.size({ + version: 1, + name: 'devon', + age: 21, + ptr: 'hello' + }); + + assert.equal(size, 15); + }); + + it('should throw if no value is given', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(4, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(4, 'utf8'), + age: uint8, + gender: uint8 + } + } + ); + + assert.throws(() => struct.size(), /not a fixed size/i); + }); + }); + + describe('encode', function() { + it('should encode objects to buffers', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + gender: uint8 + } + }); + + const buf1 = struct.toBuffer({ + version: 0, + name: 'devon', + age: 21 + }); + + assert.deepEqual(buf1, Buffer.from('\x00\x05devon\x15', 'utf8')); + + const buf2 = struct.toBuffer({ + version: 1, + name: 'devon 👍', + age: 21, + gender: 0 + }); + + assert.deepEqual(buf2, Buffer.from('\x01\x0adevon 👍\x15\x00', 'utf8')); + }); + + it('should throw for unknown version', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + gender: uint8 + } + }); + + assert.throws(() => + struct.toBuffer({ + version: 5, + name: 'devon', + age: 21 + }) + ); + }); + + it('should support common header block', function() { + const struct = new VersionedStruct(uint8, { + header: { + age: uint8, + alive: uint8 + }, + 0: { + name: new StringT(uint8, 'ascii') + }, + 1: { + name: new StringT(uint8, 'utf8'), + gender: uint8 + } + }); + + const buf1 = struct.toBuffer({ + version: 0, + age: 21, + alive: 1, + name: 'devon' + }); + + assert.deepEqual(buf1, Buffer.from('\x00\x15\x01\x05devon', 'utf8')); + + const buf2 = struct.toBuffer({ + version: 1, + age: 21, + alive: 1, + name: 'devon 👍', + gender: 0 + }); + + assert.deepEqual(buf2, Buffer.from('\x01\x15\x01\x0adevon 👍\x00', 'utf8')); + }); + + it('should encode pointer data after structure', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + ptr: new Pointer(uint8, new StringT(uint8)) + } + }); + + const buf = struct.toBuffer({ + version: 1, + name: 'devon', + age: 21, + ptr: 'hello' + }); + + assert.deepEqual(buf, Buffer.from('\x01\x05devon\x15\x09\x05hello', 'utf8')); + }); + + it('should support preEncode hook', function() { + const struct = new VersionedStruct(uint8, { + 0: { + name: new StringT(uint8, 'ascii'), + age: uint8 + }, + 1: { + name: new StringT(uint8, 'utf8'), + age: uint8, + gender: uint8 + } + }); + + struct.preEncode = function() { + return this.version = (this.gender != null) ? 1 : 0; + }; + + const buf1 = struct.toBuffer({ + name: 'devon', + age: 21 + }); + + assert.deepEqual(buf1, Buffer.from('\x00\x05devon\x15', 'utf8')); + + const buf2 = struct.toBuffer({ + name: 'devon 👍', + age: 21, + gender: 0 + }); + + assert.deepEqual(buf2, Buffer.from('\x01\x0adevon 👍\x15\x00', 'utf8')); + }); + }); +}); diff --git a/node_modules/rettime/LICENSE.md b/node_modules/rettime/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..0372e5681351f787305d697e79f98ff2175a787e --- /dev/null +++ b/node_modules/rettime/LICENSE.md @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2024—present Artem Zakharchenko + +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. diff --git a/node_modules/rettime/README.md b/node_modules/rettime/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3d502b1e22287b5a93bd20718537aa18f7607de2 --- /dev/null +++ b/node_modules/rettime/README.md @@ -0,0 +1,457 @@ +# Rettime + +A type-safe marriage of `EventTarget` and `EventEmitter`. + +## Features + +- 🎯 **Event-based**. Control event flow: prevent defaults, stop propagation, cancel events. Something your common `Emitter` can't do. +- 🗼 **Emitter-inspired**. Emit event types and data, don't bother with creating `Event` instances. A bit less verbosity than a common `EventTarget`. +- ⛑️ **Type-safe**. Describe the exact event types and payloads accepted by the emitter. Never emit or listen to unknown events. +- 🧰 **Convenience methods** like `.emitAsPromise()` and `.emitAsGenerator()` to build more complex event-driven systems. +- 🐙 **Tiny**. 700B gzipped. + +> [!WARNING] +> This library **does not** have performance as the end goal. In fact, since it operates on events and supports event cancellation, it will likely be _slower_ than the emitters that don't do that. + +## Motivation + +### Why not just `EventTarget`? + +The `EventTarget` API is fantastic. It works in the browser and in Node.js, dispatches actual events, supports cancellation, etc. At the same time, it has a number of flaws that prevent me from using it for anything serious: + +- Complete lack of type safety. The `type` in `new Event(type)` is not a type argument in `lib.dom.ts`. It's always `string`. It means it's impossible to narrow it down to a literal string type to achieve type safety. +- No concept of `.prependListener()`. There is no way to add a listener to run _first_, before other existing listeners. +- No concept of `.removeAllListeners()`. You have to remove each individual listener by hand. Good if you own the listeners, not so good if you don't. +- No concept of `.listenerCount()` or knowing if a dispatched event had any listeners (the `boolean` returned from `.dispatch()` indicates if the event has been prevented, not whether it had any listeners). +- (Opinionated) Verbose. I prefer `.on()` over `.addEventListener()`. I prefer passing data than constructing `new MessageEvent()` all the time. + +### Why not just `Emitter` (in Node.js)? + +The `Emitter` API in Node.js is great, but it has its own downsides: + +- Node.js-specific. `Emitter` does not work in the browser. +- Lacks any type safety. +- No concept of `.stopPropagation()` and `.stopImmediatePropagation()`. Those methods are defined but literally do nothing. + +## Install + +```sh +npm install rettime +``` + +## API + +### `TypedEvent` + +`TypedEvent` is a subset of `MessageEvent` that allows for type-safe event declaration. + +```ts +new TypedEvent(type: EventType, { data: DataType }) +``` + +> The `data` argument depends on the `DataType` of your event. Use `void` if the event must not send any data. + + +#### Reserved events + +_Reserved events_ refer to event types reserved for specific behaviors by the library. + +#### `*` + +Using a wildcard (`*`) event type allows you to listen to _any_ events emitted on the emitter. This is similar to methods like `.onAny()` you might find in the wild. + +```ts +const emitter = new Emitter<{ + greeting: TypedEvent() + cart: TypedEvent() +}>() + +emitter + .on('*', (event) => { + event.type // "greeting" | "cart" + console.log(`Caught: ${event.type}, ${event.data}`) + }) + .on('greeting', (event) => { + console.log(`Hello, ${event.data}!`) + }) + +emitter.emit('greeting', 'John') +// "Caught: greeting, John" +// "Hello, John!" +```` + +Wildcard listeners are supported by all subscription methods, like `.on()`, `.once()`, `.earlyOn()`, and .`earlyOnce()`, are type-safe and fully support the listener order sensitivity. + +#### Custom events + +You can implement custom events by extending the default `TypedEvent` class and forwarding the type arguments that it expects: + +```ts +class GreetingEvent< + DataType = void, + ReturnType = any, + EventType extends string = string, +> extends TypedEvent { + public id: string +} + +const emitter = new Emitter<{ greeting: GreetingEvent<'john'> }>() + +emitter.on('greeting', (event) => { + console.log(event instanceof GreetingEvent) // true + console.log(event instanceof TypedEvent) // true + console.log(event instanceof MessageEvent) // true + + console.log(event.type) // "greeting" + console.log(event.data) // "john" + console.log(event.id) // string +}) +``` + +### `Emitter` + +```ts +new Emitter() +``` + +The `EventMap` type argument allows you describe the supported event types, their payload, and the return type of their event listeners. + +```ts +import { Emitter, TypedEvent } from 'rettime' + +const emitter = new Emitter<{ hello: TypedEvent }>() + +emitter.on('hello', () => 1) // ✅ +emitter.on('hello', () => 'oops') // ❌ string not assignable to type number + +emitter.emit(new TypedEvent('hello', { data: 'John' })) // ✅ +emitter.emit(new TypedEvent('hello', { data: 123 })) // ❌ number is not assignable to type string +emitter.emit(new TypedEvent('hello')) // ❌ missing data argument of type string + +emitter.emit(new TypedEvent('unknown')) // ❌ "unknown" does not satisfy "hello" +``` + +#### Describing events + +The `Emitter` class requires a type argument that describes the event map. If you do not provide that argument, adding listeners or emitting events will produce a type error as your emitter doesn't have an event map defined. + +An event map is an object of the following shape: + +```ts +{ + [type: string]: TypedEvent +} +``` + +The `type` is a string indicating the event type (e.g. `greet` or `ping`). The array it accepts has two members: `args` describes the arguments accepted by this event (can also be `never` for events without arguments) and `returnValue` is an optional type for the data returned from the listeners for this event. + +Let's say you want to define a `greet` event that expects a user name as data and returns a greeting string: + +```ts +import { Emitter, TypedEvent } from 'rettime' + +const emitter = new Emitter<{ greet: TypedEvent }>() + +emitter.on('greet', (event) => { + console.log(`Hello, ${event.data}!`) +}) +emitter.emit(new TypedEvent('greet', { data: 'John' })) +// "Hello, John!" +``` + +Here's another example where we define a `ping` event that has no arguments but returns a timestamp for each ping: + +```ts +const emitter = new Emitter<{ ping: TypedEvent }>() + +emitter.on('ping', () => Date.now()) + +const results = await emitter.emitAsPromise(new TypedEvent('ping')) +// [1745658424732] +``` + +> [!IMPORTANT] +> When providing type arguments to your `TypedEvents`, you **do not** need to provide the `EventType` argument—it will be inferred from your event map. + +### `.on(type, listener[, options])` + +Adds an event listener for the given event type. + +```ts +import { Emitter, TypedEvent } from 'rettime' + +const emitter = new Emitter<{ hello: TypedEvent }>() + +emitter.on('hello', (event) => { + // `event` is a `TypedEvent` instance derived from `MessageEvent`. + console.log(event.data) +}) +``` + +All methods that add new listeners return an `AbortController` instance bound to that listener. You can use that controller to cancel the event handling, including mid-air: + +```ts +const controller = emitter.on('hello', listener) +controller.abort(reason) +``` + +All methods that add new listeners also accept an optional `options` argument. You can use it to configure event handling behavior. For example, you can provide an existing `AbortController` signal as the `options.signal` value so the attached listener abides by your controller: + +```ts +emitter.on('hello', listener, { signal: controller.signal }) +``` + +> Both the public controller of the event and your custom controller are combined using `AbortSignal.any()`. + +### `.once(type, listener[, options])` + +Adds a one-time event listener for the given event type. + +### `.earlyOn(type, listener[, options])` + +Prepends a listener for the given event type. + +```ts +import { Emitter, TypedEvent } from 'rettime' + +const emitter = new Emitter<{ hello: TypedEvent }>() + +emitter.on('hello', () => 1) +emitter.earlyOn('hello', () => 2) + +const results = await emitter.emitAsPromise(new TypedEvent('hello')) +// [2, 1] +``` + +### `.earlyOnce(type, listener[, options])` + +Prepends a one-time listener for the given event type. + +### `.emit(type[, data])` + +Emits the given event with optional data. + +```ts +import { Emitter, TypedEvent } from 'rettime' + +const emitter = new Emitter<{ hello: TypedEvent }>() + +emitter.on('hello', (event) => console.log(event.data)) + +emitter.emit(new TypedEvent('hello', 'John')) +``` + +### `.emitAsPromise(type[, data])` + +Emits the given event and returns a Promise that resolves with the returned data of all matching event listeners, or rejects whenever any of the matching event listeners throws an error. + +```ts +import { Emitter, TypedEvent } from 'rettime' + +const emitter = new Emitter<{ hello: TypedEvent> }>() + +emitter.on('hello', async (event) => { + await sleep(100) + return event.data + 1 +}) +emitter.on('hello', async (event) => event.data + 2) + +const values = await emitter.emitAsPromise(new TypedEvent('hello', { data: 1 })) +// [2, 3] +``` + +> Unlike `.emit()`, the `.emitAsPromise()` method _awaits asynchronous listeners_. + +### `.emitAsGenerator(type[, data])` + +Emits the given event and returns a generator function that exhausts all matching event listeners. Using a generator gives you granular control over what listeners are called. + +```ts +import { Emitter, TypedEvent } from 'rettime' + +const emitter = new Emitter<{ hello: TypedEvent }>() + +emitter.on('hello', () => 1) +emitter.on('hello', () => 2) + +for (const listenerResult of emitter.emitAsGenerator( + new TypedEvent('hello', { data: 'John' }), +)) { + // Stop event emission if a listener returns a particular value. + if (listenerResult === 1) { + break + } +} +``` + +### `.listeners([type])` + +Returns the list of all event listeners matching the given event type. If no event `type` is provided, returns the list of all existing event listeners. + +### `.listenerCount([type])` + +Returns the number of the event listeners matching the given event type. If no event `type` is provided, returns the total number of existing listeners. + +### `.removeListener(type, listener)` + +Removes the event listener for the given event type. + +### `.removeAllListeners([type])` + +Removes all event listeners for the given event type. If no event `type` is provided, removes all existing event listeners. + +## Types + +This library comes with a set of helper types for building absurdly strongly typed emitters. + +### `EventMap` + +#### `EventMap.EventTypes` + +Returns a union of all the event types from the given event map. + +```ts +type MyEventMap = { greeting: TypedEvent; handshake: TypedEvent } + +type Events = EventMap.EventTypes +// "greeting" | "handshake" +``` + + +#### `EventMap.Events` + +Returns a union of all public events from the given event map. + +```ts +class GreetingEvent extends TypedEvent {} + +type MyEventMap = { greeting: GreetingEvent; handshake: TypedEvent } + +type Events = EventMap.Events +// GreetingEvent | TypedEvent +``` + +#### `EventMap.Event` + +Returns the `Event` type (or its subtype) representing the given event type. + +```ts +import { EventMap, TypedEvent } from 'rettime' + +type MyEventMap = { greeting: TypedEvent<'john'> } +type GreetingEvent = EventMap.Event +// TypedEvent<'john'> +``` + +#### `EventMap.EventData` + +Returns the data type of the given event type. + +```ts +import { EventMap, TypedEvent } from 'rettime' + +type MyEventMap = { greeting: TypedEvent<'hello'> } +type GreetingData = EventMap.EventData +// "hello" +``` + +#### `EventMap.Listener` + +Returns the type of the given event's listener. + +```ts +import { EventMap, TypedEvent } from 'rettime' + +type MyEventMap = { greeting: TypedEvent } +type GreetingListener = EventMap.Listener +// (event: TypedEvent) => number[] +``` + +#### `EventMap.ListenerReturnType` + +Returns the return type of the given event's listener. + +```ts +import { EventMap, TypedEvent } from 'rettime' + +type MyEventMap = { getTotalPrice: TypedEvent } +type CartTotal = EventMap.ListenerReturnType +// number +``` + +### `Emitter` + +#### `Emitter.AllEventTypes` + +Returns a union of all the event types, both public and reserved, for the given emitter. + +```ts +const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>() + +type Events = Emitter.AllEventTypes +// "*" | "greeting" | "handshake" +``` + +#### `Emitter.PublicEventTypes` + +Returns a union of the public event types for the given emitter. + +```ts +const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>() + +type Events = Emitter.PublicEventTypes +// "greeting" | "handshake" +``` + +> Public events exclude reserved events like `*`. + +#### `Emitter.Events` + +Returns a union of all public events for the given emitter. + +```ts +class GreetingEvent extends TypedEvent {} + +const emitter = new Emitter<{ greeting: GreetingEvent, handshake: TypedEvent }>() + +type Events = Emitter.Events +// GreetingEvent | TypedEvent +``` + +#### `Emitter.Event` + +Returns the `Event` type (or its subtype) representing the given listener. + +```ts +import { Emitter, TypedEvent } from 'rettime' + +const emitter = new Emitter<{ greeting: TypedEvent<'john'> }>() +type GreetingEvent = Emitter.Event +// TypedEvent<'john'> +``` + +#### `Emitter.Listener` + +Returns the type of the given event's listener. + +```ts +import { Emitter, TypedEvent } from 'rettime' + +const emitter = new Emitter<{ greeting: TypedEvent }>() +type GreetingListener = Emitter.Listener +// (event: TypedEvent) => number[] +``` + +> The `Listener` helper is in itself type-safe, allowing only known event types as the second argument. + +#### `Emitter.ListenerReturnType` + +Returns the return type of the given event's listener. + +```ts +import { Emitter, TypedEvent } from 'rettime' + +const emitter = new Emitter<{ getTotalPrice: TypedEvent }>() +type CartTotal = Emitter.ListenerReturnType +// number +``` diff --git a/node_modules/rettime/build/index.d.mts b/node_modules/rettime/build/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..b8dba5849caf929de6a98ab44b4c542c10479a3a --- /dev/null +++ b/node_modules/rettime/build/index.d.mts @@ -0,0 +1,254 @@ +//#region src/index.d.ts +type DefaultEventMap = { + [eventType: string]: TypedEvent; +}; +/** + * Reserved event map containing special event types like '*' for catch-all listeners. + */ +type ReservedEventMap = { + '*': TypedEvent; +}; +type IsReservedEvent = Type extends keyof ReservedEventMap ? true : false; +interface TypedEvent extends Omit, 'type'> { + type: EventType; +} +declare const kDefaultPrevented: unique symbol; +declare const kPropagationStopped: unique symbol; +declare const kImmediatePropagationStopped: unique symbol; +declare class TypedEvent extends MessageEvent implements TypedEvent { + #private; + [kDefaultPrevented]: boolean; + [kPropagationStopped]?: Emitter; + [kImmediatePropagationStopped]?: boolean; + constructor(...args: [DataType] extends [void] ? [type: EventType] : [type: EventType, init: { + data: DataType; + }]); + get defaultPrevented(): boolean; + preventDefault(): void; + stopImmediatePropagation(): void; +} +/** + * Brands a TypedEvent or its subclass while preserving its (narrower) type. + */ +type Brand = Loose extends true ? Event extends TypedEvent ? +/** +* @note Omit the `ReturnType` so emit methods can accept type events +* where infering the return type is impossible. +*/ +TypedEvent & { + type: EventType; +} : never : Event & { + type: EventType; +}; +type InferEventMap> = Target extends Emitter ? WithReservedEvents : never; +/** + * Extracts only user-defined events, excluding reserved event types. + */ +type UserEventMap = Omit; +/** + * Decorates the given `EventMap` with the reserved emitter events (e.g. `*`). + */ +type WithReservedEvents = EventMap$1 & ReservedEventMap; +/** + * Creates a union of all events in the EventMap with their literal type strings. + */ +type AllEvents = { [K in keyof EventMap$1 & string]: Brand }[keyof EventMap$1 & string]; +type TypedListenerOptions = { + once?: boolean; + signal?: AbortSignal; +}; +interface HookListenerOptions extends TypedListenerOptions { + persist?: boolean; +} +type EmitterHookMap = { + newListener: (type: keyof WithReservedEvents & string, listener: { [K in keyof WithReservedEvents & string]: Emitter.Listener, K, WithReservedEvents> }[keyof WithReservedEvents & string], options: HookListenerOptions | undefined) => void; + removeListener: (type: keyof WithReservedEvents & string, listener: { [K in keyof WithReservedEvents & string]: Emitter.Listener, K, WithReservedEvents> }[keyof WithReservedEvents & string], options: HookListenerOptions | undefined) => void; + beforeEmit: (event: EventMap$1[keyof EventMap$1 & string]) => boolean | void; +}; +declare namespace Emitter { + /** + * Returns a union of all event types, both public and reserved, for the given emitter. + * + * @example + * const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>() + * type AllEventTypes = Emitter.AllEventTypes + * // "*" | "greeting" | "handshake" + */ + type AllEventTypes, EventMap$1 extends DefaultEventMap = InferEventMap> = string extends keyof EventMap$1 ? never : keyof EventMap$1 & string; + /** + * Returns a union of all public event types for the given emitter. + * + * @example + * const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>() + * type EventTypes = Emitter.EventTypes + * // "greeting" | "handshake" + */ + type PublicEventTypes, EventMap$1 extends DefaultEventMap = InferEventMap, UserEvents extends UserEventMap = UserEventMap> = string extends keyof UserEvents ? never : keyof UserEvents & string; + /** + * Returns a union of all public event type for the given emitter. + * + * @example + * const emitter = new Emitter<{ greeting: GreetingEvent, handshake: HandshakeEvent }>() + * type Events = Emitter.Events + * // GreetingEvent | HandshakeEvent + */ + type Events, EventMap$1 extends DefaultEventMap = InferEventMap> = string extends keyof UserEventMap ? never : UserEventMap[keyof UserEventMap]; + /** + * Returns an appropriate `Event` type for the given event type. + * + * @example + * const emitter = new Emitter<{ greeting: TypedEvent }>() + * type GreetingEvent = Emitter.Event + * // TypedEvent + */ + type Event, EventType extends keyof EventMap$1 & string, EventMap$1 extends DefaultEventMap = InferEventMap> = IsReservedEvent extends true ? AllEvents> : Brand; + /** + * Returns an appropriate event data type for the given event type. + * + * @example + * const emitter = new Emitter<{ greeting: TypedEvent<'hello'> }>() + * type GreetingData = Emitter.EventData + * // "hello" + */ + type EventData, EventType extends keyof EventMap$1 & string, EventMap$1 extends DefaultEventMap = InferEventMap> = EventMap$1[EventType] extends TypedEvent ? DataType : never; + /** + * Returns the listener type for the given event type. + * + * @example + * const emitter = new Emitter<{ getTotalPrice: TypedEvent }>() + * type Listener = Emitter.ListenerType + * // (event: TypedEvent) => number + */ + type Listener, EventType extends keyof EventMap$1 & string, EventMap$1 extends DefaultEventMap = InferEventMap> = IsReservedEvent extends true ? (event: Emitter.Event) => void : (event: Emitter.Event) => Emitter.ListenerReturnType extends [void] ? void : Emitter.ListenerReturnType; + /** + * Returns the return type of the listener for the given event type. + * + * @example + * const emitter = new Emitter<{ getTotalPrice: TypedEvent }>() + * type ListenerReturnType = Emitter.ListenerReturnType + * // number + */ + type ListenerReturnType, EventType extends keyof EventMap$1 & string, EventMap$1 extends DefaultEventMap = InferEventMap> = IsReservedEvent extends true ? void : EventMap$1[EventType] extends TypedEvent ? ReturnType : never; +} +declare namespace EventMap { + /** + * Returns a union of all public event types from the given event map. + * + * @example + * type MyEventMap = { greeting: TypedEvent, handshake: TypedEvent } + * type EventTypes = EventMap.EventTypes + * // "greeting" | "handshake" + */ + type EventTypes = Emitter.PublicEventTypes>; + /** + * Returns a union of all public event type from the given event map. + * + * @example + * type MyEventMap = { greeting: GreetingEvent, handshake: HandshakeEvent } + * type Events = EventMap.Events + * // GreetingEvent | HandshakeEvent + */ + type Events = Emitter.Events>; + /** + * Returns an appropriate `Event` type for the given event type. + * + * @example + * type MyEventMap = { greeting: TypedEvent } + * type GreetingEvent = EventMap.Event + * // TypedEvent + */ + type Event & string> = Emitter.Event, Type, WithReservedEvents>; + /** + * Returns an appropriate event data type for the given event type. + * + * @example + * type MyEventMap = { greeting: TypedEvent<'hello'> } + * type GreetingData = EventMap.EventData + * // "hello" + */ + type EventData & string> = Emitter.EventData, Type, WithReservedEvents>; + /** + * Returns the listener type for the given event type. + * + * @example + * type MyEventMap = { getTotalPrice: TypedEvent }> + * type Listener = EventMap.Listener + * // (event: TypedEvent) => number + */ + type Listener & string> = Emitter.Listener, Type, WithReservedEvents>; + /** + * Returns the return type of the listener for the given event type. + * + * @example + * type MyEventMap = { getTotalPrice: TypedEvent } + * type ListenerReturnType = EventMap.ListenerReturnType + * // number + */ + type ListenerReturnType & string> = Emitter.ListenerReturnType, Type, WithReservedEvents>; +} +declare class Emitter { + #private; + readonly hooks: { + on>(type: HookType, callback: EmitterHookMap[HookType], options?: HookListenerOptions): void; + removeListener>(type: HookType, callback: EmitterHookMap[HookType], options?: HookListenerOptions): void; + }; + constructor(); + /** + * Adds a listener for the given event type. + */ + on & string>(type: EventType, listener: Emitter.Listener>, options?: TypedListenerOptions): typeof this; + /** + * Adds a one-time listener for the given event type. + */ + once & string>(type: EventType, listener: Emitter.Listener>, options?: Omit): typeof this; + /** + * Prepends a listener for the given event type. + */ + earlyOn & string>(type: EventType, listener: Emitter.Listener>, options?: TypedListenerOptions): typeof this; + /** + * Prepends a one-time listener for the given event type. + */ + earlyOnce & string>(type: EventType, listener: Emitter.Listener>, options?: Omit): typeof this; + /** + * Emits the given typed event. + * + * @returns {boolean} Returns `true` if the event had any listeners, `false` otherwise. + */ + emit(event: Brand): boolean; + /** + * Emits the given typed event and returns a promise that resolves + * when all the listeners for that event have settled. + * + * @returns {Promise>} A promise that resolves + * with the return values of all listeners. + */ + emitAsPromise(event: Brand): Promise>>; + /** + * Emits the given event and returns a generator that yields + * the result of each listener in the order of their registration. + * This way, you stop exhausting the listeners once you get the expected value. + */ + emitAsGenerator(event: Brand): Generator>; + /** + * Removes a listener for the given event type. + */ + removeListener & string>(type: EventType, listener: Emitter.Listener>): void; + /** + * Removes all listeners for the given event type. + * If no event type is provided, removes all existing listeners. + */ + removeAllListeners & string>(type?: EventType): void; + /** + * Returns the list of listeners for the given event type. + * If no even type is provided, returns all listeners. + */ + listeners & string>(type?: EventType): Array>>; + /** + * Returns the number of listeners for the given event type. + * If no even type is provided, returns the total number of listeners. + */ + listenerCount & string>(type?: EventType): number; +} +//#endregion +export { DefaultEventMap, Emitter, EmitterHookMap, EventMap, HookListenerOptions, ReservedEventMap, TypedEvent, TypedListenerOptions, WithReservedEvents }; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/node_modules/rettime/build/index.mjs b/node_modules/rettime/build/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1fb610d917badb7442c1995a2ee0da15b1994c57 --- /dev/null +++ b/node_modules/rettime/build/index.mjs @@ -0,0 +1,312 @@ +import { LensList } from "./lens-list.mjs"; + +//#region src/index.ts +const kDefaultPrevented = Symbol("kDefaultPrevented"); +const kPropagationStopped = Symbol("kPropagationStopped"); +const kImmediatePropagationStopped = Symbol("kImmediatePropagationStopped"); +var TypedEvent = class extends MessageEvent { + /** + * @note Keep a placeholder property with the return type + * because the type must be set somewhere in order to be + * correctly associated and inferred from the event. + */ + #returnType; + [kDefaultPrevented]; + [kPropagationStopped]; + [kImmediatePropagationStopped]; + constructor(...args) { + super(args[0], args[1]); + this[kDefaultPrevented] = false; + } + get defaultPrevented() { + return this[kDefaultPrevented]; + } + preventDefault() { + super.preventDefault(); + this[kDefaultPrevented] = true; + } + stopImmediatePropagation() { + /** + * @note Despite `.stopPropagation()` and `.stopImmediatePropagation()` being defined + * in Node.js, they do nothing. It is safe to re-define them. + */ + super.stopImmediatePropagation(); + this[kImmediatePropagationStopped] = true; + } +}; +var Emitter = class { + #listeners; + #listenerOptions; + #listenerAbortCleanups; + #typelessListeners; + #hookListeners; + #hookListenerOptions; + #hookListenerAbortCleanups; + hooks; + constructor() { + this.#listeners = new LensList(); + this.#listenerOptions = /* @__PURE__ */ new WeakMap(); + this.#listenerAbortCleanups = /* @__PURE__ */ new WeakMap(); + this.#typelessListeners = /* @__PURE__ */ new WeakSet(); + this.#hookListeners = new LensList(); + this.#hookListenerOptions = /* @__PURE__ */ new WeakMap(); + this.#hookListenerAbortCleanups = /* @__PURE__ */ new WeakMap(); + this.hooks = { + on: (hook, callback, options) => { + /** + * @note An already-aborted signal would never fire its 'abort' event, + * leaving the hook registered indefinitely. Skip registration entirely. + */ + if (options?.signal?.aborted) return; + if (options?.once) { + const original = callback; + const wrapper = ((...args) => { + this.#deleteHookListener(hook, wrapper); + return original(...args); + }); + callback = wrapper; + } + this.#hookListeners.append(hook, callback); + if (options) this.#hookListenerOptions.set(callback, options); + if (options?.signal) { + const { signal } = options; + const onAbort = () => { + this.#deleteHookListener(hook, callback); + }; + signal.addEventListener("abort", onAbort, { once: true }); + this.#hookListenerAbortCleanups.set(callback, () => { + signal.removeEventListener("abort", onAbort); + }); + } + }, + removeListener: (hook, callback) => { + this.#deleteHookListener(hook, callback); + } + }; + } + #deleteHookListener(hook, callback) { + this.#hookListeners.delete(hook, callback); + const cleanup = this.#hookListenerAbortCleanups.get(callback); + if (cleanup) { + cleanup(); + this.#hookListenerAbortCleanups.delete(callback); + } + } + #deleteListener(type, listener) { + const removed = this.#listeners.delete(type, listener); + const cleanup = this.#listenerAbortCleanups.get(listener); + if (cleanup) { + cleanup(); + this.#listenerAbortCleanups.delete(listener); + } + return removed; + } + /** + * Adds a listener for the given event type. + */ + on(type, listener, options) { + this.#addListener(type, listener, options); + return this; + } + /** + * Adds a one-time listener for the given event type. + */ + once(type, listener, options) { + return this.on(type, listener, { + ...options || {}, + once: true + }); + } + /** + * Prepends a listener for the given event type. + */ + earlyOn(type, listener, options) { + this.#addListener(type, listener, options, "prepend"); + return this; + } + /** + * Prepends a one-time listener for the given event type. + */ + earlyOnce(type, listener, options) { + return this.earlyOn(type, listener, { + ...options || {}, + once: true + }); + } + /** + * Emits the given typed event. + * + * @returns {boolean} Returns `true` if the event had any listeners, `false` otherwise. + */ + emit(event) { + if (this.#listeners.size === 0) return false; + /** + * @note Calculate matching listeners before calling them + * since one-time listeners will self-destruct. + */ + const hasListeners = this.listenerCount(event.type) > 0; + const proxiedEvent = this.#proxyEvent(event); + for (const listener of this.#matchListeners(event.type)) { + if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) { + proxiedEvent.revoke(); + return false; + } + if (proxiedEvent.event[kImmediatePropagationStopped]) break; + this.#callListener(proxiedEvent.event, listener); + } + proxiedEvent.revoke(); + return hasListeners; + } + /** + * Emits the given typed event and returns a promise that resolves + * when all the listeners for that event have settled. + * + * @returns {Promise>} A promise that resolves + * with the return values of all listeners. + */ + async emitAsPromise(event) { + if (this.#listeners.size === 0) return []; + const pendingListeners = []; + const proxiedEvent = this.#proxyEvent(event); + for (const listener of this.#matchListeners(event.type)) { + if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) { + proxiedEvent.revoke(); + return []; + } + if (proxiedEvent.event[kImmediatePropagationStopped]) break; + const returnValue = await Promise.resolve(this.#callListener(proxiedEvent.event, listener)); + if (!this.#isTypelessListener(listener)) pendingListeners.push(returnValue); + } + proxiedEvent.revoke(); + return Promise.allSettled(pendingListeners).then((results) => { + return results.map((result) => result.status === "fulfilled" ? result.value : result.reason); + }); + } + /** + * Emits the given event and returns a generator that yields + * the result of each listener in the order of their registration. + * This way, you stop exhausting the listeners once you get the expected value. + */ + *emitAsGenerator(event) { + if (this.#listeners.size === 0) return; + const proxiedEvent = this.#proxyEvent(event); + for (const listener of this.#matchListeners(event.type)) { + if (proxiedEvent.event[kPropagationStopped] != null && proxiedEvent.event[kPropagationStopped] !== this) { + proxiedEvent.revoke(); + return; + } + if (proxiedEvent.event[kImmediatePropagationStopped]) break; + const returnValue = this.#callListener(proxiedEvent.event, listener); + if (!this.#isTypelessListener(listener)) yield returnValue; + } + proxiedEvent.revoke(); + } + /** + * Removes a listener for the given event type. + */ + removeListener(type, listener) { + const options = this.#listenerOptions.get(listener); + if (!this.#deleteListener(type, listener)) return; + /** + * @note Snapshot the hook list before iterating so a hook that removes + * another `removeListener` hook can't shift the live array mid-iteration. + */ + for (const hook of this.#hookListeners.get("removeListener").slice()) hook(type, listener, options); + } + /** + * Removes all listeners for the given event type. + * If no event type is provided, removes all existing listeners. + */ + removeAllListeners(type) { + if (type == null) { + for (const [listenerType, listeners$1] of this.#listeners.entries()) while (listeners$1.length > 0) this.removeListener(listenerType, listeners$1[0]); + for (const [hookType, hookListener] of [...this.#hookListeners]) if (!this.#hookListenerOptions.get(hookListener)?.persist) this.#deleteHookListener(hookType, hookListener); + return; + } + const listeners = this.listeners(type); + while (listeners.length > 0) this.removeListener(type, listeners[0]); + } + /** + * Returns the list of listeners for the given event type. + * If no even type is provided, returns all listeners. + */ + listeners(type) { + if (type == null) return this.#listeners.getAll(); + return this.#listeners.get(type); + } + /** + * Returns the number of listeners for the given event type. + * If no even type is provided, returns the total number of listeners. + */ + listenerCount(type) { + if (type == null) return this.#listeners.size; + return this.listeners(type).length; + } + #addListener(type, listener, options, insertMode = "append") { + /** + * @note An already-aborted signal would never fire its 'abort' event, + * leaving the listener registered indefinitely. Skip registration entirely. + */ + if (options?.signal?.aborted) return; + for (const hook of this.#hookListeners.get("newListener").slice()) hook(type, listener, options); + if (type === "*") this.#typelessListeners.add(listener); + if (insertMode === "prepend") this.#listeners.prepend(type, listener); + else this.#listeners.append(type, listener); + if (options) { + this.#listenerOptions.set(listener, options); + if (options.signal) { + const { signal } = options; + const onAbort = () => { + this.removeListener(type, listener); + }; + signal.addEventListener("abort", onAbort, { once: true }); + this.#listenerAbortCleanups.set(listener, () => { + signal.removeEventListener("abort", onAbort); + }); + } + } + } + #proxyEvent(event) { + const { stopPropagation } = event; + event.stopPropagation = () => { + event[kPropagationStopped] = this; + stopPropagation.call(event); + }; + return { + event, + revoke() { + event.stopPropagation = stopPropagation; + } + }; + } + #callListener(event, listener) { + for (const hook of this.#hookListeners.get("beforeEmit").slice()) if (hook(event) === false) return; + const returnValue = listener.call(this, event); + const options = this.#listenerOptions.get(listener); + if (options?.once) { + const type = this.#isTypelessListener(listener) ? "*" : event.type; + if (this.#deleteListener(type, listener)) for (const hook of this.#hookListeners.get("removeListener").slice()) hook(type, listener, options); + } + return returnValue; + } + /** + * Return a list of all event listeners relevant for the given event type. + * This includes the explicit event listeners and also typeless event listeners. + * + * @note Snapshot the matching listeners before yielding. Listeners can add or + * remove other listeners during emission (e.g. `earlyOn` unshifts `#list`), + * which would otherwise shift the live iterator and re-yield prior entries. + */ + *#matchListeners(type) { + const snapshot = []; + for (const [key, listener] of this.#listeners) if (key === "*" || key === type) snapshot.push(listener); + yield* snapshot; + } + #isTypelessListener(listener) { + return this.#typelessListeners.has(listener); + } +}; + +//#endregion +export { Emitter, TypedEvent }; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/rettime/build/index.mjs.map b/node_modules/rettime/build/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..484fc43f89cc21a443453032fc3409e68093e83e --- /dev/null +++ b/node_modules/rettime/build/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","names":["#listeners","#listenerOptions","#listenerAbortCleanups","#typelessListeners","#hookListeners","#hookListenerOptions","#hookListenerAbortCleanups","#deleteHookListener","#addListener","#proxyEvent","#matchListeners","#callListener","#isTypelessListener","#deleteListener","listeners"],"sources":["../src/index.ts"],"sourcesContent":["import { LensList } from './lens-list'\n\nexport type DefaultEventMap = {\n [eventType: string]: TypedEvent\n}\n\n/**\n * Reserved event map containing special event types like '*' for catch-all listeners.\n */\nexport type ReservedEventMap = {\n '*': TypedEvent\n}\n\ntype IsReservedEvent = Type extends keyof ReservedEventMap\n ? true\n : false\n\nexport interface TypedEvent<\n DataType = void,\n ReturnType = void,\n EventType extends string = string,\n> extends Omit, 'type'> {\n type: EventType\n}\n\nconst kDefaultPrevented = Symbol('kDefaultPrevented')\nconst kPropagationStopped = Symbol('kPropagationStopped')\nconst kImmediatePropagationStopped = Symbol('kImmediatePropagationStopped')\n\nexport class TypedEvent<\n DataType = void,\n ReturnType = void,\n EventType extends string = string,\n>\n extends MessageEvent\n implements TypedEvent\n{\n /**\n * @note Keep a placeholder property with the return type\n * because the type must be set somewhere in order to be\n * correctly associated and inferred from the event.\n */\n #returnType: ReturnType;\n\n [kDefaultPrevented]: boolean;\n [kPropagationStopped]?: Emitter;\n [kImmediatePropagationStopped]?: boolean\n\n constructor(\n ...args: [DataType] extends [void]\n ? [type: EventType]\n : [type: EventType, init: { data: DataType }]\n ) {\n super(args[0], args[1])\n this[kDefaultPrevented] = false\n }\n\n get defaultPrevented(): boolean {\n return this[kDefaultPrevented]\n }\n\n public preventDefault(): void {\n super.preventDefault()\n this[kDefaultPrevented] = true\n }\n\n public stopImmediatePropagation(): void {\n /**\n * @note Despite `.stopPropagation()` and `.stopImmediatePropagation()` being defined\n * in Node.js, they do nothing. It is safe to re-define them.\n */\n super.stopImmediatePropagation()\n this[kImmediatePropagationStopped] = true\n }\n}\n\n/**\n * Brands a TypedEvent or its subclass while preserving its (narrower) type.\n */\ntype Brand<\n Event extends TypedEvent,\n EventType extends string,\n Loose extends boolean = false,\n> = Loose extends true\n ? Event extends TypedEvent\n ? /**\n * @note Omit the `ReturnType` so emit methods can accept type events\n * where infering the return type is impossible.\n */\n TypedEvent & {\n type: EventType\n }\n : never\n : Event & { type: EventType }\n\ntype InferEventMap> =\n Target extends Emitter ? WithReservedEvents : never\n\n/**\n * Extracts only user-defined events, excluding reserved event types.\n */\ntype UserEventMap = Omit<\n EventMap,\n keyof ReservedEventMap\n>\n\n/**\n * Decorates the given `EventMap` with the reserved emitter events (e.g. `*`).\n */\nexport type WithReservedEvents = EventMap &\n ReservedEventMap\n\n/**\n * Creates a union of all events in the EventMap with their literal type strings.\n */\ntype AllEvents = {\n [K in keyof EventMap & string]: Brand\n}[keyof EventMap & string]\n\nexport type TypedListenerOptions = {\n once?: boolean\n signal?: AbortSignal\n}\n\nexport interface HookListenerOptions extends TypedListenerOptions {\n persist?: boolean\n}\n\nexport type EmitterHookMap = {\n newListener: (\n type: keyof WithReservedEvents & string,\n listener: {\n [K in keyof WithReservedEvents & string]: Emitter.Listener<\n Emitter,\n K,\n WithReservedEvents\n >\n }[keyof WithReservedEvents & string],\n options: HookListenerOptions | undefined,\n ) => void\n\n removeListener: (\n type: keyof WithReservedEvents & string,\n listener: {\n [K in keyof WithReservedEvents & string]: Emitter.Listener<\n Emitter,\n K,\n WithReservedEvents\n >\n }[keyof WithReservedEvents & string],\n options: HookListenerOptions | undefined,\n ) => void\n\n beforeEmit: (event: EventMap[keyof EventMap & string]) => boolean | void\n}\n\nexport namespace Emitter {\n /**\n * Returns a union of all event types, both public and reserved, for the given emitter.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>()\n * type AllEventTypes = Emitter.AllEventTypes\n * // \"*\" | \"greeting\" | \"handshake\"\n */\n export type AllEventTypes<\n Target extends Emitter,\n EventMap extends DefaultEventMap = InferEventMap,\n > = string extends keyof EventMap ? never : keyof EventMap & string\n\n /**\n * Returns a union of all public event types for the given emitter.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>()\n * type EventTypes = Emitter.EventTypes\n * // \"greeting\" | \"handshake\"\n */\n export type PublicEventTypes<\n Target extends Emitter,\n EventMap extends DefaultEventMap = InferEventMap,\n UserEvents extends UserEventMap = UserEventMap,\n > = string extends keyof UserEvents ? never : keyof UserEvents & string\n\n /**\n * Returns a union of all public event type for the given emitter.\n *\n * @example\n * const emitter = new Emitter<{ greeting: GreetingEvent, handshake: HandshakeEvent }>()\n * type Events = Emitter.Events\n * // GreetingEvent | HandshakeEvent\n */\n export type Events<\n Target extends Emitter,\n EventMap extends DefaultEventMap = InferEventMap,\n > = string extends keyof UserEventMap\n ? never\n : UserEventMap[keyof UserEventMap]\n\n /**\n * Returns an appropriate `Event` type for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent }>()\n * type GreetingEvent = Emitter.Event\n * // TypedEvent\n */\n export type Event<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > =\n IsReservedEvent extends true\n ? AllEvents>\n : Brand\n\n /**\n * Returns an appropriate event data type for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ greeting: TypedEvent<'hello'> }>()\n * type GreetingData = Emitter.EventData\n * // \"hello\"\n */\n export type EventData<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > = EventMap[EventType] extends TypedEvent ? DataType : never\n\n /**\n * Returns the listener type for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ getTotalPrice: TypedEvent }>()\n * type Listener = Emitter.ListenerType\n * // (event: TypedEvent) => number\n */\n export type Listener<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > =\n IsReservedEvent extends true\n ? (event: Emitter.Event) => void\n : (\n event: Emitter.Event,\n ) => Emitter.ListenerReturnType extends [\n void,\n ]\n ? void\n : Emitter.ListenerReturnType\n\n /**\n * Returns the return type of the listener for the given event type.\n *\n * @example\n * const emitter = new Emitter<{ getTotalPrice: TypedEvent }>()\n * type ListenerReturnType = Emitter.ListenerReturnType\n * // number\n */\n export type ListenerReturnType<\n Target extends Emitter,\n EventType extends keyof EventMap & string,\n EventMap extends DefaultEventMap = InferEventMap,\n > =\n IsReservedEvent extends true\n ? void\n : EventMap[EventType] extends TypedEvent\n ? ReturnType\n : never\n}\n\nexport namespace EventMap {\n /**\n * Returns a union of all public event types from the given event map.\n *\n * @example\n * type MyEventMap = { greeting: TypedEvent, handshake: TypedEvent }\n * type EventTypes = EventMap.EventTypes\n * // \"greeting\" | \"handshake\"\n */\n export type EventTypes =\n Emitter.PublicEventTypes>\n\n /**\n * Returns a union of all public event type from the given event map.\n *\n * @example\n * type MyEventMap = { greeting: GreetingEvent, handshake: HandshakeEvent }\n * type Events = EventMap.Events\n * // GreetingEvent | HandshakeEvent\n */\n export type Events = Emitter.Events>\n\n /**\n * Returns an appropriate `Event` type for the given event type.\n *\n * @example\n * type MyEventMap = { greeting: TypedEvent }\n * type GreetingEvent = EventMap.Event\n * // TypedEvent\n */\n export type Event<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.Event, Type, WithReservedEvents>\n\n /**\n * Returns an appropriate event data type for the given event type.\n *\n * @example\n * type MyEventMap = { greeting: TypedEvent<'hello'> }\n * type GreetingData = EventMap.EventData\n * // \"hello\"\n */\n export type EventData<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.EventData, Type, WithReservedEvents>\n\n /**\n * Returns the listener type for the given event type.\n *\n * @example\n * type MyEventMap = { getTotalPrice: TypedEvent }>\n * type Listener = EventMap.Listener\n * // (event: TypedEvent) => number\n */\n export type Listener<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.Listener, Type, WithReservedEvents>\n\n /**\n * Returns the return type of the listener for the given event type.\n *\n * @example\n * type MyEventMap = { getTotalPrice: TypedEvent }\n * type ListenerReturnType = EventMap.ListenerReturnType\n * // number\n */\n export type ListenerReturnType<\n Map extends DefaultEventMap,\n Type extends keyof WithReservedEvents & string,\n > = Emitter.ListenerReturnType, Type, WithReservedEvents>\n}\n\nexport class Emitter {\n #listeners: LensList<\n Record<\n string,\n Emitter.Listener<\n typeof this,\n keyof WithReservedEvents & string,\n WithReservedEvents\n >\n >\n >\n\n #listenerOptions: WeakMap\n #listenerAbortCleanups: WeakMap void>\n #typelessListeners: WeakSet\n\n #hookListeners: LensList>\n #hookListenerOptions: WeakMap\n #hookListenerAbortCleanups: WeakMap void>\n\n public readonly hooks: {\n on>(\n type: HookType,\n callback: EmitterHookMap[HookType],\n options?: HookListenerOptions,\n ): void\n\n removeListener>(\n type: HookType,\n callback: EmitterHookMap[HookType],\n options?: HookListenerOptions,\n ): void\n }\n\n constructor() {\n this.#listeners = new LensList()\n this.#listenerOptions = new WeakMap()\n this.#listenerAbortCleanups = new WeakMap()\n this.#typelessListeners = new WeakSet()\n this.#hookListeners = new LensList()\n this.#hookListenerOptions = new WeakMap()\n this.#hookListenerAbortCleanups = new WeakMap()\n\n this.hooks = {\n on: (hook, callback, options) => {\n /**\n * @note An already-aborted signal would never fire its 'abort' event,\n * leaving the hook registered indefinitely. Skip registration entirely.\n */\n if (options?.signal?.aborted) {\n return\n }\n\n if (options?.once) {\n const original = callback as (...args: Array) => void\n const wrapper = ((...args: Array) => {\n this.#deleteHookListener(hook, wrapper)\n return original(...args)\n }) as typeof callback\n callback = wrapper\n }\n\n this.#hookListeners.append(hook, callback)\n\n if (options) {\n this.#hookListenerOptions.set(callback, options)\n }\n\n if (options?.signal) {\n const { signal } = options\n const onAbort = () => {\n this.#deleteHookListener(hook, callback)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n this.#hookListenerAbortCleanups.set(callback, () => {\n signal.removeEventListener('abort', onAbort)\n })\n }\n },\n removeListener: (hook, callback) => {\n this.#deleteHookListener(hook, callback)\n },\n }\n }\n\n #deleteHookListener>(\n hook: HookType,\n callback: EmitterHookMap[HookType],\n ): void {\n this.#hookListeners.delete(hook, callback)\n const cleanup = this.#hookListenerAbortCleanups.get(callback)\n if (cleanup) {\n cleanup()\n this.#hookListenerAbortCleanups.delete(callback)\n }\n }\n\n #deleteListener<\n EventType extends keyof WithReservedEvents & string,\n >(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n ): boolean {\n const removed = this.#listeners.delete(type, listener)\n const cleanup = this.#listenerAbortCleanups.get(listener)\n if (cleanup) {\n cleanup()\n this.#listenerAbortCleanups.delete(listener)\n }\n return removed\n }\n\n /**\n * Adds a listener for the given event type.\n */\n public on & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: TypedListenerOptions,\n ): typeof this {\n this.#addListener(type, listener, options)\n return this\n }\n\n /**\n * Adds a one-time listener for the given event type.\n */\n public once & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: Omit,\n ): typeof this {\n return this.on(type, listener, {\n ...(options || {}),\n once: true,\n })\n }\n\n /**\n * Prepends a listener for the given event type.\n */\n public earlyOn & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: TypedListenerOptions,\n ): typeof this {\n this.#addListener(type, listener, options, 'prepend')\n return this\n }\n\n /**\n * Prepends a one-time listener for the given event type.\n */\n public earlyOnce<\n EventType extends keyof WithReservedEvents & string,\n >(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options?: Omit,\n ): typeof this {\n return this.earlyOn(type, listener, {\n ...(options || {}),\n once: true,\n })\n }\n\n /**\n * Emits the given typed event.\n *\n * @returns {boolean} Returns `true` if the event had any listeners, `false` otherwise.\n */\n public emit(\n event: Brand,\n ): boolean {\n if (this.#listeners.size === 0) {\n return false\n }\n\n /**\n * @note Calculate matching listeners before calling them\n * since one-time listeners will self-destruct.\n */\n const hasListeners = this.listenerCount(event.type) > 0\n\n const proxiedEvent = this.#proxyEvent(event)\n\n for (const listener of this.#matchListeners(event.type)) {\n if (\n proxiedEvent.event[kPropagationStopped] != null &&\n proxiedEvent.event[kPropagationStopped] !== this\n ) {\n proxiedEvent.revoke()\n return false\n }\n\n if (proxiedEvent.event[kImmediatePropagationStopped]) {\n break\n }\n\n this.#callListener(proxiedEvent.event, listener)\n }\n\n proxiedEvent.revoke()\n\n return hasListeners\n }\n\n /**\n * Emits the given typed event and returns a promise that resolves\n * when all the listeners for that event have settled.\n *\n * @returns {Promise>} A promise that resolves\n * with the return values of all listeners.\n */\n public async emitAsPromise(\n event: Brand,\n ): Promise<\n Array>\n > {\n if (this.#listeners.size === 0) {\n return []\n }\n\n const pendingListeners: Array<\n Promise>\n > = []\n\n const proxiedEvent = this.#proxyEvent(event)\n\n for (const listener of this.#matchListeners(event.type)) {\n if (\n proxiedEvent.event[kPropagationStopped] != null &&\n proxiedEvent.event[kPropagationStopped] !== this\n ) {\n proxiedEvent.revoke()\n return []\n }\n\n if (proxiedEvent.event[kImmediatePropagationStopped]) {\n break\n }\n\n const listenerPromise = Promise.resolve(\n this.#callListener(proxiedEvent.event, listener),\n )\n\n const returnValue = await listenerPromise\n\n if (!this.#isTypelessListener(listener)) {\n pendingListeners.push(returnValue)\n }\n }\n\n proxiedEvent.revoke()\n\n return Promise.allSettled(pendingListeners).then((results) => {\n return results.map((result) =>\n result.status === 'fulfilled' ? result.value : result.reason,\n )\n })\n }\n\n /**\n * Emits the given event and returns a generator that yields\n * the result of each listener in the order of their registration.\n * This way, you stop exhausting the listeners once you get the expected value.\n */\n public *emitAsGenerator(\n event: Brand,\n ): Generator> {\n if (this.#listeners.size === 0) {\n return\n }\n\n const proxiedEvent = this.#proxyEvent(event)\n\n for (const listener of this.#matchListeners(event.type)) {\n if (\n proxiedEvent.event[kPropagationStopped] != null &&\n proxiedEvent.event[kPropagationStopped] !== this\n ) {\n proxiedEvent.revoke()\n return\n }\n\n if (proxiedEvent.event[kImmediatePropagationStopped]) {\n break\n }\n\n const returnValue = this.#callListener(proxiedEvent.event, listener)\n\n if (!this.#isTypelessListener(listener)) {\n yield returnValue\n }\n }\n\n proxiedEvent.revoke()\n }\n\n /**\n * Removes a listener for the given event type.\n */\n public removeListener<\n EventType extends keyof WithReservedEvents & string,\n >(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n ): void {\n const options = this.#listenerOptions.get(listener)\n\n if (!this.#deleteListener(type, listener)) {\n return\n }\n\n /**\n * @note Snapshot the hook list before iterating so a hook that removes\n * another `removeListener` hook can't shift the live array mid-iteration.\n */\n for (const hook of this.#hookListeners.get('removeListener').slice()) {\n hook(\n type,\n listener as Parameters['removeListener']>[1],\n options,\n )\n }\n }\n\n /**\n * Removes all listeners for the given event type.\n * If no event type is provided, removes all existing listeners.\n */\n public removeAllListeners<\n EventType extends keyof WithReservedEvents & string,\n >(type?: EventType): void {\n if (type == null) {\n for (const [listenerType, listeners] of this.#listeners.entries()) {\n while (listeners.length > 0) {\n this.removeListener(\n listenerType as keyof WithReservedEvents & string,\n listeners[0],\n )\n }\n }\n\n for (const [hookType, hookListener] of [...this.#hookListeners]) {\n if (!this.#hookListenerOptions.get(hookListener)?.persist) {\n this.#deleteHookListener(\n hookType as keyof EmitterHookMap,\n hookListener as EmitterHookMap[keyof EmitterHookMap],\n )\n }\n }\n\n return\n }\n\n const listeners = this.listeners(type)\n\n while (listeners.length > 0) {\n this.removeListener(type, listeners[0])\n }\n }\n\n /**\n * Returns the list of listeners for the given event type.\n * If no even type is provided, returns all listeners.\n */\n public listeners<\n EventType extends keyof WithReservedEvents & string,\n >(\n type?: EventType,\n ): Array<\n Emitter.Listener>\n > {\n if (type == null) {\n return this.#listeners.getAll()\n }\n\n return this.#listeners.get(type)\n }\n\n /**\n * Returns the number of listeners for the given event type.\n * If no even type is provided, returns the total number of listeners.\n */\n public listenerCount<\n EventType extends keyof WithReservedEvents & string,\n >(type?: EventType): number {\n if (type == null) {\n return this.#listeners.size\n }\n\n return this.listeners(type).length\n }\n\n #addListener & string>(\n type: EventType,\n listener: Emitter.Listener<\n typeof this,\n EventType,\n WithReservedEvents\n >,\n options: TypedListenerOptions | undefined,\n insertMode: 'append' | 'prepend' = 'append',\n ): void {\n /**\n * @note An already-aborted signal would never fire its 'abort' event,\n * leaving the listener registered indefinitely. Skip registration entirely.\n */\n if (options?.signal?.aborted) {\n return\n }\n\n for (const hook of this.#hookListeners.get('newListener').slice()) {\n hook(\n type,\n listener as Parameters['newListener']>[1],\n options,\n )\n }\n\n if (type === '*') {\n this.#typelessListeners.add(listener)\n }\n\n if (insertMode === 'prepend') {\n this.#listeners.prepend(type, listener)\n } else {\n this.#listeners.append(type, listener)\n }\n\n if (options) {\n this.#listenerOptions.set(listener, options)\n\n if (options.signal) {\n const { signal } = options\n const onAbort = () => {\n this.removeListener(type, listener)\n }\n signal.addEventListener('abort', onAbort, { once: true })\n this.#listenerAbortCleanups.set(listener, () => {\n signal.removeEventListener('abort', onAbort)\n })\n }\n }\n }\n\n #proxyEvent(\n event: Event,\n ): { event: Event; revoke: () => void } {\n const { stopPropagation } = event\n\n event.stopPropagation = () => {\n event[kPropagationStopped] = this\n stopPropagation.call(event)\n }\n\n return {\n event,\n revoke() {\n event.stopPropagation = stopPropagation\n },\n }\n }\n\n #callListener(event: Event, listener: (event: any) => any) {\n for (const hook of this.#hookListeners.get('beforeEmit').slice()) {\n if (hook(event as EventMap[keyof EventMap & string]) === false) {\n return\n }\n }\n\n const returnValue = listener.call(this, event)\n\n const options = this.#listenerOptions.get(listener)\n\n if (options?.once) {\n const type = this.#isTypelessListener(listener) ? '*' : event.type\n\n if (this.#deleteListener(type, listener)) {\n for (const hook of this.#hookListeners.get('removeListener').slice()) {\n hook(type, listener, options)\n }\n }\n }\n\n return returnValue\n }\n\n /**\n * Return a list of all event listeners relevant for the given event type.\n * This includes the explicit event listeners and also typeless event listeners.\n *\n * @note Snapshot the matching listeners before yielding. Listeners can add or\n * remove other listeners during emission (e.g. `earlyOn` unshifts `#list`),\n * which would otherwise shift the live iterator and re-yield prior entries.\n */\n *#matchListeners(type: EventType) {\n const snapshot: Array<\n Emitter.Listener<\n typeof this,\n keyof WithReservedEvents & string,\n WithReservedEvents\n >\n > = []\n for (const [key, listener] of this.#listeners) {\n if (key === '*' || key === type) {\n snapshot.push(listener)\n }\n }\n yield* snapshot\n }\n\n #isTypelessListener(listener: any): boolean {\n return this.#typelessListeners.has(listener)\n }\n}\n"],"mappings":";;;AAyBA,MAAM,oBAAoB,OAAO,oBAAoB;AACrD,MAAM,sBAAsB,OAAO,sBAAsB;AACzD,MAAM,+BAA+B,OAAO,+BAA+B;AAE3E,IAAa,aAAb,cAKU,aAEV;;;;;;CAME;CAEA,CAAC;CACD,CAAC;CACD,CAAC;CAED,YACE,GAAG,MAGH;AACA,QAAM,KAAK,IAAI,KAAK,GAAG;AACvB,OAAK,qBAAqB;;CAG5B,IAAI,mBAA4B;AAC9B,SAAO,KAAK;;CAGd,AAAO,iBAAuB;AAC5B,QAAM,gBAAgB;AACtB,OAAK,qBAAqB;;CAG5B,AAAO,2BAAiC;;;;;AAKtC,QAAM,0BAA0B;AAChC,OAAK,gCAAgC;;;AAoRzC,IAAa,UAAb,MAAuD;CACrD;CAWA;CACA;CACA;CAEA;CACA;CACA;CAEA,AAAgB;CAchB,cAAc;AACZ,QAAKA,YAAa,IAAI,UAAU;AAChC,QAAKC,kCAAmB,IAAI,SAAS;AACrC,QAAKC,wCAAyB,IAAI,SAAS;AAC3C,QAAKC,oCAAqB,IAAI,SAAS;AACvC,QAAKC,gBAAiB,IAAI,UAAU;AACpC,QAAKC,sCAAuB,IAAI,SAAS;AACzC,QAAKC,4CAA6B,IAAI,SAAS;AAE/C,OAAK,QAAQ;GACX,KAAK,MAAM,UAAU,YAAY;;;;;AAK/B,QAAI,SAAS,QAAQ,QACnB;AAGF,QAAI,SAAS,MAAM;KACjB,MAAM,WAAW;KACjB,MAAM,YAAY,GAAG,SAAqB;AACxC,YAAKC,mBAAoB,MAAM,QAAQ;AACvC,aAAO,SAAS,GAAG,KAAK;;AAE1B,gBAAW;;AAGb,UAAKH,cAAe,OAAO,MAAM,SAAS;AAE1C,QAAI,QACF,OAAKC,oBAAqB,IAAI,UAAU,QAAQ;AAGlD,QAAI,SAAS,QAAQ;KACnB,MAAM,EAAE,WAAW;KACnB,MAAM,gBAAgB;AACpB,YAAKE,mBAAoB,MAAM,SAAS;;AAE1C,YAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,MAAM,CAAC;AACzD,WAAKD,0BAA2B,IAAI,gBAAgB;AAClD,aAAO,oBAAoB,SAAS,QAAQ;OAC5C;;;GAGN,iBAAiB,MAAM,aAAa;AAClC,UAAKC,mBAAoB,MAAM,SAAS;;GAE3C;;CAGH,oBACE,MACA,UACM;AACN,QAAKH,cAAe,OAAO,MAAM,SAAS;EAC1C,MAAM,UAAU,MAAKE,0BAA2B,IAAI,SAAS;AAC7D,MAAI,SAAS;AACX,YAAS;AACT,SAAKA,0BAA2B,OAAO,SAAS;;;CAIpD,gBAGE,MACA,UAKS;EACT,MAAM,UAAU,MAAKN,UAAW,OAAO,MAAM,SAAS;EACtD,MAAM,UAAU,MAAKE,sBAAuB,IAAI,SAAS;AACzD,MAAI,SAAS;AACX,YAAS;AACT,SAAKA,sBAAuB,OAAO,SAAS;;AAE9C,SAAO;;;;;CAMT,AAAO,GACL,MACA,UAKA,SACa;AACb,QAAKM,YAAa,MAAM,UAAU,QAAQ;AAC1C,SAAO;;;;;CAMT,AAAO,KACL,MACA,UAKA,SACa;AACb,SAAO,KAAK,GAAG,MAAM,UAAU;GAC7B,GAAI,WAAW,EAAE;GACjB,MAAM;GACP,CAAC;;;;;CAMJ,AAAO,QACL,MACA,UAKA,SACa;AACb,QAAKA,YAAa,MAAM,UAAU,SAAS,UAAU;AACrD,SAAO;;;;;CAMT,AAAO,UAGL,MACA,UAKA,SACa;AACb,SAAO,KAAK,QAAQ,MAAM,UAAU;GAClC,GAAI,WAAW,EAAE;GACjB,MAAM;GACP,CAAC;;;;;;;CAQJ,AAAO,KACL,OACS;AACT,MAAI,MAAKR,UAAW,SAAS,EAC3B,QAAO;;;;;EAOT,MAAM,eAAe,KAAK,cAAc,MAAM,KAAK,GAAG;EAEtD,MAAM,eAAe,MAAKS,WAAY,MAAM;AAE5C,OAAK,MAAM,YAAY,MAAKC,eAAgB,MAAM,KAAK,EAAE;AACvD,OACE,aAAa,MAAM,wBAAwB,QAC3C,aAAa,MAAM,yBAAyB,MAC5C;AACA,iBAAa,QAAQ;AACrB,WAAO;;AAGT,OAAI,aAAa,MAAM,8BACrB;AAGF,SAAKC,aAAc,aAAa,OAAO,SAAS;;AAGlD,eAAa,QAAQ;AAErB,SAAO;;;;;;;;;CAUT,MAAa,cACX,OAGA;AACA,MAAI,MAAKX,UAAW,SAAS,EAC3B,QAAO,EAAE;EAGX,MAAM,mBAEF,EAAE;EAEN,MAAM,eAAe,MAAKS,WAAY,MAAM;AAE5C,OAAK,MAAM,YAAY,MAAKC,eAAgB,MAAM,KAAK,EAAE;AACvD,OACE,aAAa,MAAM,wBAAwB,QAC3C,aAAa,MAAM,yBAAyB,MAC5C;AACA,iBAAa,QAAQ;AACrB,WAAO,EAAE;;AAGX,OAAI,aAAa,MAAM,8BACrB;GAOF,MAAM,cAAc,MAJI,QAAQ,QAC9B,MAAKC,aAAc,aAAa,OAAO,SAAS,CACjD;AAID,OAAI,CAAC,MAAKC,mBAAoB,SAAS,CACrC,kBAAiB,KAAK,YAAY;;AAItC,eAAa,QAAQ;AAErB,SAAO,QAAQ,WAAW,iBAAiB,CAAC,MAAM,YAAY;AAC5D,UAAO,QAAQ,KAAK,WAClB,OAAO,WAAW,cAAc,OAAO,QAAQ,OAAO,OACvD;IACD;;;;;;;CAQJ,CAAQ,gBACN,OACyE;AACzE,MAAI,MAAKZ,UAAW,SAAS,EAC3B;EAGF,MAAM,eAAe,MAAKS,WAAY,MAAM;AAE5C,OAAK,MAAM,YAAY,MAAKC,eAAgB,MAAM,KAAK,EAAE;AACvD,OACE,aAAa,MAAM,wBAAwB,QAC3C,aAAa,MAAM,yBAAyB,MAC5C;AACA,iBAAa,QAAQ;AACrB;;AAGF,OAAI,aAAa,MAAM,8BACrB;GAGF,MAAM,cAAc,MAAKC,aAAc,aAAa,OAAO,SAAS;AAEpE,OAAI,CAAC,MAAKC,mBAAoB,SAAS,CACrC,OAAM;;AAIV,eAAa,QAAQ;;;;;CAMvB,AAAO,eAGL,MACA,UAKM;EACN,MAAM,UAAU,MAAKX,gBAAiB,IAAI,SAAS;AAEnD,MAAI,CAAC,MAAKY,eAAgB,MAAM,SAAS,CACvC;;;;;AAOF,OAAK,MAAM,QAAQ,MAAKT,cAAe,IAAI,iBAAiB,CAAC,OAAO,CAClE,MACE,MACA,UACA,QACD;;;;;;CAQL,AAAO,mBAEL,MAAwB;AACxB,MAAI,QAAQ,MAAM;AAChB,QAAK,MAAM,CAAC,cAAcU,gBAAc,MAAKd,UAAW,SAAS,CAC/D,QAAOc,YAAU,SAAS,EACxB,MAAK,eACH,cACAA,YAAU,GACX;AAIL,QAAK,MAAM,CAAC,UAAU,iBAAiB,CAAC,GAAG,MAAKV,cAAe,CAC7D,KAAI,CAAC,MAAKC,oBAAqB,IAAI,aAAa,EAAE,QAChD,OAAKE,mBACH,UACA,aACD;AAIL;;EAGF,MAAM,YAAY,KAAK,UAAU,KAAK;AAEtC,SAAO,UAAU,SAAS,EACxB,MAAK,eAAe,MAAM,UAAU,GAAG;;;;;;CAQ3C,AAAO,UAGL,MAGA;AACA,MAAI,QAAQ,KACV,QAAO,MAAKP,UAAW,QAAQ;AAGjC,SAAO,MAAKA,UAAW,IAAI,KAAK;;;;;;CAOlC,AAAO,cAEL,MAA0B;AAC1B,MAAI,QAAQ,KACV,QAAO,MAAKA,UAAW;AAGzB,SAAO,KAAK,UAAU,KAAK,CAAC;;CAG9B,aACE,MACA,UAKA,SACA,aAAmC,UAC7B;;;;;AAKN,MAAI,SAAS,QAAQ,QACnB;AAGF,OAAK,MAAM,QAAQ,MAAKI,cAAe,IAAI,cAAc,CAAC,OAAO,CAC/D,MACE,MACA,UACA,QACD;AAGH,MAAI,SAAS,IACX,OAAKD,kBAAmB,IAAI,SAAS;AAGvC,MAAI,eAAe,UACjB,OAAKH,UAAW,QAAQ,MAAM,SAAS;MAEvC,OAAKA,UAAW,OAAO,MAAM,SAAS;AAGxC,MAAI,SAAS;AACX,SAAKC,gBAAiB,IAAI,UAAU,QAAQ;AAE5C,OAAI,QAAQ,QAAQ;IAClB,MAAM,EAAE,WAAW;IACnB,MAAM,gBAAgB;AACpB,UAAK,eAAe,MAAM,SAAS;;AAErC,WAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,MAAM,CAAC;AACzD,UAAKC,sBAAuB,IAAI,gBAAgB;AAC9C,YAAO,oBAAoB,SAAS,QAAQ;MAC5C;;;;CAKR,YACE,OACsC;EACtC,MAAM,EAAE,oBAAoB;AAE5B,QAAM,wBAAwB;AAC5B,SAAM,uBAAuB;AAC7B,mBAAgB,KAAK,MAAM;;AAG7B,SAAO;GACL;GACA,SAAS;AACP,UAAM,kBAAkB;;GAE3B;;CAGH,cAAc,OAAc,UAA+B;AACzD,OAAK,MAAM,QAAQ,MAAKE,cAAe,IAAI,aAAa,CAAC,OAAO,CAC9D,KAAI,KAAK,MAA2C,KAAK,MACvD;EAIJ,MAAM,cAAc,SAAS,KAAK,MAAM,MAAM;EAE9C,MAAM,UAAU,MAAKH,gBAAiB,IAAI,SAAS;AAEnD,MAAI,SAAS,MAAM;GACjB,MAAM,OAAO,MAAKW,mBAAoB,SAAS,GAAG,MAAM,MAAM;AAE9D,OAAI,MAAKC,eAAgB,MAAM,SAAS,CACtC,MAAK,MAAM,QAAQ,MAAKT,cAAe,IAAI,iBAAiB,CAAC,OAAO,CAClE,MAAK,MAAM,UAAU,QAAQ;;AAKnC,SAAO;;;;;;;;;;CAWT,EAACM,eAA2D,MAAiB;EAC3E,MAAM,WAMF,EAAE;AACN,OAAK,MAAM,CAAC,KAAK,aAAa,MAAKV,UACjC,KAAI,QAAQ,OAAO,QAAQ,KACzB,UAAS,KAAK,SAAS;AAG3B,SAAO;;CAGT,oBAAoB,UAAwB;AAC1C,SAAO,MAAKG,kBAAmB,IAAI,SAAS"} \ No newline at end of file diff --git a/node_modules/rettime/build/lens-list.d.mts b/node_modules/rettime/build/lens-list.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..04c86e39acd7da9ef670d40d0390ca812bd48ada --- /dev/null +++ b/node_modules/rettime/build/lens-list.d.mts @@ -0,0 +1,38 @@ +//#region src/lens-list.d.ts +type Values = M[keyof M & string]; +declare class LensList> { + #private; + constructor(); + get [Symbol.iterator](): any; + entries(): MapIterator<[string, Values[]]>; + /** + * Return an order-sensitive list of values by the given key. + */ + get(key: K): Array; + /** + * Return an order-sensitive list of all values. + */ + getAll(): Array>; + /** + * Append a new value to the given key. + */ + append(key: K, value: ValueMap[K]): void; + /** + * Prepend a new value to the given key. + */ + prepend(key: K, value: ValueMap[K]): void; + /** + * Delete the value belonging to the given key. + * Returns `true` if the value was present and removed, `false` otherwise. + */ + delete(key: K, value: ValueMap[K]): boolean; + /** + * Delete all values belogning to the given key. + */ + deleteAll(key: K): void; + get size(): number; + clear(): void; +} +//#endregion +export { LensList }; +//# sourceMappingURL=lens-list.d.mts.map \ No newline at end of file diff --git a/node_modules/rettime/build/lens-list.mjs b/node_modules/rettime/build/lens-list.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ce2e97c45ff6d9908df68776f30999b4808ac545 --- /dev/null +++ b/node_modules/rettime/build/lens-list.mjs @@ -0,0 +1,78 @@ +//#region src/lens-list.ts +var LensList = class { + #list; + #lens; + constructor() { + this.#list = []; + this.#lens = /* @__PURE__ */ new Map(); + } + get [Symbol.iterator]() { + return this.#list[Symbol.iterator].bind(this.#list); + } + entries() { + return this.#lens.entries(); + } + /** + * Return an order-sensitive list of values by the given key. + */ + get(key) { + return this.#lens.get(key) || []; + } + /** + * Return an order-sensitive list of all values. + */ + getAll() { + return this.#list.map(([, value]) => value); + } + /** + * Append a new value to the given key. + */ + append(key, value) { + this.#list.push([key, value]); + this.#openLens(key, (list) => list.push(value)); + } + /** + * Prepend a new value to the given key. + */ + prepend(key, value) { + this.#list.unshift([key, value]); + this.#openLens(key, (list) => list.unshift(value)); + } + /** + * Delete the value belonging to the given key. + * Returns `true` if the value was present and removed, `false` otherwise. + */ + delete(key, value) { + if (this.size === 0) return false; + const values = this.#lens.get(key); + if (!values) return false; + const index = values.indexOf(value); + if (index === -1) return false; + values.splice(index, 1); + this.#list.splice(this.#list.findIndex((item) => item[0] === key && item[1] === value), 1); + return true; + } + /** + * Delete all values belogning to the given key. + */ + deleteAll(key) { + if (this.size === 0) return; + this.#list = this.#list.filter((item) => item[0] !== key); + this.#lens.delete(key); + } + get size() { + return this.#list.length; + } + clear() { + if (this.size === 0) return; + this.#list.length = 0; + this.#lens.clear(); + } + #openLens(key, setter) { + setter(this.#lens.get(key) || this.#lens.set(key, []).get(key)); + } +}; + +//#endregion +export { LensList }; +//# sourceMappingURL=lens-list.mjs.map \ No newline at end of file diff --git a/node_modules/rettime/build/lens-list.mjs.map b/node_modules/rettime/build/lens-list.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..9d9a7cd994774e6fd199d7ab39bbf8bdc779b89e --- /dev/null +++ b/node_modules/rettime/build/lens-list.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"lens-list.mjs","names":["#list","#lens","#openLens"],"sources":["../src/lens-list.ts"],"sourcesContent":["type Values = M[keyof M & string]\n\nexport class LensList> {\n #list: Array<[string, Values]>\n #lens: Map>>\n\n constructor() {\n this.#list = []\n this.#lens = new Map()\n }\n\n get [Symbol.iterator]() {\n // Return the list's iterator so iteration is order-sensitive.\n return this.#list[Symbol.iterator].bind(this.#list)\n }\n\n public entries() {\n return this.#lens.entries()\n }\n\n /**\n * Return an order-sensitive list of values by the given key.\n */\n public get(key: K): Array {\n return (this.#lens.get(key) || []) as Array\n }\n\n /**\n * Return an order-sensitive list of all values.\n */\n public getAll(): Array> {\n return this.#list.map(([, value]) => value)\n }\n\n /**\n * Append a new value to the given key.\n */\n public append(\n key: K,\n value: ValueMap[K],\n ): void {\n this.#list.push([key, value])\n this.#openLens(key, (list) => list.push(value))\n }\n\n /**\n * Prepend a new value to the given key.\n */\n public prepend(\n key: K,\n value: ValueMap[K],\n ): void {\n this.#list.unshift([key, value])\n this.#openLens(key, (list) => list.unshift(value))\n }\n\n /**\n * Delete the value belonging to the given key.\n * Returns `true` if the value was present and removed, `false` otherwise.\n */\n public delete(\n key: K,\n value: ValueMap[K],\n ): boolean {\n if (this.size === 0) {\n return false\n }\n\n const values = this.#lens.get(key)\n if (!values) {\n return false\n }\n\n const index = values.indexOf(value)\n if (index === -1) {\n return false\n }\n\n values.splice(index, 1)\n this.#list.splice(\n this.#list.findIndex(\n (item) => item[0] === key && item[1] === value,\n ),\n 1,\n )\n return true\n }\n\n /**\n * Delete all values belogning to the given key.\n */\n public deleteAll(key: K): void {\n if (this.size === 0) {\n return\n }\n\n this.#list = this.#list.filter((item) => item[0] !== key)\n this.#lens.delete(key)\n }\n\n get size(): number {\n return this.#list.length\n }\n\n public clear(): void {\n if (this.size === 0) {\n return\n }\n\n this.#list.length = 0\n this.#lens.clear()\n }\n\n #openLens(\n key: string,\n setter: (target: Array>) => void,\n ): void {\n setter(this.#lens.get(key) || this.#lens.set(key, []).get(key))\n }\n}\n"],"mappings":";AAEA,IAAa,WAAb,MAA4D;CAC1D;CACA;CAEA,cAAc;AACZ,QAAKA,OAAQ,EAAE;AACf,QAAKC,uBAAQ,IAAI,KAAK;;CAGxB,KAAK,OAAO,YAAY;AAEtB,SAAO,MAAKD,KAAM,OAAO,UAAU,KAAK,MAAKA,KAAM;;CAGrD,AAAO,UAAU;AACf,SAAO,MAAKC,KAAM,SAAS;;;;;CAM7B,AAAO,IAAuC,KAA4B;AACxE,SAAQ,MAAKA,KAAM,IAAI,IAAI,IAAI,EAAE;;;;;CAMnC,AAAO,SAAkC;AACvC,SAAO,MAAKD,KAAM,KAAK,GAAG,WAAW,MAAM;;;;;CAM7C,AAAO,OACL,KACA,OACM;AACN,QAAKA,KAAM,KAAK,CAAC,KAAK,MAAM,CAAC;AAC7B,QAAKE,SAAU,MAAM,SAAS,KAAK,KAAK,MAAM,CAAC;;;;;CAMjD,AAAO,QACL,KACA,OACM;AACN,QAAKF,KAAM,QAAQ,CAAC,KAAK,MAAM,CAAC;AAChC,QAAKE,SAAU,MAAM,SAAS,KAAK,QAAQ,MAAM,CAAC;;;;;;CAOpD,AAAO,OACL,KACA,OACS;AACT,MAAI,KAAK,SAAS,EAChB,QAAO;EAGT,MAAM,SAAS,MAAKD,KAAM,IAAI,IAAI;AAClC,MAAI,CAAC,OACH,QAAO;EAGT,MAAM,QAAQ,OAAO,QAAQ,MAAM;AACnC,MAAI,UAAU,GACZ,QAAO;AAGT,SAAO,OAAO,OAAO,EAAE;AACvB,QAAKD,KAAM,OACT,MAAKA,KAAM,WACR,SAAS,KAAK,OAAO,OAAO,KAAK,OAAO,MAC1C,EACD,EACD;AACD,SAAO;;;;;CAMT,AAAO,UAA6C,KAAc;AAChE,MAAI,KAAK,SAAS,EAChB;AAGF,QAAKA,OAAQ,MAAKA,KAAM,QAAQ,SAAS,KAAK,OAAO,IAAI;AACzD,QAAKC,KAAM,OAAO,IAAI;;CAGxB,IAAI,OAAe;AACjB,SAAO,MAAKD,KAAM;;CAGpB,AAAO,QAAc;AACnB,MAAI,KAAK,SAAS,EAChB;AAGF,QAAKA,KAAM,SAAS;AACpB,QAAKC,KAAM,OAAO;;CAGpB,UACE,KACA,QACM;AACN,SAAO,MAAKA,KAAM,IAAI,IAAI,IAAI,MAAKA,KAAM,IAAI,KAAK,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/rettime/package.json b/node_modules/rettime/package.json new file mode 100644 index 0000000000000000000000000000000000000000..1549cfa1dc9ca30ad1b72914a7213da25c9f3a25 --- /dev/null +++ b/node_modules/rettime/package.json @@ -0,0 +1,50 @@ +{ + "type": "module", + "name": "rettime", + "version": "0.11.11", + "description": "A type-safe marriage of `EventTarget` and `EventEmitter`.", + "main": "./build/index.mjs", + "types": "./build/index.d.mts", + "files": [ + "build", + "src" + ], + "imports": { + "#src/*": "./src/*" + }, + "exports": { + ".": { + "types": "./build/index.d.mts", + "default": "./build/index.mjs" + } + }, + "keywords": [ + "emitter", + "event", + "dispatcher", + "type-safe", + "strict", + "event-target" + ], + "author": "Artem Zakharchenko ", + "license": "MIT", + "repository": { + "url": "https://github.com/kettanaito/rettime" + }, + "devDependencies": { + "@ossjs/release": "^0.10.1", + "@rolldown/binding-darwin-arm64": "1.0.0-rc.9", + "publint": "^0.3.18", + "tsdown": "^0.19.0", + "typescript": "^5.9.3", + "vitest": "^3.2.4" + }, + "scripts": { + "dev": "tsdown -w", + "test": "vitest", + "benchmark": "vitest bench", + "build": "tsdown", + "lint": "publint", + "release": "release publish" + } +} \ No newline at end of file diff --git a/node_modules/rettime/src/index.ts b/node_modules/rettime/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..3e85e72cec0b59216d683cdeccea67874ff4838d --- /dev/null +++ b/node_modules/rettime/src/index.ts @@ -0,0 +1,889 @@ +import { LensList } from './lens-list' + +export type DefaultEventMap = { + [eventType: string]: TypedEvent +} + +/** + * Reserved event map containing special event types like '*' for catch-all listeners. + */ +export type ReservedEventMap = { + '*': TypedEvent +} + +type IsReservedEvent = Type extends keyof ReservedEventMap + ? true + : false + +export interface TypedEvent< + DataType = void, + ReturnType = void, + EventType extends string = string, +> extends Omit, 'type'> { + type: EventType +} + +const kDefaultPrevented = Symbol('kDefaultPrevented') +const kPropagationStopped = Symbol('kPropagationStopped') +const kImmediatePropagationStopped = Symbol('kImmediatePropagationStopped') + +export class TypedEvent< + DataType = void, + ReturnType = void, + EventType extends string = string, +> + extends MessageEvent + implements TypedEvent +{ + /** + * @note Keep a placeholder property with the return type + * because the type must be set somewhere in order to be + * correctly associated and inferred from the event. + */ + #returnType: ReturnType; + + [kDefaultPrevented]: boolean; + [kPropagationStopped]?: Emitter; + [kImmediatePropagationStopped]?: boolean + + constructor( + ...args: [DataType] extends [void] + ? [type: EventType] + : [type: EventType, init: { data: DataType }] + ) { + super(args[0], args[1]) + this[kDefaultPrevented] = false + } + + get defaultPrevented(): boolean { + return this[kDefaultPrevented] + } + + public preventDefault(): void { + super.preventDefault() + this[kDefaultPrevented] = true + } + + public stopImmediatePropagation(): void { + /** + * @note Despite `.stopPropagation()` and `.stopImmediatePropagation()` being defined + * in Node.js, they do nothing. It is safe to re-define them. + */ + super.stopImmediatePropagation() + this[kImmediatePropagationStopped] = true + } +} + +/** + * Brands a TypedEvent or its subclass while preserving its (narrower) type. + */ +type Brand< + Event extends TypedEvent, + EventType extends string, + Loose extends boolean = false, +> = Loose extends true + ? Event extends TypedEvent + ? /** + * @note Omit the `ReturnType` so emit methods can accept type events + * where infering the return type is impossible. + */ + TypedEvent & { + type: EventType + } + : never + : Event & { type: EventType } + +type InferEventMap> = + Target extends Emitter ? WithReservedEvents : never + +/** + * Extracts only user-defined events, excluding reserved event types. + */ +type UserEventMap = Omit< + EventMap, + keyof ReservedEventMap +> + +/** + * Decorates the given `EventMap` with the reserved emitter events (e.g. `*`). + */ +export type WithReservedEvents = EventMap & + ReservedEventMap + +/** + * Creates a union of all events in the EventMap with their literal type strings. + */ +type AllEvents = { + [K in keyof EventMap & string]: Brand +}[keyof EventMap & string] + +export type TypedListenerOptions = { + once?: boolean + signal?: AbortSignal +} + +export interface HookListenerOptions extends TypedListenerOptions { + persist?: boolean +} + +export type EmitterHookMap = { + newListener: ( + type: keyof WithReservedEvents & string, + listener: { + [K in keyof WithReservedEvents & string]: Emitter.Listener< + Emitter, + K, + WithReservedEvents + > + }[keyof WithReservedEvents & string], + options: HookListenerOptions | undefined, + ) => void + + removeListener: ( + type: keyof WithReservedEvents & string, + listener: { + [K in keyof WithReservedEvents & string]: Emitter.Listener< + Emitter, + K, + WithReservedEvents + > + }[keyof WithReservedEvents & string], + options: HookListenerOptions | undefined, + ) => void + + beforeEmit: (event: EventMap[keyof EventMap & string]) => boolean | void +} + +export namespace Emitter { + /** + * Returns a union of all event types, both public and reserved, for the given emitter. + * + * @example + * const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>() + * type AllEventTypes = Emitter.AllEventTypes + * // "*" | "greeting" | "handshake" + */ + export type AllEventTypes< + Target extends Emitter, + EventMap extends DefaultEventMap = InferEventMap, + > = string extends keyof EventMap ? never : keyof EventMap & string + + /** + * Returns a union of all public event types for the given emitter. + * + * @example + * const emitter = new Emitter<{ greeting: TypedEvent, handshake: TypedEvent }>() + * type EventTypes = Emitter.EventTypes + * // "greeting" | "handshake" + */ + export type PublicEventTypes< + Target extends Emitter, + EventMap extends DefaultEventMap = InferEventMap, + UserEvents extends UserEventMap = UserEventMap, + > = string extends keyof UserEvents ? never : keyof UserEvents & string + + /** + * Returns a union of all public event type for the given emitter. + * + * @example + * const emitter = new Emitter<{ greeting: GreetingEvent, handshake: HandshakeEvent }>() + * type Events = Emitter.Events + * // GreetingEvent | HandshakeEvent + */ + export type Events< + Target extends Emitter, + EventMap extends DefaultEventMap = InferEventMap, + > = string extends keyof UserEventMap + ? never + : UserEventMap[keyof UserEventMap] + + /** + * Returns an appropriate `Event` type for the given event type. + * + * @example + * const emitter = new Emitter<{ greeting: TypedEvent }>() + * type GreetingEvent = Emitter.Event + * // TypedEvent + */ + export type Event< + Target extends Emitter, + EventType extends keyof EventMap & string, + EventMap extends DefaultEventMap = InferEventMap, + > = + IsReservedEvent extends true + ? AllEvents> + : Brand + + /** + * Returns an appropriate event data type for the given event type. + * + * @example + * const emitter = new Emitter<{ greeting: TypedEvent<'hello'> }>() + * type GreetingData = Emitter.EventData + * // "hello" + */ + export type EventData< + Target extends Emitter, + EventType extends keyof EventMap & string, + EventMap extends DefaultEventMap = InferEventMap, + > = EventMap[EventType] extends TypedEvent ? DataType : never + + /** + * Returns the listener type for the given event type. + * + * @example + * const emitter = new Emitter<{ getTotalPrice: TypedEvent }>() + * type Listener = Emitter.ListenerType + * // (event: TypedEvent) => number + */ + export type Listener< + Target extends Emitter, + EventType extends keyof EventMap & string, + EventMap extends DefaultEventMap = InferEventMap, + > = + IsReservedEvent extends true + ? (event: Emitter.Event) => void + : ( + event: Emitter.Event, + ) => Emitter.ListenerReturnType extends [ + void, + ] + ? void + : Emitter.ListenerReturnType + + /** + * Returns the return type of the listener for the given event type. + * + * @example + * const emitter = new Emitter<{ getTotalPrice: TypedEvent }>() + * type ListenerReturnType = Emitter.ListenerReturnType + * // number + */ + export type ListenerReturnType< + Target extends Emitter, + EventType extends keyof EventMap & string, + EventMap extends DefaultEventMap = InferEventMap, + > = + IsReservedEvent extends true + ? void + : EventMap[EventType] extends TypedEvent + ? ReturnType + : never +} + +export namespace EventMap { + /** + * Returns a union of all public event types from the given event map. + * + * @example + * type MyEventMap = { greeting: TypedEvent, handshake: TypedEvent } + * type EventTypes = EventMap.EventTypes + * // "greeting" | "handshake" + */ + export type EventTypes = + Emitter.PublicEventTypes> + + /** + * Returns a union of all public event type from the given event map. + * + * @example + * type MyEventMap = { greeting: GreetingEvent, handshake: HandshakeEvent } + * type Events = EventMap.Events + * // GreetingEvent | HandshakeEvent + */ + export type Events = Emitter.Events> + + /** + * Returns an appropriate `Event` type for the given event type. + * + * @example + * type MyEventMap = { greeting: TypedEvent } + * type GreetingEvent = EventMap.Event + * // TypedEvent + */ + export type Event< + Map extends DefaultEventMap, + Type extends keyof WithReservedEvents & string, + > = Emitter.Event, Type, WithReservedEvents> + + /** + * Returns an appropriate event data type for the given event type. + * + * @example + * type MyEventMap = { greeting: TypedEvent<'hello'> } + * type GreetingData = EventMap.EventData + * // "hello" + */ + export type EventData< + Map extends DefaultEventMap, + Type extends keyof WithReservedEvents & string, + > = Emitter.EventData, Type, WithReservedEvents> + + /** + * Returns the listener type for the given event type. + * + * @example + * type MyEventMap = { getTotalPrice: TypedEvent }> + * type Listener = EventMap.Listener + * // (event: TypedEvent) => number + */ + export type Listener< + Map extends DefaultEventMap, + Type extends keyof WithReservedEvents & string, + > = Emitter.Listener, Type, WithReservedEvents> + + /** + * Returns the return type of the listener for the given event type. + * + * @example + * type MyEventMap = { getTotalPrice: TypedEvent } + * type ListenerReturnType = EventMap.ListenerReturnType + * // number + */ + export type ListenerReturnType< + Map extends DefaultEventMap, + Type extends keyof WithReservedEvents & string, + > = Emitter.ListenerReturnType, Type, WithReservedEvents> +} + +export class Emitter { + #listeners: LensList< + Record< + string, + Emitter.Listener< + typeof this, + keyof WithReservedEvents & string, + WithReservedEvents + > + > + > + + #listenerOptions: WeakMap + #listenerAbortCleanups: WeakMap void> + #typelessListeners: WeakSet + + #hookListeners: LensList> + #hookListenerOptions: WeakMap + #hookListenerAbortCleanups: WeakMap void> + + public readonly hooks: { + on>( + type: HookType, + callback: EmitterHookMap[HookType], + options?: HookListenerOptions, + ): void + + removeListener>( + type: HookType, + callback: EmitterHookMap[HookType], + options?: HookListenerOptions, + ): void + } + + constructor() { + this.#listeners = new LensList() + this.#listenerOptions = new WeakMap() + this.#listenerAbortCleanups = new WeakMap() + this.#typelessListeners = new WeakSet() + this.#hookListeners = new LensList() + this.#hookListenerOptions = new WeakMap() + this.#hookListenerAbortCleanups = new WeakMap() + + this.hooks = { + on: (hook, callback, options) => { + /** + * @note An already-aborted signal would never fire its 'abort' event, + * leaving the hook registered indefinitely. Skip registration entirely. + */ + if (options?.signal?.aborted) { + return + } + + if (options?.once) { + const original = callback as (...args: Array) => void + const wrapper = ((...args: Array) => { + this.#deleteHookListener(hook, wrapper) + return original(...args) + }) as typeof callback + callback = wrapper + } + + this.#hookListeners.append(hook, callback) + + if (options) { + this.#hookListenerOptions.set(callback, options) + } + + if (options?.signal) { + const { signal } = options + const onAbort = () => { + this.#deleteHookListener(hook, callback) + } + signal.addEventListener('abort', onAbort, { once: true }) + this.#hookListenerAbortCleanups.set(callback, () => { + signal.removeEventListener('abort', onAbort) + }) + } + }, + removeListener: (hook, callback) => { + this.#deleteHookListener(hook, callback) + }, + } + } + + #deleteHookListener>( + hook: HookType, + callback: EmitterHookMap[HookType], + ): void { + this.#hookListeners.delete(hook, callback) + const cleanup = this.#hookListenerAbortCleanups.get(callback) + if (cleanup) { + cleanup() + this.#hookListenerAbortCleanups.delete(callback) + } + } + + #deleteListener< + EventType extends keyof WithReservedEvents & string, + >( + type: EventType, + listener: Emitter.Listener< + typeof this, + EventType, + WithReservedEvents + >, + ): boolean { + const removed = this.#listeners.delete(type, listener) + const cleanup = this.#listenerAbortCleanups.get(listener) + if (cleanup) { + cleanup() + this.#listenerAbortCleanups.delete(listener) + } + return removed + } + + /** + * Adds a listener for the given event type. + */ + public on & string>( + type: EventType, + listener: Emitter.Listener< + typeof this, + EventType, + WithReservedEvents + >, + options?: TypedListenerOptions, + ): typeof this { + this.#addListener(type, listener, options) + return this + } + + /** + * Adds a one-time listener for the given event type. + */ + public once & string>( + type: EventType, + listener: Emitter.Listener< + typeof this, + EventType, + WithReservedEvents + >, + options?: Omit, + ): typeof this { + return this.on(type, listener, { + ...(options || {}), + once: true, + }) + } + + /** + * Prepends a listener for the given event type. + */ + public earlyOn & string>( + type: EventType, + listener: Emitter.Listener< + typeof this, + EventType, + WithReservedEvents + >, + options?: TypedListenerOptions, + ): typeof this { + this.#addListener(type, listener, options, 'prepend') + return this + } + + /** + * Prepends a one-time listener for the given event type. + */ + public earlyOnce< + EventType extends keyof WithReservedEvents & string, + >( + type: EventType, + listener: Emitter.Listener< + typeof this, + EventType, + WithReservedEvents + >, + options?: Omit, + ): typeof this { + return this.earlyOn(type, listener, { + ...(options || {}), + once: true, + }) + } + + /** + * Emits the given typed event. + * + * @returns {boolean} Returns `true` if the event had any listeners, `false` otherwise. + */ + public emit( + event: Brand, + ): boolean { + if (this.#listeners.size === 0) { + return false + } + + /** + * @note Calculate matching listeners before calling them + * since one-time listeners will self-destruct. + */ + const hasListeners = this.listenerCount(event.type) > 0 + + const proxiedEvent = this.#proxyEvent(event) + + for (const listener of this.#matchListeners(event.type)) { + if ( + proxiedEvent.event[kPropagationStopped] != null && + proxiedEvent.event[kPropagationStopped] !== this + ) { + proxiedEvent.revoke() + return false + } + + if (proxiedEvent.event[kImmediatePropagationStopped]) { + break + } + + this.#callListener(proxiedEvent.event, listener) + } + + proxiedEvent.revoke() + + return hasListeners + } + + /** + * Emits the given typed event and returns a promise that resolves + * when all the listeners for that event have settled. + * + * @returns {Promise>} A promise that resolves + * with the return values of all listeners. + */ + public async emitAsPromise( + event: Brand, + ): Promise< + Array> + > { + if (this.#listeners.size === 0) { + return [] + } + + const pendingListeners: Array< + Promise> + > = [] + + const proxiedEvent = this.#proxyEvent(event) + + for (const listener of this.#matchListeners(event.type)) { + if ( + proxiedEvent.event[kPropagationStopped] != null && + proxiedEvent.event[kPropagationStopped] !== this + ) { + proxiedEvent.revoke() + return [] + } + + if (proxiedEvent.event[kImmediatePropagationStopped]) { + break + } + + const listenerPromise = Promise.resolve( + this.#callListener(proxiedEvent.event, listener), + ) + + const returnValue = await listenerPromise + + if (!this.#isTypelessListener(listener)) { + pendingListeners.push(returnValue) + } + } + + proxiedEvent.revoke() + + return Promise.allSettled(pendingListeners).then((results) => { + return results.map((result) => + result.status === 'fulfilled' ? result.value : result.reason, + ) + }) + } + + /** + * Emits the given event and returns a generator that yields + * the result of each listener in the order of their registration. + * This way, you stop exhausting the listeners once you get the expected value. + */ + public *emitAsGenerator( + event: Brand, + ): Generator> { + if (this.#listeners.size === 0) { + return + } + + const proxiedEvent = this.#proxyEvent(event) + + for (const listener of this.#matchListeners(event.type)) { + if ( + proxiedEvent.event[kPropagationStopped] != null && + proxiedEvent.event[kPropagationStopped] !== this + ) { + proxiedEvent.revoke() + return + } + + if (proxiedEvent.event[kImmediatePropagationStopped]) { + break + } + + const returnValue = this.#callListener(proxiedEvent.event, listener) + + if (!this.#isTypelessListener(listener)) { + yield returnValue + } + } + + proxiedEvent.revoke() + } + + /** + * Removes a listener for the given event type. + */ + public removeListener< + EventType extends keyof WithReservedEvents & string, + >( + type: EventType, + listener: Emitter.Listener< + typeof this, + EventType, + WithReservedEvents + >, + ): void { + const options = this.#listenerOptions.get(listener) + + if (!this.#deleteListener(type, listener)) { + return + } + + /** + * @note Snapshot the hook list before iterating so a hook that removes + * another `removeListener` hook can't shift the live array mid-iteration. + */ + for (const hook of this.#hookListeners.get('removeListener').slice()) { + hook( + type, + listener as Parameters['removeListener']>[1], + options, + ) + } + } + + /** + * Removes all listeners for the given event type. + * If no event type is provided, removes all existing listeners. + */ + public removeAllListeners< + EventType extends keyof WithReservedEvents & string, + >(type?: EventType): void { + if (type == null) { + for (const [listenerType, listeners] of this.#listeners.entries()) { + while (listeners.length > 0) { + this.removeListener( + listenerType as keyof WithReservedEvents & string, + listeners[0], + ) + } + } + + for (const [hookType, hookListener] of [...this.#hookListeners]) { + if (!this.#hookListenerOptions.get(hookListener)?.persist) { + this.#deleteHookListener( + hookType as keyof EmitterHookMap, + hookListener as EmitterHookMap[keyof EmitterHookMap], + ) + } + } + + return + } + + const listeners = this.listeners(type) + + while (listeners.length > 0) { + this.removeListener(type, listeners[0]) + } + } + + /** + * Returns the list of listeners for the given event type. + * If no even type is provided, returns all listeners. + */ + public listeners< + EventType extends keyof WithReservedEvents & string, + >( + type?: EventType, + ): Array< + Emitter.Listener> + > { + if (type == null) { + return this.#listeners.getAll() + } + + return this.#listeners.get(type) + } + + /** + * Returns the number of listeners for the given event type. + * If no even type is provided, returns the total number of listeners. + */ + public listenerCount< + EventType extends keyof WithReservedEvents & string, + >(type?: EventType): number { + if (type == null) { + return this.#listeners.size + } + + return this.listeners(type).length + } + + #addListener & string>( + type: EventType, + listener: Emitter.Listener< + typeof this, + EventType, + WithReservedEvents + >, + options: TypedListenerOptions | undefined, + insertMode: 'append' | 'prepend' = 'append', + ): void { + /** + * @note An already-aborted signal would never fire its 'abort' event, + * leaving the listener registered indefinitely. Skip registration entirely. + */ + if (options?.signal?.aborted) { + return + } + + for (const hook of this.#hookListeners.get('newListener').slice()) { + hook( + type, + listener as Parameters['newListener']>[1], + options, + ) + } + + if (type === '*') { + this.#typelessListeners.add(listener) + } + + if (insertMode === 'prepend') { + this.#listeners.prepend(type, listener) + } else { + this.#listeners.append(type, listener) + } + + if (options) { + this.#listenerOptions.set(listener, options) + + if (options.signal) { + const { signal } = options + const onAbort = () => { + this.removeListener(type, listener) + } + signal.addEventListener('abort', onAbort, { once: true }) + this.#listenerAbortCleanups.set(listener, () => { + signal.removeEventListener('abort', onAbort) + }) + } + } + } + + #proxyEvent( + event: Event, + ): { event: Event; revoke: () => void } { + const { stopPropagation } = event + + event.stopPropagation = () => { + event[kPropagationStopped] = this + stopPropagation.call(event) + } + + return { + event, + revoke() { + event.stopPropagation = stopPropagation + }, + } + } + + #callListener(event: Event, listener: (event: any) => any) { + for (const hook of this.#hookListeners.get('beforeEmit').slice()) { + if (hook(event as EventMap[keyof EventMap & string]) === false) { + return + } + } + + const returnValue = listener.call(this, event) + + const options = this.#listenerOptions.get(listener) + + if (options?.once) { + const type = this.#isTypelessListener(listener) ? '*' : event.type + + if (this.#deleteListener(type, listener)) { + for (const hook of this.#hookListeners.get('removeListener').slice()) { + hook(type, listener, options) + } + } + } + + return returnValue + } + + /** + * Return a list of all event listeners relevant for the given event type. + * This includes the explicit event listeners and also typeless event listeners. + * + * @note Snapshot the matching listeners before yielding. Listeners can add or + * remove other listeners during emission (e.g. `earlyOn` unshifts `#list`), + * which would otherwise shift the live iterator and re-yield prior entries. + */ + *#matchListeners(type: EventType) { + const snapshot: Array< + Emitter.Listener< + typeof this, + keyof WithReservedEvents & string, + WithReservedEvents + > + > = [] + for (const [key, listener] of this.#listeners) { + if (key === '*' || key === type) { + snapshot.push(listener) + } + } + yield* snapshot + } + + #isTypelessListener(listener: any): boolean { + return this.#typelessListeners.has(listener) + } +} diff --git a/node_modules/rettime/src/lens-list.ts b/node_modules/rettime/src/lens-list.ts new file mode 100644 index 0000000000000000000000000000000000000000..24a674eed47e435ea5470a59dfd69bc5acabeb8e --- /dev/null +++ b/node_modules/rettime/src/lens-list.ts @@ -0,0 +1,120 @@ +type Values = M[keyof M & string] + +export class LensList> { + #list: Array<[string, Values]> + #lens: Map>> + + constructor() { + this.#list = [] + this.#lens = new Map() + } + + get [Symbol.iterator]() { + // Return the list's iterator so iteration is order-sensitive. + return this.#list[Symbol.iterator].bind(this.#list) + } + + public entries() { + return this.#lens.entries() + } + + /** + * Return an order-sensitive list of values by the given key. + */ + public get(key: K): Array { + return (this.#lens.get(key) || []) as Array + } + + /** + * Return an order-sensitive list of all values. + */ + public getAll(): Array> { + return this.#list.map(([, value]) => value) + } + + /** + * Append a new value to the given key. + */ + public append( + key: K, + value: ValueMap[K], + ): void { + this.#list.push([key, value]) + this.#openLens(key, (list) => list.push(value)) + } + + /** + * Prepend a new value to the given key. + */ + public prepend( + key: K, + value: ValueMap[K], + ): void { + this.#list.unshift([key, value]) + this.#openLens(key, (list) => list.unshift(value)) + } + + /** + * Delete the value belonging to the given key. + * Returns `true` if the value was present and removed, `false` otherwise. + */ + public delete( + key: K, + value: ValueMap[K], + ): boolean { + if (this.size === 0) { + return false + } + + const values = this.#lens.get(key) + if (!values) { + return false + } + + const index = values.indexOf(value) + if (index === -1) { + return false + } + + values.splice(index, 1) + this.#list.splice( + this.#list.findIndex( + (item) => item[0] === key && item[1] === value, + ), + 1, + ) + return true + } + + /** + * Delete all values belogning to the given key. + */ + public deleteAll(key: K): void { + if (this.size === 0) { + return + } + + this.#list = this.#list.filter((item) => item[0] !== key) + this.#lens.delete(key) + } + + get size(): number { + return this.#list.length + } + + public clear(): void { + if (this.size === 0) { + return + } + + this.#list.length = 0 + this.#lens.clear() + } + + #openLens( + key: string, + setter: (target: Array>) => void, + ): void { + setter(this.#lens.get(key) || this.#lens.set(key, []).get(key)) + } +} diff --git a/node_modules/reusify/.github/dependabot.yml b/node_modules/reusify/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..4872c5afd204d6c4ebd8361f14a4fb99390ef2f3 --- /dev/null +++ b/node_modules/reusify/.github/dependabot.yml @@ -0,0 +1,7 @@ +version: 2 +updates: +- package-ecosystem: npm + directory: "/" + schedule: + interval: daily + open-pull-requests-limit: 10 diff --git a/node_modules/reusify/.github/workflows/ci.yml b/node_modules/reusify/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..1e30ad806298004255f98694d61c683d9f7446a0 --- /dev/null +++ b/node_modules/reusify/.github/workflows/ci.yml @@ -0,0 +1,96 @@ +name: ci + +on: [push, pull_request] + +jobs: + legacy: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: ['0.10', '0.12', 4.x, 6.x, 8.x, 10.x, 12.x, 13.x, 14.x, 15.x, 16.x] + + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + - name: Install + run: | + npm install --production && npm install tape + + - name: Run tests + run: | + npm run test + + test: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [18.x, 20.x, 22.x] + + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + - name: Install + run: | + npm install + + - name: Run tests + run: | + npm run test:coverage + + types: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Install + run: | + npm install + + - name: Run types tests + run: | + npm run test:typescript + + lint: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Install + run: | + npm install + + - name: Lint + run: | + npm run lint diff --git a/node_modules/reusify/LICENSE b/node_modules/reusify/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..56d1590db316d670e9f5fa9ac46584dcc133845e --- /dev/null +++ b/node_modules/reusify/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015-2024 Matteo Collina + +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. + diff --git a/node_modules/reusify/README.md b/node_modules/reusify/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1aaee5d968c6b2071b8f5e7e19aa3c57b42ff700 --- /dev/null +++ b/node_modules/reusify/README.md @@ -0,0 +1,139 @@ +# reusify + +[![npm version][npm-badge]][npm-url] + +Reuse your objects and functions for maximum speed. This technique will +make any function run ~10% faster. You call your functions a +lot, and it adds up quickly in hot code paths. + +``` +$ node benchmarks/createNoCodeFunction.js +Total time 53133 +Total iterations 100000000 +Iteration/s 1882069.5236482036 + +$ node benchmarks/reuseNoCodeFunction.js +Total time 50617 +Total iterations 100000000 +Iteration/s 1975620.838848608 +``` + +The above benchmark uses fibonacci to simulate a real high-cpu load. +The actual numbers might differ for your use case, but the difference +should not. + +The benchmark was taken using Node v6.10.0. + +This library was extracted from +[fastparallel](http://npm.im/fastparallel). + +## Example + +```js +var reusify = require('reusify') +var fib = require('reusify/benchmarks/fib') +var instance = reusify(MyObject) + +// get an object from the cache, +// or creates a new one when cache is empty +var obj = instance.get() + +// set the state +obj.num = 100 +obj.func() + +// reset the state. +// if the state contains any external object +// do not use delete operator (it is slow) +// prefer set them to null +obj.num = 0 + +// store an object in the cache +instance.release(obj) + +function MyObject () { + // you need to define this property + // so V8 can compile MyObject into an + // hidden class + this.next = null + this.num = 0 + + var that = this + + // this function is never reallocated, + // so it can be optimized by V8 + this.func = function () { + if (null) { + // do nothing + } else { + // calculates fibonacci + fib(that.num) + } + } +} +``` + +The above example was intended for synchronous code, let's see async: +```js +var reusify = require('reusify') +var instance = reusify(MyObject) + +for (var i = 0; i < 100; i++) { + getData(i, console.log) +} + +function getData (value, cb) { + var obj = instance.get() + + obj.value = value + obj.cb = cb + obj.run() +} + +function MyObject () { + this.next = null + this.value = null + + var that = this + + this.run = function () { + asyncOperation(that.value, that.handle) + } + + this.handle = function (err, result) { + that.cb(err, result) + that.value = null + that.cb = null + instance.release(that) + } +} +``` + +Also note how in the above examples, the code, that consumes an instance of `MyObject`, +reset the state to initial condition, just before storing it in the cache. +That's needed so that every subsequent request for an instance from the cache, +could get a clean instance. + +## Why + +It is faster because V8 doesn't have to collect all the functions you +create. On a short-lived benchmark, it is as fast as creating the +nested function, but on a longer time frame it creates less +pressure on the garbage collector. + +## Other examples +If you want to see some complex example, checkout [middie](https://github.com/fastify/middie) and [steed](https://github.com/mcollina/steed). + +## Acknowledgements + +Thanks to [Trevor Norris](https://github.com/trevnorris) for +getting me down the rabbit hole of performance, and thanks to [Mathias +Buss](http://github.com/mafintosh) for suggesting me to share this +trick. + +## License + +MIT + +[npm-badge]: https://badge.fury.io/js/reusify.svg +[npm-url]: https://badge.fury.io/js/reusify diff --git a/node_modules/reusify/SECURITY.md b/node_modules/reusify/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..dd9f1d510216450b9311a3b30815fdf381baa787 --- /dev/null +++ b/node_modules/reusify/SECURITY.md @@ -0,0 +1,15 @@ +# Security Policy + +## Supported Versions + +Use this section to tell people about which versions of your project are +currently being supported with security updates. + +| Version | Supported | +| ------- | ------------------ | +| 1.x | :white_check_mark: | +| < 1.0 | :x: | + +## Reporting a Vulnerability + +Please report all vulnerabilities at [https://github.com/mcollina/fastq/security](https://github.com/mcollina/fastq/security). diff --git a/node_modules/reusify/benchmarks/createNoCodeFunction.js b/node_modules/reusify/benchmarks/createNoCodeFunction.js new file mode 100644 index 0000000000000000000000000000000000000000..ce1aac7b7a6968b0377eac9c4fd9dcc4836a8bac --- /dev/null +++ b/node_modules/reusify/benchmarks/createNoCodeFunction.js @@ -0,0 +1,30 @@ +'use strict' + +var fib = require('./fib') +var max = 100000000 +var start = Date.now() + +// create a funcion with the typical error +// pattern, that delegates the heavy load +// to something else +function createNoCodeFunction () { + /* eslint no-constant-condition: "off" */ + var num = 100 + + ;(function () { + if (null) { + // do nothing + } else { + fib(num) + } + })() +} + +for (var i = 0; i < max; i++) { + createNoCodeFunction() +} + +var time = Date.now() - start +console.log('Total time', time) +console.log('Total iterations', max) +console.log('Iteration/s', max / time * 1000) diff --git a/node_modules/reusify/benchmarks/fib.js b/node_modules/reusify/benchmarks/fib.js new file mode 100644 index 0000000000000000000000000000000000000000..e22cc48dec9efa13644385c395272f16a9e45462 --- /dev/null +++ b/node_modules/reusify/benchmarks/fib.js @@ -0,0 +1,13 @@ +'use strict' + +function fib (num) { + var fib = [] + + fib[0] = 0 + fib[1] = 1 + for (var i = 2; i <= num; i++) { + fib[i] = fib[i - 2] + fib[i - 1] + } +} + +module.exports = fib diff --git a/node_modules/reusify/benchmarks/reuseNoCodeFunction.js b/node_modules/reusify/benchmarks/reuseNoCodeFunction.js new file mode 100644 index 0000000000000000000000000000000000000000..3358d6e50d8ffbf1ce1559213ba63ffc50c5f752 --- /dev/null +++ b/node_modules/reusify/benchmarks/reuseNoCodeFunction.js @@ -0,0 +1,38 @@ +'use strict' + +var reusify = require('../') +var fib = require('./fib') +var instance = reusify(MyObject) +var max = 100000000 +var start = Date.now() + +function reuseNoCodeFunction () { + var obj = instance.get() + obj.num = 100 + obj.func() + obj.num = 0 + instance.release(obj) +} + +function MyObject () { + this.next = null + var that = this + this.num = 0 + this.func = function () { + /* eslint no-constant-condition: "off" */ + if (null) { + // do nothing + } else { + fib(that.num) + } + } +} + +for (var i = 0; i < max; i++) { + reuseNoCodeFunction() +} + +var time = Date.now() - start +console.log('Total time', time) +console.log('Total iterations', max) +console.log('Iteration/s', max / time * 1000) diff --git a/node_modules/reusify/eslint.config.js b/node_modules/reusify/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..d0a9af62bf268261a317a0a211d63a9dde85dda3 --- /dev/null +++ b/node_modules/reusify/eslint.config.js @@ -0,0 +1,14 @@ +'use strict' + +const base = require('neostandard')({}) + +module.exports = [ + ...base, + { + name: 'old-standard', + rules: { + 'no-var': 'off', + 'object-shorthand': 'off', + } + } +] diff --git a/node_modules/reusify/package.json b/node_modules/reusify/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e47ff11c3dbe87dc397ffce3c0abfcaca5056c68 --- /dev/null +++ b/node_modules/reusify/package.json @@ -0,0 +1,50 @@ +{ + "name": "reusify", + "version": "1.1.0", + "description": "Reuse objects and functions with style", + "main": "reusify.js", + "types": "reusify.d.ts", + "scripts": { + "lint": "eslint", + "test": "tape test.js", + "test:coverage": "c8 --100 tape test.js", + "test:typescript": "tsc" + }, + "pre-commit": [ + "lint", + "test", + "test:typescript" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/mcollina/reusify.git" + }, + "keywords": [ + "reuse", + "object", + "performance", + "function", + "fast" + ], + "author": "Matteo Collina ", + "license": "MIT", + "bugs": { + "url": "https://github.com/mcollina/reusify/issues" + }, + "homepage": "https://github.com/mcollina/reusify#readme", + "engines": { + "node": ">=0.10.0", + "iojs": ">=1.0.0" + }, + "devDependencies": { + "@types/node": "^22.9.0", + "eslint": "^9.13.0", + "neostandard": "^0.12.0", + "pre-commit": "^1.2.2", + "tape": "^5.0.0", + "c8": "^10.1.2", + "typescript": "^5.2.2" + }, + "dependencies": { + } +} diff --git a/node_modules/reusify/reusify.d.ts b/node_modules/reusify/reusify.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9ba277ddde66cd367c0fd7a5594faf3a3340a3b1 --- /dev/null +++ b/node_modules/reusify/reusify.d.ts @@ -0,0 +1,14 @@ +interface Node { + next: Node | null; +} + +interface Constructor { + new(): T; +} + +declare function reusify(constructor: Constructor): { + get(): T; + release(node: T): void; +}; + +export = reusify; diff --git a/node_modules/reusify/reusify.js b/node_modules/reusify/reusify.js new file mode 100644 index 0000000000000000000000000000000000000000..e6f36f3a83688ef6945cc9f7624c4e37539bd132 --- /dev/null +++ b/node_modules/reusify/reusify.js @@ -0,0 +1,33 @@ +'use strict' + +function reusify (Constructor) { + var head = new Constructor() + var tail = head + + function get () { + var current = head + + if (current.next) { + head = current.next + } else { + head = new Constructor() + tail = head + } + + current.next = null + + return current + } + + function release (obj) { + tail.next = obj + tail = obj + } + + return { + get: get, + release: release + } +} + +module.exports = reusify diff --git a/node_modules/reusify/test.js b/node_modules/reusify/test.js new file mode 100644 index 0000000000000000000000000000000000000000..929cfd71980d81ea9899bddeb8551b0e881c460b --- /dev/null +++ b/node_modules/reusify/test.js @@ -0,0 +1,66 @@ +'use strict' + +var test = require('tape') +var reusify = require('./') + +test('reuse objects', function (t) { + t.plan(6) + + function MyObject () { + t.pass('constructor called') + this.next = null + } + + var instance = reusify(MyObject) + var obj = instance.get() + + t.notEqual(obj, instance.get(), 'two instance created') + t.notOk(obj.next, 'next must be null') + + instance.release(obj) + + // the internals keeps a hot copy ready for reuse + // putting this one back in the queue + instance.release(instance.get()) + + // comparing the old one with the one we got + // never do this in real code, after release you + // should never reuse that instance + t.equal(obj, instance.get(), 'instance must be reused') +}) + +test('reuse more than 2 objects', function (t) { + function MyObject () { + t.pass('constructor called') + this.next = null + } + + var instance = reusify(MyObject) + var obj = instance.get() + var obj2 = instance.get() + var obj3 = instance.get() + + t.notOk(obj.next, 'next must be null') + t.notOk(obj2.next, 'next must be null') + t.notOk(obj3.next, 'next must be null') + + t.notEqual(obj, obj2) + t.notEqual(obj, obj3) + t.notEqual(obj3, obj2) + + instance.release(obj) + instance.release(obj2) + instance.release(obj3) + + // skip one + instance.get() + + var obj4 = instance.get() + var obj5 = instance.get() + var obj6 = instance.get() + + t.equal(obj4, obj) + t.equal(obj5, obj2) + t.equal(obj6, obj3) + t.end() +}) diff --git a/node_modules/reusify/tsconfig.json b/node_modules/reusify/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..dbe862bb2718ae74e7f31b014f302f983aa248c7 --- /dev/null +++ b/node_modules/reusify/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "commonjs", + "noEmit": true, + "strict": true + }, + "files": [ + "./reusify.d.ts" + ] +} diff --git a/node_modules/robust-predicates/LICENSE b/node_modules/robust-predicates/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cf1ab25da0349f84a3fdd40032f0ce99db813b8b --- /dev/null +++ b/node_modules/robust-predicates/LICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +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 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. + +For more information, please refer to diff --git a/node_modules/robust-predicates/README.md b/node_modules/robust-predicates/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6c145038372d315d774ea8a8a3b13cec6b834135 --- /dev/null +++ b/node_modules/robust-predicates/README.md @@ -0,0 +1,82 @@ +# robust-predicates + +Fast robust predicates for computational geometry in JavaScript. Provides reliable 2D and 3D point orientation tests (`orient2d`, `orient3d`, `incircle`, `insphere`) that are not susceptible to floating point errors (without sacrificing performance). A modern port of [Jonathan R Shewchuk's C code](https://www.cs.cmu.edu/~quake/robust.html), an industry standard since 1996. + + + +_Figure: non-robust vs robust `orient2d` test for points within a tiny range (2-42)._ + +[![Build Status](https://travis-ci.com/mourner/robust-predicates.svg?branch=master)](https://travis-ci.com/mourner/robust-predicates) +[![Simply Awesome](https://img.shields.io/badge/simply-awesome-brightgreen.svg)](https://github.com/mourner/projects) +[![Browser Build](https://badgen.net/bundlephobia/minzip/robust-predicates)](https://unpkg.com/robust-predicates) + +## [Demo](https://observablehq.com/@mourner/non-robust-arithmetic-as-art) + +## API + +Note: unlike J. Shewchuk's original code, all the functions in this library assume `y` axis is oriented _downwards_ ↓, so the semantics are different. + +### `orient2d(ax,ay, bx,by, cx,cy)` + +- Returns a *positive* value if the points `a`, `b`, and `c` occur in _counterclockwise_ order (`c` lies to the left of the directed line defined by points `a` and `b`). +- Returns a *negative* value if they occur in _clockwise_ order (`c` lies to the right of the directed line `ab`). +- Returns *zero* if they are _collinear_. + +The result is also an approximation of twice the signed area of the triangle defined by the three points. + +### `incircle(ax,ay, bx,by, cx,cy, dx,dy)` + +- Returns a _positive_ value if the point `d` lies _outside_ the circle passing through `a`, `b`, and `c`. +- Returns a _negative_ value if it lies _inside_. +- Returns _zero_ if the four points are _cocircular_. + +The points `a`, `b`, and `c` must be in _counterclockwise_ order, or the sign of the result will be reversed. + +### `orient3d(ax,ay,az, bx,by,bz, cx,cy,cz, dx,dy,dz)` + +- Returns a _positive_ value if the point `d` lies _above_ the plane passing through `a`, `b`, and `c`, meaning that `a`, `b`, and `c` appear in counterclockwise order when viewed from `d`. +- Returns a _negative_ value if `d` lies _below_ the plane. +- Returns _zero_ if the points are _coplanar_. + +The result is also an approximation of six times the signed volume of the tetrahedron defined by the four points. + +### `insphere(ax,ay,az, bx,by,bz, cx,cy,cz, dx,dy,dz, ex,ey,ez)` + +- Returns a _positive_ value if the point `e` lies _outside_ the sphere passing through `a`, `b`, `c`, and `d`. +- Returns a _negative_ value if it lies _inside_. +- Returns _zero_ if the five points are _cospherical_. + +The points `a`, `b`, `c`, and `d` must be ordered so that they have a _positive orientation_ +(as defined by `orient3d`), or the sign of the result will be reversed. + +### `orient2dfast`, `orient3dfast`, `incirclefast`, `inspherefast` + +Simple, approximate, non-robust versions of predicates above. Use when robustness isn't needed. + +## Example + +```js +import {orient2d} from 'robust-predicates'; + +const ccw = orient2d(ax, ay, bx, by, cx, cy) > 0; +```` + +## Install + +Install with `npm install robust-predicates` or `yarn add robust-predicates`, or use one of the browser builds: + +- [predicates.min.js](https://unpkg.com/robust-predicates/umd/predicates.min.js) (all predicates) +- [orient2d.min.js](https://unpkg.com/robust-predicates/umd/orient2d.min.js) (`orient2d`, `orient2dfast`) +- [orient3d.min.js](https://unpkg.com/robust-predicates/umd/orient3d.min.js) (`orient3d`, `orient3dfast`) +- [incircle.min.js](https://unpkg.com/robust-predicates/umd/incircle.min.js) (`incircle`, `incirclefast`) +- [insphere.min.js](https://unpkg.com/robust-predicates/umd/insphere.min.js) (`insphere`, `inspherefast`) + +## Thanks + +This project is just a port — all the brilliant, hard work was done by [Jonathan Richard Shewchuk](https://people.eecs.berkeley.edu/~jrs/). + +The port was also inspired by [Mikola Lysenko](https://twitter.com/MikolaLysenko)'s excellent [Robust Arithmetic Notes](https://github.com/mikolalysenko/robust-arithmetic-notes) and related projects like [robust-orientation](https://github.com/mikolalysenko/robust-orientation) and [robust-in-sphere](https://github.com/mikolalysenko/robust-in-sphere). + +## License + +Since the original code is in the public domain, this project follows the same choice. See [Unlicense](https://unlicense.org). diff --git a/node_modules/robust-predicates/esm/incircle.js b/node_modules/robust-predicates/esm/incircle.js new file mode 100644 index 0000000000000000000000000000000000000000..77b7301c738c093ddfafa6bedf4bd1e7330a5b36 --- /dev/null +++ b/node_modules/robust-predicates/esm/incircle.js @@ -0,0 +1,765 @@ +import {epsilon, splitter, resulterrbound, estimate, vec, sum, sum_three, scale} from './util.js'; + +const iccerrboundA = (10 + 96 * epsilon) * epsilon; +const iccerrboundB = (4 + 48 * epsilon) * epsilon; +const iccerrboundC = (44 + 576 * epsilon) * epsilon * epsilon; + +const bc = vec(4); +const ca = vec(4); +const ab = vec(4); +const aa = vec(4); +const bb = vec(4); +const cc = vec(4); +const u = vec(4); +const v = vec(4); +const axtbc = vec(8); +const aytbc = vec(8); +const bxtca = vec(8); +const bytca = vec(8); +const cxtab = vec(8); +const cytab = vec(8); +const abt = vec(8); +const bct = vec(8); +const cat = vec(8); +const abtt = vec(4); +const bctt = vec(4); +const catt = vec(4); + +const _8 = vec(8); +const _16 = vec(16); +const _16b = vec(16); +const _16c = vec(16); +const _32 = vec(32); +const _32b = vec(32); +const _48 = vec(48); +const _64 = vec(64); + +let fin = vec(1152); +let fin2 = vec(1152); + +function finadd(finlen, a, alen) { + finlen = sum(finlen, fin, a, alen, fin2); + const tmp = fin; fin = fin2; fin2 = tmp; + return finlen; +} + +function incircleadapt(ax, ay, bx, by, cx, cy, dx, dy, permanent) { + let finlen; + let adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail; + let axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen; + let abtlen, bctlen, catlen; + let abttlen, bcttlen, cattlen; + let n1, n0; + + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + + s1 = bdx * cdy; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * bdy; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bc[2] = _j - (u3 - bvirt) + (_i - bvirt); + bc[3] = u3; + s1 = cdx * ady; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * cdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ca[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ca[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ca[2] = _j - (u3 - bvirt) + (_i - bvirt); + ca[3] = u3; + s1 = adx * bdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * ady; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ab[2] = _j - (u3 - bvirt) + (_i - bvirt); + ab[3] = u3; + + finlen = sum( + sum( + sum( + scale(scale(4, bc, adx, _8), _8, adx, _16), _16, + scale(scale(4, bc, ady, _8), _8, ady, _16b), _16b, _32), _32, + sum( + scale(scale(4, ca, bdx, _8), _8, bdx, _16), _16, + scale(scale(4, ca, bdy, _8), _8, bdy, _16b), _16b, _32b), _32b, _64), _64, + sum( + scale(scale(4, ab, cdx, _8), _8, cdx, _16), _16, + scale(scale(4, ab, cdy, _8), _8, cdy, _16b), _16b, _32), _32, fin); + + let det = estimate(finlen, fin); + let errbound = iccerrboundB * permanent; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - adx; + adxtail = ax - (adx + bvirt) + (bvirt - dx); + bvirt = ay - ady; + adytail = ay - (ady + bvirt) + (bvirt - dy); + bvirt = bx - bdx; + bdxtail = bx - (bdx + bvirt) + (bvirt - dx); + bvirt = by - bdy; + bdytail = by - (bdy + bvirt) + (bvirt - dy); + bvirt = cx - cdx; + cdxtail = cx - (cdx + bvirt) + (bvirt - dx); + bvirt = cy - cdy; + cdytail = cy - (cdy + bvirt) + (bvirt - dy); + if (adxtail === 0 && bdxtail === 0 && cdxtail === 0 && adytail === 0 && bdytail === 0 && cdytail === 0) { + return det; + } + + errbound = iccerrboundC * permanent + resulterrbound * Math.abs(det); + det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail) - (bdy * cdxtail + cdx * bdytail)) + + 2 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx)) + + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail) - (cdy * adxtail + adx * cdytail)) + + 2 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx)) + + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail) - (ady * bdxtail + bdx * adytail)) + + 2 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx)); + + if (det >= errbound || -det >= errbound) { + return det; + } + + if (bdxtail !== 0 || bdytail !== 0 || cdxtail !== 0 || cdytail !== 0) { + s1 = adx * adx; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo); + t1 = ady * ady; + c = splitter * ady; + ahi = c - (c - ady); + alo = ady - ahi; + t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo); + _i = s0 + t0; + bvirt = _i - s0; + aa[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + aa[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + aa[2] = _j - (u3 - bvirt) + (_i - bvirt); + aa[3] = u3; + } + if (cdxtail !== 0 || cdytail !== 0 || adxtail !== 0 || adytail !== 0) { + s1 = bdx * bdx; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo); + t1 = bdy * bdy; + c = splitter * bdy; + ahi = c - (c - bdy); + alo = bdy - ahi; + t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo); + _i = s0 + t0; + bvirt = _i - s0; + bb[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + bb[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + bb[2] = _j - (u3 - bvirt) + (_i - bvirt); + bb[3] = u3; + } + if (adxtail !== 0 || adytail !== 0 || bdxtail !== 0 || bdytail !== 0) { + s1 = cdx * cdx; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo); + t1 = cdy * cdy; + c = splitter * cdy; + ahi = c - (c - cdy); + alo = cdy - ahi; + t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo); + _i = s0 + t0; + bvirt = _i - s0; + cc[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + cc[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + cc[2] = _j - (u3 - bvirt) + (_i - bvirt); + cc[3] = u3; + } + + if (adxtail !== 0) { + axtbclen = scale(4, bc, adxtail, axtbc); + finlen = finadd(finlen, sum_three( + scale(axtbclen, axtbc, 2 * adx, _16), _16, + scale(scale(4, cc, adxtail, _8), _8, bdy, _16b), _16b, + scale(scale(4, bb, adxtail, _8), _8, -cdy, _16c), _16c, _32, _48), _48); + } + if (adytail !== 0) { + aytbclen = scale(4, bc, adytail, aytbc); + finlen = finadd(finlen, sum_three( + scale(aytbclen, aytbc, 2 * ady, _16), _16, + scale(scale(4, bb, adytail, _8), _8, cdx, _16b), _16b, + scale(scale(4, cc, adytail, _8), _8, -bdx, _16c), _16c, _32, _48), _48); + } + if (bdxtail !== 0) { + bxtcalen = scale(4, ca, bdxtail, bxtca); + finlen = finadd(finlen, sum_three( + scale(bxtcalen, bxtca, 2 * bdx, _16), _16, + scale(scale(4, aa, bdxtail, _8), _8, cdy, _16b), _16b, + scale(scale(4, cc, bdxtail, _8), _8, -ady, _16c), _16c, _32, _48), _48); + } + if (bdytail !== 0) { + bytcalen = scale(4, ca, bdytail, bytca); + finlen = finadd(finlen, sum_three( + scale(bytcalen, bytca, 2 * bdy, _16), _16, + scale(scale(4, cc, bdytail, _8), _8, adx, _16b), _16b, + scale(scale(4, aa, bdytail, _8), _8, -cdx, _16c), _16c, _32, _48), _48); + } + if (cdxtail !== 0) { + cxtablen = scale(4, ab, cdxtail, cxtab); + finlen = finadd(finlen, sum_three( + scale(cxtablen, cxtab, 2 * cdx, _16), _16, + scale(scale(4, bb, cdxtail, _8), _8, ady, _16b), _16b, + scale(scale(4, aa, cdxtail, _8), _8, -bdy, _16c), _16c, _32, _48), _48); + } + if (cdytail !== 0) { + cytablen = scale(4, ab, cdytail, cytab); + finlen = finadd(finlen, sum_three( + scale(cytablen, cytab, 2 * cdy, _16), _16, + scale(scale(4, aa, cdytail, _8), _8, bdx, _16b), _16b, + scale(scale(4, bb, cdytail, _8), _8, -adx, _16c), _16c, _32, _48), _48); + } + + if (adxtail !== 0 || adytail !== 0) { + if (bdxtail !== 0 || bdytail !== 0 || cdxtail !== 0 || cdytail !== 0) { + s1 = bdxtail * cdy; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * cdytail; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * cdytail; + bhi = c - (c - cdytail); + blo = cdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + u[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + u[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + s1 = cdxtail * -bdy; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * -bdy; + bhi = c - (c - -bdy); + blo = -bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * -bdytail; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * -bdytail; + bhi = c - (c - -bdytail); + blo = -bdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + v[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + v[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + v[2] = _j - (u3 - bvirt) + (_i - bvirt); + v[3] = u3; + bctlen = sum(4, u, 4, v, bct); + s1 = bdxtail * cdytail; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * cdytail; + bhi = c - (c - cdytail); + blo = cdytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdxtail * bdytail; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * bdytail; + bhi = c - (c - bdytail); + blo = bdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bctt[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bctt[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bctt[2] = _j - (u3 - bvirt) + (_i - bvirt); + bctt[3] = u3; + bcttlen = 4; + } else { + bct[0] = 0; + bctlen = 1; + bctt[0] = 0; + bcttlen = 1; + } + if (adxtail !== 0) { + const len = scale(bctlen, bct, adxtail, _16c); + finlen = finadd(finlen, sum( + scale(axtbclen, axtbc, adxtail, _16), _16, + scale(len, _16c, 2 * adx, _32), _32, _48), _48); + + const len2 = scale(bcttlen, bctt, adxtail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * adx, _16), _16, + scale(len2, _8, adxtail, _16b), _16b, + scale(len, _16c, adxtail, _32), _32, _32b, _64), _64); + + if (bdytail !== 0) { + finlen = finadd(finlen, scale(scale(4, cc, adxtail, _8), _8, bdytail, _16), _16); + } + if (cdytail !== 0) { + finlen = finadd(finlen, scale(scale(4, bb, -adxtail, _8), _8, cdytail, _16), _16); + } + } + if (adytail !== 0) { + const len = scale(bctlen, bct, adytail, _16c); + finlen = finadd(finlen, sum( + scale(aytbclen, aytbc, adytail, _16), _16, + scale(len, _16c, 2 * ady, _32), _32, _48), _48); + + const len2 = scale(bcttlen, bctt, adytail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * ady, _16), _16, + scale(len2, _8, adytail, _16b), _16b, + scale(len, _16c, adytail, _32), _32, _32b, _64), _64); + } + } + if (bdxtail !== 0 || bdytail !== 0) { + if (cdxtail !== 0 || cdytail !== 0 || adxtail !== 0 || adytail !== 0) { + s1 = cdxtail * ady; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * adytail; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * adytail; + bhi = c - (c - adytail); + blo = adytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + u[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + u[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + n1 = -cdy; + n0 = -cdytail; + s1 = adxtail * n1; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * n1; + bhi = c - (c - n1); + blo = n1 - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * n0; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * n0; + bhi = c - (c - n0); + blo = n0 - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + v[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + v[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + v[2] = _j - (u3 - bvirt) + (_i - bvirt); + v[3] = u3; + catlen = sum(4, u, 4, v, cat); + s1 = cdxtail * adytail; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * adytail; + bhi = c - (c - adytail); + blo = adytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adxtail * cdytail; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * cdytail; + bhi = c - (c - cdytail); + blo = cdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + catt[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + catt[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + catt[2] = _j - (u3 - bvirt) + (_i - bvirt); + catt[3] = u3; + cattlen = 4; + } else { + cat[0] = 0; + catlen = 1; + catt[0] = 0; + cattlen = 1; + } + if (bdxtail !== 0) { + const len = scale(catlen, cat, bdxtail, _16c); + finlen = finadd(finlen, sum( + scale(bxtcalen, bxtca, bdxtail, _16), _16, + scale(len, _16c, 2 * bdx, _32), _32, _48), _48); + + const len2 = scale(cattlen, catt, bdxtail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * bdx, _16), _16, + scale(len2, _8, bdxtail, _16b), _16b, + scale(len, _16c, bdxtail, _32), _32, _32b, _64), _64); + + if (cdytail !== 0) { + finlen = finadd(finlen, scale(scale(4, aa, bdxtail, _8), _8, cdytail, _16), _16); + } + if (adytail !== 0) { + finlen = finadd(finlen, scale(scale(4, cc, -bdxtail, _8), _8, adytail, _16), _16); + } + } + if (bdytail !== 0) { + const len = scale(catlen, cat, bdytail, _16c); + finlen = finadd(finlen, sum( + scale(bytcalen, bytca, bdytail, _16), _16, + scale(len, _16c, 2 * bdy, _32), _32, _48), _48); + + const len2 = scale(cattlen, catt, bdytail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * bdy, _16), _16, + scale(len2, _8, bdytail, _16b), _16b, + scale(len, _16c, bdytail, _32), _32, _32b, _64), _64); + } + } + if (cdxtail !== 0 || cdytail !== 0) { + if (adxtail !== 0 || adytail !== 0 || bdxtail !== 0 || bdytail !== 0) { + s1 = adxtail * bdy; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * bdytail; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * bdytail; + bhi = c - (c - bdytail); + blo = bdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + u[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + u[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + n1 = -ady; + n0 = -adytail; + s1 = bdxtail * n1; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * n1; + bhi = c - (c - n1); + blo = n1 - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * n0; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * n0; + bhi = c - (c - n0); + blo = n0 - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + v[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + v[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + v[2] = _j - (u3 - bvirt) + (_i - bvirt); + v[3] = u3; + abtlen = sum(4, u, 4, v, abt); + s1 = adxtail * bdytail; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * bdytail; + bhi = c - (c - bdytail); + blo = bdytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdxtail * adytail; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * adytail; + bhi = c - (c - adytail); + blo = adytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + abtt[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + abtt[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + abtt[2] = _j - (u3 - bvirt) + (_i - bvirt); + abtt[3] = u3; + abttlen = 4; + } else { + abt[0] = 0; + abtlen = 1; + abtt[0] = 0; + abttlen = 1; + } + if (cdxtail !== 0) { + const len = scale(abtlen, abt, cdxtail, _16c); + finlen = finadd(finlen, sum( + scale(cxtablen, cxtab, cdxtail, _16), _16, + scale(len, _16c, 2 * cdx, _32), _32, _48), _48); + + const len2 = scale(abttlen, abtt, cdxtail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * cdx, _16), _16, + scale(len2, _8, cdxtail, _16b), _16b, + scale(len, _16c, cdxtail, _32), _32, _32b, _64), _64); + + if (adytail !== 0) { + finlen = finadd(finlen, scale(scale(4, bb, cdxtail, _8), _8, adytail, _16), _16); + } + if (bdytail !== 0) { + finlen = finadd(finlen, scale(scale(4, aa, -cdxtail, _8), _8, bdytail, _16), _16); + } + } + if (cdytail !== 0) { + const len = scale(abtlen, abt, cdytail, _16c); + finlen = finadd(finlen, sum( + scale(cytablen, cytab, cdytail, _16), _16, + scale(len, _16c, 2 * cdy, _32), _32, _48), _48); + + const len2 = scale(abttlen, abtt, cdytail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * cdy, _16), _16, + scale(len2, _8, cdytail, _16b), _16b, + scale(len, _16c, cdytail, _32), _32, _32b, _64), _64); + } + } + + return fin[finlen - 1]; +} + +export function incircle(ax, ay, bx, by, cx, cy, dx, dy) { + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + + const bdxcdy = bdx * cdy; + const cdxbdy = cdx * bdy; + const alift = adx * adx + ady * ady; + + const cdxady = cdx * ady; + const adxcdy = adx * cdy; + const blift = bdx * bdx + bdy * bdy; + + const adxbdy = adx * bdy; + const bdxady = bdx * ady; + const clift = cdx * cdx + cdy * cdy; + + const det = + alift * (bdxcdy - cdxbdy) + + blift * (cdxady - adxcdy) + + clift * (adxbdy - bdxady); + + const permanent = + (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * alift + + (Math.abs(cdxady) + Math.abs(adxcdy)) * blift + + (Math.abs(adxbdy) + Math.abs(bdxady)) * clift; + + const errbound = iccerrboundA * permanent; + + if (det > errbound || -det > errbound) { + return det; + } + return incircleadapt(ax, ay, bx, by, cx, cy, dx, dy, permanent); +} + +export function incirclefast(ax, ay, bx, by, cx, cy, dx, dy) { + const adx = ax - dx; + const ady = ay - dy; + const bdx = bx - dx; + const bdy = by - dy; + const cdx = cx - dx; + const cdy = cy - dy; + + const abdet = adx * bdy - bdx * ady; + const bcdet = bdx * cdy - cdx * bdy; + const cadet = cdx * ady - adx * cdy; + const alift = adx * adx + ady * ady; + const blift = bdx * bdx + bdy * bdy; + const clift = cdx * cdx + cdy * cdy; + + return alift * bcdet + blift * cadet + clift * abdet; +} diff --git a/node_modules/robust-predicates/esm/insphere.js b/node_modules/robust-predicates/esm/insphere.js new file mode 100644 index 0000000000000000000000000000000000000000..7f5eeee5bfa6eb243c03e815d889c4cd843e4a1c --- /dev/null +++ b/node_modules/robust-predicates/esm/insphere.js @@ -0,0 +1,775 @@ +import {epsilon, splitter, resulterrbound, estimate, vec, sum, sum_three, scale, negate} from './util.js'; + +const isperrboundA = (16 + 224 * epsilon) * epsilon; +const isperrboundB = (5 + 72 * epsilon) * epsilon; +const isperrboundC = (71 + 1408 * epsilon) * epsilon * epsilon; + +const ab = vec(4); +const bc = vec(4); +const cd = vec(4); +const de = vec(4); +const ea = vec(4); +const ac = vec(4); +const bd = vec(4); +const ce = vec(4); +const da = vec(4); +const eb = vec(4); + +const abc = vec(24); +const bcd = vec(24); +const cde = vec(24); +const dea = vec(24); +const eab = vec(24); +const abd = vec(24); +const bce = vec(24); +const cda = vec(24); +const deb = vec(24); +const eac = vec(24); + +const adet = vec(1152); +const bdet = vec(1152); +const cdet = vec(1152); +const ddet = vec(1152); +const edet = vec(1152); +const abdet = vec(2304); +const cddet = vec(2304); +const cdedet = vec(3456); +const deter = vec(5760); + +const _8 = vec(8); +const _8b = vec(8); +const _8c = vec(8); +const _16 = vec(16); +const _24 = vec(24); +const _48 = vec(48); +const _48b = vec(48); +const _96 = vec(96); +const _192 = vec(192); +const _384x = vec(384); +const _384y = vec(384); +const _384z = vec(384); +const _768 = vec(768); + +function sum_three_scale(a, b, c, az, bz, cz, out) { + return sum_three( + scale(4, a, az, _8), _8, + scale(4, b, bz, _8b), _8b, + scale(4, c, cz, _8c), _8c, _16, out); +} + +function liftexact(alen, a, blen, b, clen, c, dlen, d, x, y, z, out) { + const len = sum( + sum(alen, a, blen, b, _48), _48, + negate(sum(clen, c, dlen, d, _48b), _48b), _48b, _96); + + return sum_three( + scale(scale(len, _96, x, _192), _192, x, _384x), _384x, + scale(scale(len, _96, y, _192), _192, y, _384y), _384y, + scale(scale(len, _96, z, _192), _192, z, _384z), _384z, _768, out); +} + +function insphereexact(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez) { + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + s1 = ax * by; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bx * ay; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ab[2] = _j - (u3 - bvirt) + (_i - bvirt); + ab[3] = u3; + s1 = bx * cy; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cx * by; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bc[2] = _j - (u3 - bvirt) + (_i - bvirt); + bc[3] = u3; + s1 = cx * dy; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dx * cy; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + cd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + cd[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + cd[2] = _j - (u3 - bvirt) + (_i - bvirt); + cd[3] = u3; + s1 = dx * ey; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ex * dy; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + de[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + de[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + de[2] = _j - (u3 - bvirt) + (_i - bvirt); + de[3] = u3; + s1 = ex * ay; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ax * ey; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ea[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ea[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ea[2] = _j - (u3 - bvirt) + (_i - bvirt); + ea[3] = u3; + s1 = ax * cy; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cx * ay; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ac[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ac[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ac[2] = _j - (u3 - bvirt) + (_i - bvirt); + ac[3] = u3; + s1 = bx * dy; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dx * by; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bd[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bd[2] = _j - (u3 - bvirt) + (_i - bvirt); + bd[3] = u3; + s1 = cx * ey; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ex * cy; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ce[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ce[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ce[2] = _j - (u3 - bvirt) + (_i - bvirt); + ce[3] = u3; + s1 = dx * ay; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ax * dy; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + da[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + da[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + da[2] = _j - (u3 - bvirt) + (_i - bvirt); + da[3] = u3; + s1 = ex * by; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bx * ey; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + eb[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + eb[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + eb[2] = _j - (u3 - bvirt) + (_i - bvirt); + eb[3] = u3; + + const abclen = sum_three_scale(ab, bc, ac, cz, az, -bz, abc); + const bcdlen = sum_three_scale(bc, cd, bd, dz, bz, -cz, bcd); + const cdelen = sum_three_scale(cd, de, ce, ez, cz, -dz, cde); + const dealen = sum_three_scale(de, ea, da, az, dz, -ez, dea); + const eablen = sum_three_scale(ea, ab, eb, bz, ez, -az, eab); + const abdlen = sum_three_scale(ab, bd, da, dz, az, bz, abd); + const bcelen = sum_three_scale(bc, ce, eb, ez, bz, cz, bce); + const cdalen = sum_three_scale(cd, da, ac, az, cz, dz, cda); + const deblen = sum_three_scale(de, eb, bd, bz, dz, ez, deb); + const eaclen = sum_three_scale(ea, ac, ce, cz, ez, az, eac); + + const deterlen = sum_three( + liftexact(cdelen, cde, bcelen, bce, deblen, deb, bcdlen, bcd, ax, ay, az, adet), adet, + liftexact(dealen, dea, cdalen, cda, eaclen, eac, cdelen, cde, bx, by, bz, bdet), bdet, + sum_three( + liftexact(eablen, eab, deblen, deb, abdlen, abd, dealen, dea, cx, cy, cz, cdet), cdet, + liftexact(abclen, abc, eaclen, eac, bcelen, bce, eablen, eab, dx, dy, dz, ddet), ddet, + liftexact(bcdlen, bcd, abdlen, abd, cdalen, cda, abclen, abc, ex, ey, ez, edet), edet, cddet, cdedet), cdedet, abdet, deter); + + return deter[deterlen - 1]; +} + +const xdet = vec(96); +const ydet = vec(96); +const zdet = vec(96); +const fin = vec(1152); + +function liftadapt(a, b, c, az, bz, cz, x, y, z, out) { + const len = sum_three_scale(a, b, c, az, bz, cz, _24); + return sum_three( + scale(scale(len, _24, x, _48), _48, x, xdet), xdet, + scale(scale(len, _24, y, _48), _48, y, ydet), ydet, + scale(scale(len, _24, z, _48), _48, z, zdet), zdet, _192, out); +} + +function insphereadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez, permanent) { + let ab3, bc3, cd3, da3, ac3, bd3; + + let aextail, bextail, cextail, dextail; + let aeytail, beytail, ceytail, deytail; + let aeztail, beztail, ceztail, deztail; + + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0; + + const aex = ax - ex; + const bex = bx - ex; + const cex = cx - ex; + const dex = dx - ex; + const aey = ay - ey; + const bey = by - ey; + const cey = cy - ey; + const dey = dy - ey; + const aez = az - ez; + const bez = bz - ez; + const cez = cz - ez; + const dez = dz - ez; + + s1 = aex * bey; + c = splitter * aex; + ahi = c - (c - aex); + alo = aex - ahi; + c = splitter * bey; + bhi = c - (c - bey); + blo = bey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bex * aey; + c = splitter * bex; + ahi = c - (c - bex); + alo = bex - ahi; + c = splitter * aey; + bhi = c - (c - aey); + blo = aey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab[1] = _0 - (_i + bvirt) + (bvirt - t1); + ab3 = _j + _i; + bvirt = ab3 - _j; + ab[2] = _j - (ab3 - bvirt) + (_i - bvirt); + ab[3] = ab3; + s1 = bex * cey; + c = splitter * bex; + ahi = c - (c - bex); + alo = bex - ahi; + c = splitter * cey; + bhi = c - (c - cey); + blo = cey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cex * bey; + c = splitter * cex; + ahi = c - (c - cex); + alo = cex - ahi; + c = splitter * bey; + bhi = c - (c - bey); + blo = bey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc[1] = _0 - (_i + bvirt) + (bvirt - t1); + bc3 = _j + _i; + bvirt = bc3 - _j; + bc[2] = _j - (bc3 - bvirt) + (_i - bvirt); + bc[3] = bc3; + s1 = cex * dey; + c = splitter * cex; + ahi = c - (c - cex); + alo = cex - ahi; + c = splitter * dey; + bhi = c - (c - dey); + blo = dey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dex * cey; + c = splitter * dex; + ahi = c - (c - dex); + alo = dex - ahi; + c = splitter * cey; + bhi = c - (c - cey); + blo = cey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + cd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + cd[1] = _0 - (_i + bvirt) + (bvirt - t1); + cd3 = _j + _i; + bvirt = cd3 - _j; + cd[2] = _j - (cd3 - bvirt) + (_i - bvirt); + cd[3] = cd3; + s1 = dex * aey; + c = splitter * dex; + ahi = c - (c - dex); + alo = dex - ahi; + c = splitter * aey; + bhi = c - (c - aey); + blo = aey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = aex * dey; + c = splitter * aex; + ahi = c - (c - aex); + alo = aex - ahi; + c = splitter * dey; + bhi = c - (c - dey); + blo = dey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + da[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + da[1] = _0 - (_i + bvirt) + (bvirt - t1); + da3 = _j + _i; + bvirt = da3 - _j; + da[2] = _j - (da3 - bvirt) + (_i - bvirt); + da[3] = da3; + s1 = aex * cey; + c = splitter * aex; + ahi = c - (c - aex); + alo = aex - ahi; + c = splitter * cey; + bhi = c - (c - cey); + blo = cey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cex * aey; + c = splitter * cex; + ahi = c - (c - cex); + alo = cex - ahi; + c = splitter * aey; + bhi = c - (c - aey); + blo = aey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ac[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ac[1] = _0 - (_i + bvirt) + (bvirt - t1); + ac3 = _j + _i; + bvirt = ac3 - _j; + ac[2] = _j - (ac3 - bvirt) + (_i - bvirt); + ac[3] = ac3; + s1 = bex * dey; + c = splitter * bex; + ahi = c - (c - bex); + alo = bex - ahi; + c = splitter * dey; + bhi = c - (c - dey); + blo = dey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dex * bey; + c = splitter * dex; + ahi = c - (c - dex); + alo = dex - ahi; + c = splitter * bey; + bhi = c - (c - bey); + blo = bey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bd[1] = _0 - (_i + bvirt) + (bvirt - t1); + bd3 = _j + _i; + bvirt = bd3 - _j; + bd[2] = _j - (bd3 - bvirt) + (_i - bvirt); + bd[3] = bd3; + + const finlen = sum( + sum( + negate(liftadapt(bc, cd, bd, dez, bez, -cez, aex, aey, aez, adet), adet), adet, + liftadapt(cd, da, ac, aez, cez, dez, bex, bey, bez, bdet), bdet, abdet), abdet, + sum( + negate(liftadapt(da, ab, bd, bez, dez, aez, cex, cey, cez, cdet), cdet), cdet, + liftadapt(ab, bc, ac, cez, aez, -bez, dex, dey, dez, ddet), ddet, cddet), cddet, fin); + + let det = estimate(finlen, fin); + let errbound = isperrboundB * permanent; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - aex; + aextail = ax - (aex + bvirt) + (bvirt - ex); + bvirt = ay - aey; + aeytail = ay - (aey + bvirt) + (bvirt - ey); + bvirt = az - aez; + aeztail = az - (aez + bvirt) + (bvirt - ez); + bvirt = bx - bex; + bextail = bx - (bex + bvirt) + (bvirt - ex); + bvirt = by - bey; + beytail = by - (bey + bvirt) + (bvirt - ey); + bvirt = bz - bez; + beztail = bz - (bez + bvirt) + (bvirt - ez); + bvirt = cx - cex; + cextail = cx - (cex + bvirt) + (bvirt - ex); + bvirt = cy - cey; + ceytail = cy - (cey + bvirt) + (bvirt - ey); + bvirt = cz - cez; + ceztail = cz - (cez + bvirt) + (bvirt - ez); + bvirt = dx - dex; + dextail = dx - (dex + bvirt) + (bvirt - ex); + bvirt = dy - dey; + deytail = dy - (dey + bvirt) + (bvirt - ey); + bvirt = dz - dez; + deztail = dz - (dez + bvirt) + (bvirt - ez); + if (aextail === 0 && aeytail === 0 && aeztail === 0 && + bextail === 0 && beytail === 0 && beztail === 0 && + cextail === 0 && ceytail === 0 && ceztail === 0 && + dextail === 0 && deytail === 0 && deztail === 0) { + return det; + } + + errbound = isperrboundC * permanent + resulterrbound * Math.abs(det); + + const abeps = (aex * beytail + bey * aextail) - (aey * bextail + bex * aeytail); + const bceps = (bex * ceytail + cey * bextail) - (bey * cextail + cex * beytail); + const cdeps = (cex * deytail + dey * cextail) - (cey * dextail + dex * ceytail); + const daeps = (dex * aeytail + aey * dextail) - (dey * aextail + aex * deytail); + const aceps = (aex * ceytail + cey * aextail) - (aey * cextail + cex * aeytail); + const bdeps = (bex * deytail + dey * bextail) - (bey * dextail + dex * beytail); + det += + (((bex * bex + bey * bey + bez * bez) * ((cez * daeps + dez * aceps + aez * cdeps) + + (ceztail * da3 + deztail * ac3 + aeztail * cd3)) + (dex * dex + dey * dey + dez * dez) * + ((aez * bceps - bez * aceps + cez * abeps) + (aeztail * bc3 - beztail * ac3 + ceztail * ab3))) - + ((aex * aex + aey * aey + aez * aez) * ((bez * cdeps - cez * bdeps + dez * bceps) + + (beztail * cd3 - ceztail * bd3 + deztail * bc3)) + (cex * cex + cey * cey + cez * cez) * + ((dez * abeps + aez * bdeps + bez * daeps) + (deztail * ab3 + aeztail * bd3 + beztail * da3)))) + + 2 * (((bex * bextail + bey * beytail + bez * beztail) * (cez * da3 + dez * ac3 + aez * cd3) + + (dex * dextail + dey * deytail + dez * deztail) * (aez * bc3 - bez * ac3 + cez * ab3)) - + ((aex * aextail + aey * aeytail + aez * aeztail) * (bez * cd3 - cez * bd3 + dez * bc3) + + (cex * cextail + cey * ceytail + cez * ceztail) * (dez * ab3 + aez * bd3 + bez * da3))); + + if (det >= errbound || -det >= errbound) { + return det; + } + + return insphereexact(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez); +} + +export function insphere(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez) { + const aex = ax - ex; + const bex = bx - ex; + const cex = cx - ex; + const dex = dx - ex; + const aey = ay - ey; + const bey = by - ey; + const cey = cy - ey; + const dey = dy - ey; + const aez = az - ez; + const bez = bz - ez; + const cez = cz - ez; + const dez = dz - ez; + + const aexbey = aex * bey; + const bexaey = bex * aey; + const ab = aexbey - bexaey; + const bexcey = bex * cey; + const cexbey = cex * bey; + const bc = bexcey - cexbey; + const cexdey = cex * dey; + const dexcey = dex * cey; + const cd = cexdey - dexcey; + const dexaey = dex * aey; + const aexdey = aex * dey; + const da = dexaey - aexdey; + const aexcey = aex * cey; + const cexaey = cex * aey; + const ac = aexcey - cexaey; + const bexdey = bex * dey; + const dexbey = dex * bey; + const bd = bexdey - dexbey; + + const abc = aez * bc - bez * ac + cez * ab; + const bcd = bez * cd - cez * bd + dez * bc; + const cda = cez * da + dez * ac + aez * cd; + const dab = dez * ab + aez * bd + bez * da; + + const alift = aex * aex + aey * aey + aez * aez; + const blift = bex * bex + bey * bey + bez * bez; + const clift = cex * cex + cey * cey + cez * cez; + const dlift = dex * dex + dey * dey + dez * dez; + + const det = (clift * dab - dlift * abc) + (alift * bcd - blift * cda); + + const aezplus = Math.abs(aez); + const bezplus = Math.abs(bez); + const cezplus = Math.abs(cez); + const dezplus = Math.abs(dez); + const aexbeyplus = Math.abs(aexbey); + const bexaeyplus = Math.abs(bexaey); + const bexceyplus = Math.abs(bexcey); + const cexbeyplus = Math.abs(cexbey); + const cexdeyplus = Math.abs(cexdey); + const dexceyplus = Math.abs(dexcey); + const dexaeyplus = Math.abs(dexaey); + const aexdeyplus = Math.abs(aexdey); + const aexceyplus = Math.abs(aexcey); + const cexaeyplus = Math.abs(cexaey); + const bexdeyplus = Math.abs(bexdey); + const dexbeyplus = Math.abs(dexbey); + const permanent = + ((cexdeyplus + dexceyplus) * bezplus + (dexbeyplus + bexdeyplus) * cezplus + (bexceyplus + cexbeyplus) * dezplus) * alift + + ((dexaeyplus + aexdeyplus) * cezplus + (aexceyplus + cexaeyplus) * dezplus + (cexdeyplus + dexceyplus) * aezplus) * blift + + ((aexbeyplus + bexaeyplus) * dezplus + (bexdeyplus + dexbeyplus) * aezplus + (dexaeyplus + aexdeyplus) * bezplus) * clift + + ((bexceyplus + cexbeyplus) * aezplus + (cexaeyplus + aexceyplus) * bezplus + (aexbeyplus + bexaeyplus) * cezplus) * dlift; + + const errbound = isperrboundA * permanent; + if (det > errbound || -det > errbound) { + return det; + } + return -insphereadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez, permanent); +} + +export function inspherefast(pax, pay, paz, pbx, pby, pbz, pcx, pcy, pcz, pdx, pdy, pdz, pex, pey, pez) { + const aex = pax - pex; + const bex = pbx - pex; + const cex = pcx - pex; + const dex = pdx - pex; + const aey = pay - pey; + const bey = pby - pey; + const cey = pcy - pey; + const dey = pdy - pey; + const aez = paz - pez; + const bez = pbz - pez; + const cez = pcz - pez; + const dez = pdz - pez; + + const ab = aex * bey - bex * aey; + const bc = bex * cey - cex * bey; + const cd = cex * dey - dex * cey; + const da = dex * aey - aex * dey; + const ac = aex * cey - cex * aey; + const bd = bex * dey - dex * bey; + + const abc = aez * bc - bez * ac + cez * ab; + const bcd = bez * cd - cez * bd + dez * bc; + const cda = cez * da + dez * ac + aez * cd; + const dab = dez * ab + aez * bd + bez * da; + + const alift = aex * aex + aey * aey + aez * aez; + const blift = bex * bex + bey * bey + bez * bez; + const clift = cex * cex + cey * cey + cez * cez; + const dlift = dex * dex + dey * dey + dez * dez; + + return (clift * dab - dlift * abc) + (alift * bcd - blift * cda); +} diff --git a/node_modules/robust-predicates/esm/orient2d.js b/node_modules/robust-predicates/esm/orient2d.js new file mode 100644 index 0000000000000000000000000000000000000000..492b3f97ec7a663a61e7a68702d4491afa47cbb3 --- /dev/null +++ b/node_modules/robust-predicates/esm/orient2d.js @@ -0,0 +1,186 @@ +import {epsilon, splitter, resulterrbound, estimate, vec, sum} from './util.js'; + +const ccwerrboundA = (3 + 16 * epsilon) * epsilon; +const ccwerrboundB = (2 + 12 * epsilon) * epsilon; +const ccwerrboundC = (9 + 64 * epsilon) * epsilon * epsilon; + +const B = vec(4); +const C1 = vec(8); +const C2 = vec(12); +const D = vec(16); +const u = vec(4); + +function orient2dadapt(ax, ay, bx, by, cx, cy, detsum) { + let acxtail, acytail, bcxtail, bcytail; + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + const acx = ax - cx; + const bcx = bx - cx; + const acy = ay - cy; + const bcy = by - cy; + + s1 = acx * bcy; + c = splitter * acx; + ahi = c - (c - acx); + alo = acx - ahi; + c = splitter * bcy; + bhi = c - (c - bcy); + blo = bcy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acy * bcx; + c = splitter * acy; + ahi = c - (c - acy); + alo = acy - ahi; + c = splitter * bcx; + bhi = c - (c - bcx); + blo = bcx - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + B[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + B[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + B[2] = _j - (u3 - bvirt) + (_i - bvirt); + B[3] = u3; + + let det = estimate(4, B); + let errbound = ccwerrboundB * detsum; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - acx; + acxtail = ax - (acx + bvirt) + (bvirt - cx); + bvirt = bx - bcx; + bcxtail = bx - (bcx + bvirt) + (bvirt - cx); + bvirt = ay - acy; + acytail = ay - (acy + bvirt) + (bvirt - cy); + bvirt = by - bcy; + bcytail = by - (bcy + bvirt) + (bvirt - cy); + + if (acxtail === 0 && acytail === 0 && bcxtail === 0 && bcytail === 0) { + return det; + } + + errbound = ccwerrboundC * detsum + resulterrbound * Math.abs(det); + det += (acx * bcytail + bcy * acxtail) - (acy * bcxtail + bcx * acytail); + if (det >= errbound || -det >= errbound) return det; + + s1 = acxtail * bcy; + c = splitter * acxtail; + ahi = c - (c - acxtail); + alo = acxtail - ahi; + c = splitter * bcy; + bhi = c - (c - bcy); + blo = bcy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acytail * bcx; + c = splitter * acytail; + ahi = c - (c - acytail); + alo = acytail - ahi; + c = splitter * bcx; + bhi = c - (c - bcx); + blo = bcx - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + const C1len = sum(4, B, 4, u, C1); + + s1 = acx * bcytail; + c = splitter * acx; + ahi = c - (c - acx); + alo = acx - ahi; + c = splitter * bcytail; + bhi = c - (c - bcytail); + blo = bcytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acy * bcxtail; + c = splitter * acy; + ahi = c - (c - acy); + alo = acy - ahi; + c = splitter * bcxtail; + bhi = c - (c - bcxtail); + blo = bcxtail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + const C2len = sum(C1len, C1, 4, u, C2); + + s1 = acxtail * bcytail; + c = splitter * acxtail; + ahi = c - (c - acxtail); + alo = acxtail - ahi; + c = splitter * bcytail; + bhi = c - (c - bcytail); + blo = bcytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acytail * bcxtail; + c = splitter * acytail; + ahi = c - (c - acytail); + alo = acytail - ahi; + c = splitter * bcxtail; + bhi = c - (c - bcxtail); + blo = bcxtail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + const Dlen = sum(C2len, C2, 4, u, D); + + return D[Dlen - 1]; +} + +export function orient2d(ax, ay, bx, by, cx, cy) { + const detleft = (ay - cy) * (bx - cx); + const detright = (ax - cx) * (by - cy); + const det = detleft - detright; + + if (detleft === 0 || detright === 0 || (detleft > 0) !== (detright > 0)) return det; + + const detsum = Math.abs(detleft + detright); + if (Math.abs(det) >= ccwerrboundA * detsum) return det; + + return -orient2dadapt(ax, ay, bx, by, cx, cy, detsum); +} + +export function orient2dfast(ax, ay, bx, by, cx, cy) { + return (ay - cy) * (bx - cx) - (ax - cx) * (by - cy); +} diff --git a/node_modules/robust-predicates/esm/orient3d.js b/node_modules/robust-predicates/esm/orient3d.js new file mode 100644 index 0000000000000000000000000000000000000000..7cb741cac29d9d1456dc633a45e926212582ecd7 --- /dev/null +++ b/node_modules/robust-predicates/esm/orient3d.js @@ -0,0 +1,462 @@ +import {epsilon, splitter, resulterrbound, estimate, vec, sum, scale} from './util.js'; + +const o3derrboundA = (7 + 56 * epsilon) * epsilon; +const o3derrboundB = (3 + 28 * epsilon) * epsilon; +const o3derrboundC = (26 + 288 * epsilon) * epsilon * epsilon; + +const bc = vec(4); +const ca = vec(4); +const ab = vec(4); +const at_b = vec(4); +const at_c = vec(4); +const bt_c = vec(4); +const bt_a = vec(4); +const ct_a = vec(4); +const ct_b = vec(4); +const bct = vec(8); +const cat = vec(8); +const abt = vec(8); +const u = vec(4); + +const _8 = vec(8); +const _8b = vec(8); +const _16 = vec(8); +const _12 = vec(12); + +let fin = vec(192); +let fin2 = vec(192); + +function finadd(finlen, alen, a) { + finlen = sum(finlen, fin, alen, a, fin2); + const tmp = fin; fin = fin2; fin2 = tmp; + return finlen; +} + +function tailinit(xtail, ytail, ax, ay, bx, by, a, b) { + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _k, _0, s1, s0, t1, t0, u3, negate; + if (xtail === 0) { + if (ytail === 0) { + a[0] = 0; + b[0] = 0; + return 1; + } else { + negate = -ytail; + s1 = negate * ax; + c = splitter * negate; + ahi = c - (c - negate); + alo = negate - ahi; + c = splitter * ax; + bhi = c - (c - ax); + blo = ax - bhi; + a[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + a[1] = s1; + s1 = ytail * bx; + c = splitter * ytail; + ahi = c - (c - ytail); + alo = ytail - ahi; + c = splitter * bx; + bhi = c - (c - bx); + blo = bx - bhi; + b[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + b[1] = s1; + return 2; + } + } else { + if (ytail === 0) { + s1 = xtail * ay; + c = splitter * xtail; + ahi = c - (c - xtail); + alo = xtail - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + a[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + a[1] = s1; + negate = -xtail; + s1 = negate * by; + c = splitter * negate; + ahi = c - (c - negate); + alo = negate - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + b[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + b[1] = s1; + return 2; + } else { + s1 = xtail * ay; + c = splitter * xtail; + ahi = c - (c - xtail); + alo = xtail - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ytail * ax; + c = splitter * ytail; + ahi = c - (c - ytail); + alo = ytail - ahi; + c = splitter * ax; + bhi = c - (c - ax); + blo = ax - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + a[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + a[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + a[2] = _j - (u3 - bvirt) + (_i - bvirt); + a[3] = u3; + s1 = ytail * bx; + c = splitter * ytail; + ahi = c - (c - ytail); + alo = ytail - ahi; + c = splitter * bx; + bhi = c - (c - bx); + blo = bx - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = xtail * by; + c = splitter * xtail; + ahi = c - (c - xtail); + alo = xtail - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + b[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + b[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + b[2] = _j - (u3 - bvirt) + (_i - bvirt); + b[3] = u3; + return 4; + } + } +} + +function tailadd(finlen, a, b, k, z) { + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _k, _0, s1, s0, u3; + s1 = a * b; + c = splitter * a; + ahi = c - (c - a); + alo = a - ahi; + c = splitter * b; + bhi = c - (c - b); + blo = b - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + c = splitter * k; + bhi = c - (c - k); + blo = k - bhi; + _i = s0 * k; + c = splitter * s0; + ahi = c - (c - s0); + alo = s0 - ahi; + u[0] = alo * blo - (_i - ahi * bhi - alo * bhi - ahi * blo); + _j = s1 * k; + c = splitter * s1; + ahi = c - (c - s1); + alo = s1 - ahi; + _0 = alo * blo - (_j - ahi * bhi - alo * bhi - ahi * blo); + _k = _i + _0; + bvirt = _k - _i; + u[1] = _i - (_k - bvirt) + (_0 - bvirt); + u3 = _j + _k; + u[2] = _k - (u3 - _j); + u[3] = u3; + finlen = finadd(finlen, 4, u); + if (z !== 0) { + c = splitter * z; + bhi = c - (c - z); + blo = z - bhi; + _i = s0 * z; + c = splitter * s0; + ahi = c - (c - s0); + alo = s0 - ahi; + u[0] = alo * blo - (_i - ahi * bhi - alo * bhi - ahi * blo); + _j = s1 * z; + c = splitter * s1; + ahi = c - (c - s1); + alo = s1 - ahi; + _0 = alo * blo - (_j - ahi * bhi - alo * bhi - ahi * blo); + _k = _i + _0; + bvirt = _k - _i; + u[1] = _i - (_k - bvirt) + (_0 - bvirt); + u3 = _j + _k; + u[2] = _k - (u3 - _j); + u[3] = u3; + finlen = finadd(finlen, 4, u); + } + return finlen; +} + +function orient3dadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, permanent) { + let finlen; + let adxtail, bdxtail, cdxtail; + let adytail, bdytail, cdytail; + let adztail, bdztail, cdztail; + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _k, _0, s1, s0, t1, t0, u3; + + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + const adz = az - dz; + const bdz = bz - dz; + const cdz = cz - dz; + + s1 = bdx * cdy; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * bdy; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bc[2] = _j - (u3 - bvirt) + (_i - bvirt); + bc[3] = u3; + s1 = cdx * ady; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * cdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ca[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ca[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ca[2] = _j - (u3 - bvirt) + (_i - bvirt); + ca[3] = u3; + s1 = adx * bdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * ady; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ab[2] = _j - (u3 - bvirt) + (_i - bvirt); + ab[3] = u3; + + finlen = sum( + sum( + scale(4, bc, adz, _8), _8, + scale(4, ca, bdz, _8b), _8b, _16), _16, + scale(4, ab, cdz, _8), _8, fin); + + let det = estimate(finlen, fin); + let errbound = o3derrboundB * permanent; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - adx; + adxtail = ax - (adx + bvirt) + (bvirt - dx); + bvirt = bx - bdx; + bdxtail = bx - (bdx + bvirt) + (bvirt - dx); + bvirt = cx - cdx; + cdxtail = cx - (cdx + bvirt) + (bvirt - dx); + bvirt = ay - ady; + adytail = ay - (ady + bvirt) + (bvirt - dy); + bvirt = by - bdy; + bdytail = by - (bdy + bvirt) + (bvirt - dy); + bvirt = cy - cdy; + cdytail = cy - (cdy + bvirt) + (bvirt - dy); + bvirt = az - adz; + adztail = az - (adz + bvirt) + (bvirt - dz); + bvirt = bz - bdz; + bdztail = bz - (bdz + bvirt) + (bvirt - dz); + bvirt = cz - cdz; + cdztail = cz - (cdz + bvirt) + (bvirt - dz); + + if (adxtail === 0 && bdxtail === 0 && cdxtail === 0 && + adytail === 0 && bdytail === 0 && cdytail === 0 && + adztail === 0 && bdztail === 0 && cdztail === 0) { + return det; + } + + errbound = o3derrboundC * permanent + resulterrbound * Math.abs(det); + det += + adz * (bdx * cdytail + cdy * bdxtail - (bdy * cdxtail + cdx * bdytail)) + adztail * (bdx * cdy - bdy * cdx) + + bdz * (cdx * adytail + ady * cdxtail - (cdy * adxtail + adx * cdytail)) + bdztail * (cdx * ady - cdy * adx) + + cdz * (adx * bdytail + bdy * adxtail - (ady * bdxtail + bdx * adytail)) + cdztail * (adx * bdy - ady * bdx); + if (det >= errbound || -det >= errbound) { + return det; + } + + const at_len = tailinit(adxtail, adytail, bdx, bdy, cdx, cdy, at_b, at_c); + const bt_len = tailinit(bdxtail, bdytail, cdx, cdy, adx, ady, bt_c, bt_a); + const ct_len = tailinit(cdxtail, cdytail, adx, ady, bdx, bdy, ct_a, ct_b); + + const bctlen = sum(bt_len, bt_c, ct_len, ct_b, bct); + finlen = finadd(finlen, scale(bctlen, bct, adz, _16), _16); + + const catlen = sum(ct_len, ct_a, at_len, at_c, cat); + finlen = finadd(finlen, scale(catlen, cat, bdz, _16), _16); + + const abtlen = sum(at_len, at_b, bt_len, bt_a, abt); + finlen = finadd(finlen, scale(abtlen, abt, cdz, _16), _16); + + if (adztail !== 0) { + finlen = finadd(finlen, scale(4, bc, adztail, _12), _12); + finlen = finadd(finlen, scale(bctlen, bct, adztail, _16), _16); + } + if (bdztail !== 0) { + finlen = finadd(finlen, scale(4, ca, bdztail, _12), _12); + finlen = finadd(finlen, scale(catlen, cat, bdztail, _16), _16); + } + if (cdztail !== 0) { + finlen = finadd(finlen, scale(4, ab, cdztail, _12), _12); + finlen = finadd(finlen, scale(abtlen, abt, cdztail, _16), _16); + } + + if (adxtail !== 0) { + if (bdytail !== 0) { + finlen = tailadd(finlen, adxtail, bdytail, cdz, cdztail); + } + if (cdytail !== 0) { + finlen = tailadd(finlen, -adxtail, cdytail, bdz, bdztail); + } + } + if (bdxtail !== 0) { + if (cdytail !== 0) { + finlen = tailadd(finlen, bdxtail, cdytail, adz, adztail); + } + if (adytail !== 0) { + finlen = tailadd(finlen, -bdxtail, adytail, cdz, cdztail); + } + } + if (cdxtail !== 0) { + if (adytail !== 0) { + finlen = tailadd(finlen, cdxtail, adytail, bdz, bdztail); + } + if (bdytail !== 0) { + finlen = tailadd(finlen, -cdxtail, bdytail, adz, adztail); + } + } + + return fin[finlen - 1]; +} + +export function orient3d(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz) { + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + const adz = az - dz; + const bdz = bz - dz; + const cdz = cz - dz; + + const bdxcdy = bdx * cdy; + const cdxbdy = cdx * bdy; + + const cdxady = cdx * ady; + const adxcdy = adx * cdy; + + const adxbdy = adx * bdy; + const bdxady = bdx * ady; + + const det = + adz * (bdxcdy - cdxbdy) + + bdz * (cdxady - adxcdy) + + cdz * (adxbdy - bdxady); + + const permanent = + (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) + + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) + + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz); + + const errbound = o3derrboundA * permanent; + if (det > errbound || -det > errbound) { + return det; + } + + return orient3dadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, permanent); +} + +export function orient3dfast(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz) { + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + const adz = az - dz; + const bdz = bz - dz; + const cdz = cz - dz; + + return adx * (bdy * cdz - bdz * cdy) + + bdx * (cdy * adz - cdz * ady) + + cdx * (ady * bdz - adz * bdy); +} diff --git a/node_modules/robust-predicates/esm/util.js b/node_modules/robust-predicates/esm/util.js new file mode 100644 index 0000000000000000000000000000000000000000..5325de10da248e076ceb7a9dd90aaa96b8ed1602 --- /dev/null +++ b/node_modules/robust-predicates/esm/util.js @@ -0,0 +1,138 @@ +export const epsilon = 1.1102230246251565e-16; +export const splitter = 134217729; +export const resulterrbound = (3 + 8 * epsilon) * epsilon; + +// fast_expansion_sum_zeroelim routine from oritinal code +export function sum(elen, e, flen, f, h) { + let Q, Qnew, hh, bvirt; + let enow = e[0]; + let fnow = f[0]; + let eindex = 0; + let findex = 0; + if ((fnow > enow) === (fnow > -enow)) { + Q = enow; + enow = e[++eindex]; + } else { + Q = fnow; + fnow = f[++findex]; + } + let hindex = 0; + if (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = enow + Q; + hh = Q - (Qnew - enow); + enow = e[++eindex]; + } else { + Qnew = fnow + Q; + hh = Q - (Qnew - fnow); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + while (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + } else { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + } + while (eindex < elen) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + while (findex < flen) { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +export function sum_three(alen, a, blen, b, clen, c, tmp, out) { + return sum(sum(alen, a, blen, b, tmp), tmp, clen, c, out); +} + +// scale_expansion_zeroelim routine from oritinal code +export function scale(elen, e, b, h) { + let Q, sum, hh, product1, product0; + let bvirt, c, ahi, alo, bhi, blo; + + c = splitter * b; + bhi = c - (c - b); + blo = b - bhi; + let enow = e[0]; + Q = enow * b; + c = splitter * enow; + ahi = c - (c - enow); + alo = enow - ahi; + hh = alo * blo - (Q - ahi * bhi - alo * bhi - ahi * blo); + let hindex = 0; + if (hh !== 0) { + h[hindex++] = hh; + } + for (let i = 1; i < elen; i++) { + enow = e[i]; + product1 = enow * b; + c = splitter * enow; + ahi = c - (c - enow); + alo = enow - ahi; + product0 = alo * blo - (product1 - ahi * bhi - alo * bhi - ahi * blo); + sum = Q + product0; + bvirt = sum - Q; + hh = Q - (sum - bvirt) + (product0 - bvirt); + if (hh !== 0) { + h[hindex++] = hh; + } + Q = product1 + sum; + hh = sum - (Q - product1); + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +export function negate(elen, e) { + for (let i = 0; i < elen; i++) e[i] = -e[i]; + return elen; +} + +export function estimate(elen, e) { + let Q = e[0]; + for (let i = 1; i < elen; i++) Q += e[i]; + return Q; +} + +export function vec(n) { + return new Float64Array(n); +} diff --git a/node_modules/robust-predicates/index.js b/node_modules/robust-predicates/index.js new file mode 100644 index 0000000000000000000000000000000000000000..db4764b6aa0766b73e5e910085e6d055797c80c7 --- /dev/null +++ b/node_modules/robust-predicates/index.js @@ -0,0 +1,5 @@ + +export {orient2d, orient2dfast} from './esm/orient2d.js'; +export {orient3d, orient3dfast} from './esm/orient3d.js'; +export {incircle, incirclefast} from './esm/incircle.js'; +export {insphere, inspherefast} from './esm/insphere.js'; diff --git a/node_modules/robust-predicates/package.json b/node_modules/robust-predicates/package.json new file mode 100644 index 0000000000000000000000000000000000000000..834d6f1143348c4ccd7b6d37f631621f9a8a4124 --- /dev/null +++ b/node_modules/robust-predicates/package.json @@ -0,0 +1,68 @@ +{ + "name": "robust-predicates", + "version": "2.0.4", + "description": "Fast robust predicates for computational geometry", + "keywords": [ + "computational geometry", + "robust arithmetic" + ], + "author": "Vladimir Agafonkin", + "license": "Unlicense", + "main": "umd/predicates.js", + "unpkg": "umd/predicates.min.js", + "module": "index.js", + "types": "index.d.ts", + "scripts": { + "build": "mkdirp esm && node compile.js", + "lint": "eslint *.js src test/test.js", + "test": "npm run lint && npm run build && node -r esm test/test.js", + "cov": "rm -rf node_modules/.cache/esm && nyc --require esm -r lcov -r text node test/test.js", + "bench": "node -r esm bench.js", + "prepublishOnly": "npm run test && rollup -c" + }, + "devDependencies": { + "eslint": "^6.3.0", + "eslint-config-mourner": "^3.0.0", + "esm": "^3.2.25", + "mkdirp": "^0.5.1", + "nextafter": "^1.0.0", + "nyc": "^14.1.1", + "robust-in-sphere": "^1.1.3", + "robust-orientation": "^1.1.3", + "rollup": "^1.20.3", + "rollup-plugin-terser": "^5.1.1", + "tape": "^4.11.0", + "terser": "^4.2.1" + }, + "files": [ + "index.js", + "esm", + "umd" + ], + "eslintConfig": { + "extends": "mourner", + "rules": { + "camelcase": 0, + "new-cap": 0, + "no-unused-vars": [ + 2, + { + "varsIgnorePattern": "splitter|bvirt|c|[ab]hi|[ab]lo|_[ijk0]|u3|[st][01]" + } + ], + "no-lonely-if": 0 + }, + "globals": { + "$Fast_Two_Sum": false, + "$Two_Sum": false, + "$Two_Diff_Tail": false, + "$Split": false, + "$Two_Product": false, + "$Two_Product_Presplit": false, + "$Two_One_Product": false, + "$Cross_Product": false, + "$Square_Sum": false, + "$Two_Product_Sum": false + } + } +} diff --git a/node_modules/robust-predicates/umd/incircle.js b/node_modules/robust-predicates/umd/incircle.js new file mode 100644 index 0000000000000000000000000000000000000000..f273b15882d49b0abca883814c2106fa300ee5d1 --- /dev/null +++ b/node_modules/robust-predicates/umd/incircle.js @@ -0,0 +1,910 @@ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : +typeof define === 'function' && define.amd ? define(['exports'], factory) : +(global = global || self, factory(global.predicates = {})); +}(this, function (exports) { 'use strict'; + +const epsilon = 1.1102230246251565e-16; +const splitter = 134217729; +const resulterrbound = (3 + 8 * epsilon) * epsilon; + +// fast_expansion_sum_zeroelim routine from oritinal code +function sum(elen, e, flen, f, h) { + let Q, Qnew, hh, bvirt; + let enow = e[0]; + let fnow = f[0]; + let eindex = 0; + let findex = 0; + if ((fnow > enow) === (fnow > -enow)) { + Q = enow; + enow = e[++eindex]; + } else { + Q = fnow; + fnow = f[++findex]; + } + let hindex = 0; + if (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = enow + Q; + hh = Q - (Qnew - enow); + enow = e[++eindex]; + } else { + Qnew = fnow + Q; + hh = Q - (Qnew - fnow); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + while (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + } else { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + } + while (eindex < elen) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + while (findex < flen) { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +function sum_three(alen, a, blen, b, clen, c, tmp, out) { + return sum(sum(alen, a, blen, b, tmp), tmp, clen, c, out); +} + +// scale_expansion_zeroelim routine from oritinal code +function scale(elen, e, b, h) { + let Q, sum, hh, product1, product0; + let bvirt, c, ahi, alo, bhi, blo; + + c = splitter * b; + bhi = c - (c - b); + blo = b - bhi; + let enow = e[0]; + Q = enow * b; + c = splitter * enow; + ahi = c - (c - enow); + alo = enow - ahi; + hh = alo * blo - (Q - ahi * bhi - alo * bhi - ahi * blo); + let hindex = 0; + if (hh !== 0) { + h[hindex++] = hh; + } + for (let i = 1; i < elen; i++) { + enow = e[i]; + product1 = enow * b; + c = splitter * enow; + ahi = c - (c - enow); + alo = enow - ahi; + product0 = alo * blo - (product1 - ahi * bhi - alo * bhi - ahi * blo); + sum = Q + product0; + bvirt = sum - Q; + hh = Q - (sum - bvirt) + (product0 - bvirt); + if (hh !== 0) { + h[hindex++] = hh; + } + Q = product1 + sum; + hh = sum - (Q - product1); + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +function estimate(elen, e) { + let Q = e[0]; + for (let i = 1; i < elen; i++) Q += e[i]; + return Q; +} + +function vec(n) { + return new Float64Array(n); +} + +const iccerrboundA = (10 + 96 * epsilon) * epsilon; +const iccerrboundB = (4 + 48 * epsilon) * epsilon; +const iccerrboundC = (44 + 576 * epsilon) * epsilon * epsilon; + +const bc = vec(4); +const ca = vec(4); +const ab = vec(4); +const aa = vec(4); +const bb = vec(4); +const cc = vec(4); +const u = vec(4); +const v = vec(4); +const axtbc = vec(8); +const aytbc = vec(8); +const bxtca = vec(8); +const bytca = vec(8); +const cxtab = vec(8); +const cytab = vec(8); +const abt = vec(8); +const bct = vec(8); +const cat = vec(8); +const abtt = vec(4); +const bctt = vec(4); +const catt = vec(4); + +const _8 = vec(8); +const _16 = vec(16); +const _16b = vec(16); +const _16c = vec(16); +const _32 = vec(32); +const _32b = vec(32); +const _48 = vec(48); +const _64 = vec(64); + +let fin = vec(1152); +let fin2 = vec(1152); + +function finadd(finlen, a, alen) { + finlen = sum(finlen, fin, a, alen, fin2); + const tmp = fin; fin = fin2; fin2 = tmp; + return finlen; +} + +function incircleadapt(ax, ay, bx, by, cx, cy, dx, dy, permanent) { + let finlen; + let adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail; + let axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen; + let abtlen, bctlen, catlen; + let abttlen, bcttlen, cattlen; + let n1, n0; + + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + + s1 = bdx * cdy; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * bdy; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bc[2] = _j - (u3 - bvirt) + (_i - bvirt); + bc[3] = u3; + s1 = cdx * ady; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * cdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ca[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ca[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ca[2] = _j - (u3 - bvirt) + (_i - bvirt); + ca[3] = u3; + s1 = adx * bdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * ady; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ab[2] = _j - (u3 - bvirt) + (_i - bvirt); + ab[3] = u3; + + finlen = sum( + sum( + sum( + scale(scale(4, bc, adx, _8), _8, adx, _16), _16, + scale(scale(4, bc, ady, _8), _8, ady, _16b), _16b, _32), _32, + sum( + scale(scale(4, ca, bdx, _8), _8, bdx, _16), _16, + scale(scale(4, ca, bdy, _8), _8, bdy, _16b), _16b, _32b), _32b, _64), _64, + sum( + scale(scale(4, ab, cdx, _8), _8, cdx, _16), _16, + scale(scale(4, ab, cdy, _8), _8, cdy, _16b), _16b, _32), _32, fin); + + let det = estimate(finlen, fin); + let errbound = iccerrboundB * permanent; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - adx; + adxtail = ax - (adx + bvirt) + (bvirt - dx); + bvirt = ay - ady; + adytail = ay - (ady + bvirt) + (bvirt - dy); + bvirt = bx - bdx; + bdxtail = bx - (bdx + bvirt) + (bvirt - dx); + bvirt = by - bdy; + bdytail = by - (bdy + bvirt) + (bvirt - dy); + bvirt = cx - cdx; + cdxtail = cx - (cdx + bvirt) + (bvirt - dx); + bvirt = cy - cdy; + cdytail = cy - (cdy + bvirt) + (bvirt - dy); + if (adxtail === 0 && bdxtail === 0 && cdxtail === 0 && adytail === 0 && bdytail === 0 && cdytail === 0) { + return det; + } + + errbound = iccerrboundC * permanent + resulterrbound * Math.abs(det); + det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail) - (bdy * cdxtail + cdx * bdytail)) + + 2 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx)) + + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail) - (cdy * adxtail + adx * cdytail)) + + 2 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx)) + + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail) - (ady * bdxtail + bdx * adytail)) + + 2 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx)); + + if (det >= errbound || -det >= errbound) { + return det; + } + + if (bdxtail !== 0 || bdytail !== 0 || cdxtail !== 0 || cdytail !== 0) { + s1 = adx * adx; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo); + t1 = ady * ady; + c = splitter * ady; + ahi = c - (c - ady); + alo = ady - ahi; + t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo); + _i = s0 + t0; + bvirt = _i - s0; + aa[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + aa[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + aa[2] = _j - (u3 - bvirt) + (_i - bvirt); + aa[3] = u3; + } + if (cdxtail !== 0 || cdytail !== 0 || adxtail !== 0 || adytail !== 0) { + s1 = bdx * bdx; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo); + t1 = bdy * bdy; + c = splitter * bdy; + ahi = c - (c - bdy); + alo = bdy - ahi; + t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo); + _i = s0 + t0; + bvirt = _i - s0; + bb[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + bb[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + bb[2] = _j - (u3 - bvirt) + (_i - bvirt); + bb[3] = u3; + } + if (adxtail !== 0 || adytail !== 0 || bdxtail !== 0 || bdytail !== 0) { + s1 = cdx * cdx; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo); + t1 = cdy * cdy; + c = splitter * cdy; + ahi = c - (c - cdy); + alo = cdy - ahi; + t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo); + _i = s0 + t0; + bvirt = _i - s0; + cc[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + cc[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + cc[2] = _j - (u3 - bvirt) + (_i - bvirt); + cc[3] = u3; + } + + if (adxtail !== 0) { + axtbclen = scale(4, bc, adxtail, axtbc); + finlen = finadd(finlen, sum_three( + scale(axtbclen, axtbc, 2 * adx, _16), _16, + scale(scale(4, cc, adxtail, _8), _8, bdy, _16b), _16b, + scale(scale(4, bb, adxtail, _8), _8, -cdy, _16c), _16c, _32, _48), _48); + } + if (adytail !== 0) { + aytbclen = scale(4, bc, adytail, aytbc); + finlen = finadd(finlen, sum_three( + scale(aytbclen, aytbc, 2 * ady, _16), _16, + scale(scale(4, bb, adytail, _8), _8, cdx, _16b), _16b, + scale(scale(4, cc, adytail, _8), _8, -bdx, _16c), _16c, _32, _48), _48); + } + if (bdxtail !== 0) { + bxtcalen = scale(4, ca, bdxtail, bxtca); + finlen = finadd(finlen, sum_three( + scale(bxtcalen, bxtca, 2 * bdx, _16), _16, + scale(scale(4, aa, bdxtail, _8), _8, cdy, _16b), _16b, + scale(scale(4, cc, bdxtail, _8), _8, -ady, _16c), _16c, _32, _48), _48); + } + if (bdytail !== 0) { + bytcalen = scale(4, ca, bdytail, bytca); + finlen = finadd(finlen, sum_three( + scale(bytcalen, bytca, 2 * bdy, _16), _16, + scale(scale(4, cc, bdytail, _8), _8, adx, _16b), _16b, + scale(scale(4, aa, bdytail, _8), _8, -cdx, _16c), _16c, _32, _48), _48); + } + if (cdxtail !== 0) { + cxtablen = scale(4, ab, cdxtail, cxtab); + finlen = finadd(finlen, sum_three( + scale(cxtablen, cxtab, 2 * cdx, _16), _16, + scale(scale(4, bb, cdxtail, _8), _8, ady, _16b), _16b, + scale(scale(4, aa, cdxtail, _8), _8, -bdy, _16c), _16c, _32, _48), _48); + } + if (cdytail !== 0) { + cytablen = scale(4, ab, cdytail, cytab); + finlen = finadd(finlen, sum_three( + scale(cytablen, cytab, 2 * cdy, _16), _16, + scale(scale(4, aa, cdytail, _8), _8, bdx, _16b), _16b, + scale(scale(4, bb, cdytail, _8), _8, -adx, _16c), _16c, _32, _48), _48); + } + + if (adxtail !== 0 || adytail !== 0) { + if (bdxtail !== 0 || bdytail !== 0 || cdxtail !== 0 || cdytail !== 0) { + s1 = bdxtail * cdy; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * cdytail; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * cdytail; + bhi = c - (c - cdytail); + blo = cdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + u[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + u[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + s1 = cdxtail * -bdy; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * -bdy; + bhi = c - (c - -bdy); + blo = -bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * -bdytail; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * -bdytail; + bhi = c - (c - -bdytail); + blo = -bdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + v[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + v[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + v[2] = _j - (u3 - bvirt) + (_i - bvirt); + v[3] = u3; + bctlen = sum(4, u, 4, v, bct); + s1 = bdxtail * cdytail; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * cdytail; + bhi = c - (c - cdytail); + blo = cdytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdxtail * bdytail; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * bdytail; + bhi = c - (c - bdytail); + blo = bdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bctt[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bctt[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bctt[2] = _j - (u3 - bvirt) + (_i - bvirt); + bctt[3] = u3; + bcttlen = 4; + } else { + bct[0] = 0; + bctlen = 1; + bctt[0] = 0; + bcttlen = 1; + } + if (adxtail !== 0) { + const len = scale(bctlen, bct, adxtail, _16c); + finlen = finadd(finlen, sum( + scale(axtbclen, axtbc, adxtail, _16), _16, + scale(len, _16c, 2 * adx, _32), _32, _48), _48); + + const len2 = scale(bcttlen, bctt, adxtail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * adx, _16), _16, + scale(len2, _8, adxtail, _16b), _16b, + scale(len, _16c, adxtail, _32), _32, _32b, _64), _64); + + if (bdytail !== 0) { + finlen = finadd(finlen, scale(scale(4, cc, adxtail, _8), _8, bdytail, _16), _16); + } + if (cdytail !== 0) { + finlen = finadd(finlen, scale(scale(4, bb, -adxtail, _8), _8, cdytail, _16), _16); + } + } + if (adytail !== 0) { + const len = scale(bctlen, bct, adytail, _16c); + finlen = finadd(finlen, sum( + scale(aytbclen, aytbc, adytail, _16), _16, + scale(len, _16c, 2 * ady, _32), _32, _48), _48); + + const len2 = scale(bcttlen, bctt, adytail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * ady, _16), _16, + scale(len2, _8, adytail, _16b), _16b, + scale(len, _16c, adytail, _32), _32, _32b, _64), _64); + } + } + if (bdxtail !== 0 || bdytail !== 0) { + if (cdxtail !== 0 || cdytail !== 0 || adxtail !== 0 || adytail !== 0) { + s1 = cdxtail * ady; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * adytail; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * adytail; + bhi = c - (c - adytail); + blo = adytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + u[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + u[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + n1 = -cdy; + n0 = -cdytail; + s1 = adxtail * n1; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * n1; + bhi = c - (c - n1); + blo = n1 - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * n0; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * n0; + bhi = c - (c - n0); + blo = n0 - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + v[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + v[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + v[2] = _j - (u3 - bvirt) + (_i - bvirt); + v[3] = u3; + catlen = sum(4, u, 4, v, cat); + s1 = cdxtail * adytail; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * adytail; + bhi = c - (c - adytail); + blo = adytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adxtail * cdytail; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * cdytail; + bhi = c - (c - cdytail); + blo = cdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + catt[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + catt[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + catt[2] = _j - (u3 - bvirt) + (_i - bvirt); + catt[3] = u3; + cattlen = 4; + } else { + cat[0] = 0; + catlen = 1; + catt[0] = 0; + cattlen = 1; + } + if (bdxtail !== 0) { + const len = scale(catlen, cat, bdxtail, _16c); + finlen = finadd(finlen, sum( + scale(bxtcalen, bxtca, bdxtail, _16), _16, + scale(len, _16c, 2 * bdx, _32), _32, _48), _48); + + const len2 = scale(cattlen, catt, bdxtail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * bdx, _16), _16, + scale(len2, _8, bdxtail, _16b), _16b, + scale(len, _16c, bdxtail, _32), _32, _32b, _64), _64); + + if (cdytail !== 0) { + finlen = finadd(finlen, scale(scale(4, aa, bdxtail, _8), _8, cdytail, _16), _16); + } + if (adytail !== 0) { + finlen = finadd(finlen, scale(scale(4, cc, -bdxtail, _8), _8, adytail, _16), _16); + } + } + if (bdytail !== 0) { + const len = scale(catlen, cat, bdytail, _16c); + finlen = finadd(finlen, sum( + scale(bytcalen, bytca, bdytail, _16), _16, + scale(len, _16c, 2 * bdy, _32), _32, _48), _48); + + const len2 = scale(cattlen, catt, bdytail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * bdy, _16), _16, + scale(len2, _8, bdytail, _16b), _16b, + scale(len, _16c, bdytail, _32), _32, _32b, _64), _64); + } + } + if (cdxtail !== 0 || cdytail !== 0) { + if (adxtail !== 0 || adytail !== 0 || bdxtail !== 0 || bdytail !== 0) { + s1 = adxtail * bdy; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * bdytail; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * bdytail; + bhi = c - (c - bdytail); + blo = bdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + u[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + u[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + n1 = -ady; + n0 = -adytail; + s1 = bdxtail * n1; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * n1; + bhi = c - (c - n1); + blo = n1 - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * n0; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * n0; + bhi = c - (c - n0); + blo = n0 - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + v[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + v[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + v[2] = _j - (u3 - bvirt) + (_i - bvirt); + v[3] = u3; + abtlen = sum(4, u, 4, v, abt); + s1 = adxtail * bdytail; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * bdytail; + bhi = c - (c - bdytail); + blo = bdytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdxtail * adytail; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * adytail; + bhi = c - (c - adytail); + blo = adytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + abtt[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + abtt[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + abtt[2] = _j - (u3 - bvirt) + (_i - bvirt); + abtt[3] = u3; + abttlen = 4; + } else { + abt[0] = 0; + abtlen = 1; + abtt[0] = 0; + abttlen = 1; + } + if (cdxtail !== 0) { + const len = scale(abtlen, abt, cdxtail, _16c); + finlen = finadd(finlen, sum( + scale(cxtablen, cxtab, cdxtail, _16), _16, + scale(len, _16c, 2 * cdx, _32), _32, _48), _48); + + const len2 = scale(abttlen, abtt, cdxtail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * cdx, _16), _16, + scale(len2, _8, cdxtail, _16b), _16b, + scale(len, _16c, cdxtail, _32), _32, _32b, _64), _64); + + if (adytail !== 0) { + finlen = finadd(finlen, scale(scale(4, bb, cdxtail, _8), _8, adytail, _16), _16); + } + if (bdytail !== 0) { + finlen = finadd(finlen, scale(scale(4, aa, -cdxtail, _8), _8, bdytail, _16), _16); + } + } + if (cdytail !== 0) { + const len = scale(abtlen, abt, cdytail, _16c); + finlen = finadd(finlen, sum( + scale(cytablen, cytab, cdytail, _16), _16, + scale(len, _16c, 2 * cdy, _32), _32, _48), _48); + + const len2 = scale(abttlen, abtt, cdytail, _8); + finlen = finadd(finlen, sum_three( + scale(len2, _8, 2 * cdy, _16), _16, + scale(len2, _8, cdytail, _16b), _16b, + scale(len, _16c, cdytail, _32), _32, _32b, _64), _64); + } + } + + return fin[finlen - 1]; +} + +function incircle(ax, ay, bx, by, cx, cy, dx, dy) { + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + + const bdxcdy = bdx * cdy; + const cdxbdy = cdx * bdy; + const alift = adx * adx + ady * ady; + + const cdxady = cdx * ady; + const adxcdy = adx * cdy; + const blift = bdx * bdx + bdy * bdy; + + const adxbdy = adx * bdy; + const bdxady = bdx * ady; + const clift = cdx * cdx + cdy * cdy; + + const det = + alift * (bdxcdy - cdxbdy) + + blift * (cdxady - adxcdy) + + clift * (adxbdy - bdxady); + + const permanent = + (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * alift + + (Math.abs(cdxady) + Math.abs(adxcdy)) * blift + + (Math.abs(adxbdy) + Math.abs(bdxady)) * clift; + + const errbound = iccerrboundA * permanent; + + if (det > errbound || -det > errbound) { + return det; + } + return incircleadapt(ax, ay, bx, by, cx, cy, dx, dy, permanent); +} + +function incirclefast(ax, ay, bx, by, cx, cy, dx, dy) { + const adx = ax - dx; + const ady = ay - dy; + const bdx = bx - dx; + const bdy = by - dy; + const cdx = cx - dx; + const cdy = cy - dy; + + const abdet = adx * bdy - bdx * ady; + const bcdet = bdx * cdy - cdx * bdy; + const cadet = cdx * ady - adx * cdy; + const alift = adx * adx + ady * ady; + const blift = bdx * bdx + bdy * bdy; + const clift = cdx * cdx + cdy * cdy; + + return alift * bcdet + blift * cadet + clift * abdet; +} + +exports.incircle = incircle; +exports.incirclefast = incirclefast; + +Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/robust-predicates/umd/incircle.min.js b/node_modules/robust-predicates/umd/incircle.min.js new file mode 100644 index 0000000000000000000000000000000000000000..25990a4e9bffac2297f092ac7fe8d2a90bbc27a7 --- /dev/null +++ b/node_modules/robust-predicates/umd/incircle.min.js @@ -0,0 +1 @@ +!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t=t||self).predicates={})}(this,function(t){"use strict";const n=134217729,e=33306690738754706e-32;function o(t,n,e,o,f){let r,c,i,s,u=n[0],a=o[0],l=0,d=0;a>u==a>-u?(r=u,u=n[++l]):(r=a,a=o[++d]);let b=0;if(lu==a>-u?(i=r-((c=u+r)-u),u=n[++l]):(i=r-((c=a+r)-a),a=o[++d]),r=c,0!==i&&(f[b++]=i);lu==a>-u?(i=r-((c=r+u)-(s=c-r))+(u-s),u=n[++l]):(i=r-((c=r+a)-(s=c-r))+(a-s),a=o[++d]),r=c,0!==i&&(f[b++]=i);for(;lut||-it>ut?it:function(t,c,i,J,L,N,Q,R,S){let T,U,V,W,X,Y,Z,$,tt,nt,et,ot,ft,rt,ct,it,st,ut,at,lt,dt,bt,ht,pt,Mt,yt,xt,jt,mt,_t,vt,wt,At,Ft,Ot;const Pt=t-Q,gt=i-Q,kt=L-Q,qt=c-R,zt=J-R,Bt=N-R;bt=(wt=(Mt=gt-(pt=(ht=n*gt)-(ht-gt)))*(xt=Bt-(yt=(ht=n*Bt)-(ht-Bt)))-((vt=gt*Bt)-pt*yt-Mt*yt-pt*xt))-(jt=wt-(Ft=(Mt=kt-(pt=(ht=n*kt)-(ht-kt)))*(xt=zt-(yt=(ht=n*zt)-(ht-zt)))-((At=kt*zt)-pt*yt-Mt*yt-pt*xt))),a[0]=wt-(jt+bt)+(bt-Ft),bt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))-(jt=_t-At),a[1]=_t-(jt+bt)+(bt-At),bt=(Ot=mt+jt)-mt,a[2]=mt-(Ot-bt)+(jt-bt),a[3]=Ot,bt=(wt=(Mt=kt-(pt=(ht=n*kt)-(ht-kt)))*(xt=qt-(yt=(ht=n*qt)-(ht-qt)))-((vt=kt*qt)-pt*yt-Mt*yt-pt*xt))-(jt=wt-(Ft=(Mt=Pt-(pt=(ht=n*Pt)-(ht-Pt)))*(xt=Bt-(yt=(ht=n*Bt)-(ht-Bt)))-((At=Pt*Bt)-pt*yt-Mt*yt-pt*xt))),l[0]=wt-(jt+bt)+(bt-Ft),bt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))-(jt=_t-At),l[1]=_t-(jt+bt)+(bt-At),bt=(Ot=mt+jt)-mt,l[2]=mt-(Ot-bt)+(jt-bt),l[3]=Ot,bt=(wt=(Mt=Pt-(pt=(ht=n*Pt)-(ht-Pt)))*(xt=zt-(yt=(ht=n*zt)-(ht-zt)))-((vt=Pt*zt)-pt*yt-Mt*yt-pt*xt))-(jt=wt-(Ft=(Mt=gt-(pt=(ht=n*gt)-(ht-gt)))*(xt=qt-(yt=(ht=n*qt)-(ht-qt)))-((At=gt*qt)-pt*yt-Mt*yt-pt*xt))),d[0]=wt-(jt+bt)+(bt-Ft),bt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))-(jt=_t-At),d[1]=_t-(jt+bt)+(bt-At),bt=(Ot=mt+jt)-mt,d[2]=mt-(Ot-bt)+(jt-bt),d[3]=Ot;let Ct=function(t,n){let e=n[0];for(let o=1;o=Dt||-Ct>=Dt)return Ct;if(U=t-(Pt+(bt=t-Pt))+(bt-Q),X=c-(qt+(bt=c-qt))+(bt-R),V=i-(gt+(bt=i-gt))+(bt-Q),Y=J-(zt+(bt=J-zt))+(bt-R),W=L-(kt+(bt=L-kt))+(bt-Q),Z=N-(Bt+(bt=N-Bt))+(bt-R),0===U&&0===V&&0===W&&0===X&&0===Y&&0===Z)return Ct;if(Dt=u*S+e*Math.abs(Ct),(Ct+=(Pt*Pt+qt*qt)*(gt*Z+Bt*V-(zt*W+kt*Y))+2*(Pt*U+qt*X)*(gt*Bt-zt*kt)+((gt*gt+zt*zt)*(kt*X+qt*W-(Bt*U+Pt*Z))+2*(gt*V+zt*Y)*(kt*qt-Bt*Pt))+((kt*kt+Bt*Bt)*(Pt*Y+zt*U-(qt*V+gt*X))+2*(kt*W+Bt*Z)*(Pt*zt-qt*gt)))>=Dt||-Ct>=Dt)return Ct;if(0===V&&0===Y&&0===W&&0===Z||(bt=(jt=(wt=(Mt=Pt-(pt=(ht=n*Pt)-(ht-Pt)))*Mt-((vt=Pt*Pt)-pt*pt-(pt+pt)*Mt))+(Ft=(Mt=qt-(pt=(ht=n*qt)-(ht-qt)))*Mt-((At=qt*qt)-pt*pt-(pt+pt)*Mt)))-wt,b[0]=wt-(jt-bt)+(Ft-bt),bt=(jt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))+At)-_t,b[1]=_t-(jt-bt)+(At-bt),bt=(Ot=mt+jt)-mt,b[2]=mt-(Ot-bt)+(jt-bt),b[3]=Ot),0===W&&0===Z&&0===U&&0===X||(bt=(jt=(wt=(Mt=gt-(pt=(ht=n*gt)-(ht-gt)))*Mt-((vt=gt*gt)-pt*pt-(pt+pt)*Mt))+(Ft=(Mt=zt-(pt=(ht=n*zt)-(ht-zt)))*Mt-((At=zt*zt)-pt*pt-(pt+pt)*Mt)))-wt,h[0]=wt-(jt-bt)+(Ft-bt),bt=(jt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))+At)-_t,h[1]=_t-(jt-bt)+(At-bt),bt=(Ot=mt+jt)-mt,h[2]=mt-(Ot-bt)+(jt-bt),h[3]=Ot),0===U&&0===X&&0===V&&0===Y||(bt=(jt=(wt=(Mt=kt-(pt=(ht=n*kt)-(ht-kt)))*Mt-((vt=kt*kt)-pt*pt-(pt+pt)*Mt))+(Ft=(Mt=Bt-(pt=(ht=n*Bt)-(ht-Bt)))*Mt-((At=Bt*Bt)-pt*pt-(pt+pt)*Mt)))-wt,p[0]=wt-(jt-bt)+(Ft-bt),bt=(jt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))+At)-_t,p[1]=_t-(jt-bt)+(At-bt),bt=(Ot=mt+jt)-mt,p[2]=mt-(Ot-bt)+(jt-bt),p[3]=Ot),0!==U&&($=r(4,a,U,x),T=K(T,f(r($,x,2*Pt,z),z,r(r(4,p,U,q),q,zt,B),B,r(r(4,h,U,q),q,-Bt,C),C,D,G),G)),0!==X&&(tt=r(4,a,X,j),T=K(T,f(r(tt,j,2*qt,z),z,r(r(4,h,X,q),q,kt,B),B,r(r(4,p,X,q),q,-gt,C),C,D,G),G)),0!==V&&(nt=r(4,l,V,m),T=K(T,f(r(nt,m,2*gt,z),z,r(r(4,b,V,q),q,Bt,B),B,r(r(4,p,V,q),q,-qt,C),C,D,G),G)),0!==Y&&(et=r(4,l,Y,_),T=K(T,f(r(et,_,2*zt,z),z,r(r(4,p,Y,q),q,Pt,B),B,r(r(4,b,Y,q),q,-kt,C),C,D,G),G)),0!==W&&(ot=r(4,d,W,v),T=K(T,f(r(ot,v,2*kt,z),z,r(r(4,h,W,q),q,qt,B),B,r(r(4,b,W,q),q,-zt,C),C,D,G),G)),0!==Z&&(ft=r(4,d,Z,w),T=K(T,f(r(ft,w,2*Bt,z),z,r(r(4,b,Z,q),q,gt,B),B,r(r(4,h,Z,q),q,-Pt,C),C,D,G),G)),0!==U||0!==X){if(0!==V||0!==Y||0!==W||0!==Z?(bt=(jt=(wt=(Mt=V-(pt=(ht=n*V)-(ht-V)))*(xt=Bt-(yt=(ht=n*Bt)-(ht-Bt)))-((vt=V*Bt)-pt*yt-Mt*yt-pt*xt))+(Ft=(Mt=gt-(pt=(ht=n*gt)-(ht-gt)))*(xt=Z-(yt=(ht=n*Z)-(ht-Z)))-((At=gt*Z)-pt*yt-Mt*yt-pt*xt)))-wt,M[0]=wt-(jt-bt)+(Ft-bt),bt=(jt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))+At)-_t,M[1]=_t-(jt-bt)+(At-bt),bt=(Ot=mt+jt)-mt,M[2]=mt-(Ot-bt)+(jt-bt),M[3]=Ot,bt=(jt=(wt=(Mt=W-(pt=(ht=n*W)-(ht-W)))*(xt=-zt-(yt=(ht=n*-zt)-(ht- -zt)))-((vt=W*-zt)-pt*yt-Mt*yt-pt*xt))+(Ft=(Mt=kt-(pt=(ht=n*kt)-(ht-kt)))*(xt=-Y-(yt=(ht=n*-Y)-(ht- -Y)))-((At=kt*-Y)-pt*yt-Mt*yt-pt*xt)))-wt,y[0]=wt-(jt-bt)+(Ft-bt),bt=(jt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))+At)-_t,y[1]=_t-(jt-bt)+(At-bt),bt=(Ot=mt+jt)-mt,y[2]=mt-(Ot-bt)+(jt-bt),y[3]=Ot,ct=o(4,M,4,y,F),bt=(wt=(Mt=V-(pt=(ht=n*V)-(ht-V)))*(xt=Z-(yt=(ht=n*Z)-(ht-Z)))-((vt=V*Z)-pt*yt-Mt*yt-pt*xt))-(jt=wt-(Ft=(Mt=W-(pt=(ht=n*W)-(ht-W)))*(xt=Y-(yt=(ht=n*Y)-(ht-Y)))-((At=W*Y)-pt*yt-Mt*yt-pt*xt))),g[0]=wt-(jt+bt)+(bt-Ft),bt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))-(jt=_t-At),g[1]=_t-(jt+bt)+(bt-At),bt=(Ot=mt+jt)-mt,g[2]=mt-(Ot-bt)+(jt-bt),g[3]=Ot,ut=4):(F[0]=0,ct=1,g[0]=0,ut=1),0!==U){const t=r(ct,F,U,C);T=K(T,o(r($,x,U,z),z,r(t,C,2*Pt,D),D,G),G);const n=r(ut,g,U,q);T=K(T,f(r(n,q,2*Pt,z),z,r(n,q,U,B),B,r(t,C,U,D),D,E,H),H),0!==Y&&(T=K(T,r(r(4,p,U,q),q,Y,z),z)),0!==Z&&(T=K(T,r(r(4,h,-U,q),q,Z,z),z))}if(0!==X){const t=r(ct,F,X,C);T=K(T,o(r(tt,j,X,z),z,r(t,C,2*qt,D),D,G),G);const n=r(ut,g,X,q);T=K(T,f(r(n,q,2*qt,z),z,r(n,q,X,B),B,r(t,C,X,D),D,E,H),H)}}if(0!==V||0!==Y){if(0!==W||0!==Z||0!==U||0!==X?(bt=(jt=(wt=(Mt=W-(pt=(ht=n*W)-(ht-W)))*(xt=qt-(yt=(ht=n*qt)-(ht-qt)))-((vt=W*qt)-pt*yt-Mt*yt-pt*xt))+(Ft=(Mt=kt-(pt=(ht=n*kt)-(ht-kt)))*(xt=X-(yt=(ht=n*X)-(ht-X)))-((At=kt*X)-pt*yt-Mt*yt-pt*xt)))-wt,M[0]=wt-(jt-bt)+(Ft-bt),bt=(jt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))+At)-_t,M[1]=_t-(jt-bt)+(At-bt),bt=(Ot=mt+jt)-mt,M[2]=mt-(Ot-bt)+(jt-bt),M[3]=Ot,bt=(jt=(wt=(Mt=U-(pt=(ht=n*U)-(ht-U)))*(xt=(lt=-Bt)-(yt=(ht=n*lt)-(ht-lt)))-((vt=U*lt)-pt*yt-Mt*yt-pt*xt))+(Ft=(Mt=Pt-(pt=(ht=n*Pt)-(ht-Pt)))*(xt=(dt=-Z)-(yt=(ht=n*dt)-(ht-dt)))-((At=Pt*dt)-pt*yt-Mt*yt-pt*xt)))-wt,y[0]=wt-(jt-bt)+(Ft-bt),bt=(jt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))+At)-_t,y[1]=_t-(jt-bt)+(At-bt),bt=(Ot=mt+jt)-mt,y[2]=mt-(Ot-bt)+(jt-bt),y[3]=Ot,it=o(4,M,4,y,O),bt=(wt=(Mt=W-(pt=(ht=n*W)-(ht-W)))*(xt=X-(yt=(ht=n*X)-(ht-X)))-((vt=W*X)-pt*yt-Mt*yt-pt*xt))-(jt=wt-(Ft=(Mt=U-(pt=(ht=n*U)-(ht-U)))*(xt=Z-(yt=(ht=n*Z)-(ht-Z)))-((At=U*Z)-pt*yt-Mt*yt-pt*xt))),k[0]=wt-(jt+bt)+(bt-Ft),bt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))-(jt=_t-At),k[1]=_t-(jt+bt)+(bt-At),bt=(Ot=mt+jt)-mt,k[2]=mt-(Ot-bt)+(jt-bt),k[3]=Ot,at=4):(O[0]=0,it=1,k[0]=0,at=1),0!==V){const t=r(it,O,V,C);T=K(T,o(r(nt,m,V,z),z,r(t,C,2*gt,D),D,G),G);const n=r(at,k,V,q);T=K(T,f(r(n,q,2*gt,z),z,r(n,q,V,B),B,r(t,C,V,D),D,E,H),H),0!==Z&&(T=K(T,r(r(4,b,V,q),q,Z,z),z)),0!==X&&(T=K(T,r(r(4,p,-V,q),q,X,z),z))}if(0!==Y){const t=r(it,O,Y,C);T=K(T,o(r(et,_,Y,z),z,r(t,C,2*zt,D),D,G),G);const n=r(at,k,Y,q);T=K(T,f(r(n,q,2*zt,z),z,r(n,q,Y,B),B,r(t,C,Y,D),D,E,H),H)}}if(0!==W||0!==Z){if(0!==U||0!==X||0!==V||0!==Y?(bt=(jt=(wt=(Mt=U-(pt=(ht=n*U)-(ht-U)))*(xt=zt-(yt=(ht=n*zt)-(ht-zt)))-((vt=U*zt)-pt*yt-Mt*yt-pt*xt))+(Ft=(Mt=Pt-(pt=(ht=n*Pt)-(ht-Pt)))*(xt=Y-(yt=(ht=n*Y)-(ht-Y)))-((At=Pt*Y)-pt*yt-Mt*yt-pt*xt)))-wt,M[0]=wt-(jt-bt)+(Ft-bt),bt=(jt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))+At)-_t,M[1]=_t-(jt-bt)+(At-bt),bt=(Ot=mt+jt)-mt,M[2]=mt-(Ot-bt)+(jt-bt),M[3]=Ot,bt=(jt=(wt=(Mt=V-(pt=(ht=n*V)-(ht-V)))*(xt=(lt=-qt)-(yt=(ht=n*lt)-(ht-lt)))-((vt=V*lt)-pt*yt-Mt*yt-pt*xt))+(Ft=(Mt=gt-(pt=(ht=n*gt)-(ht-gt)))*(xt=(dt=-X)-(yt=(ht=n*dt)-(ht-dt)))-((At=gt*dt)-pt*yt-Mt*yt-pt*xt)))-wt,y[0]=wt-(jt-bt)+(Ft-bt),bt=(jt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))+At)-_t,y[1]=_t-(jt-bt)+(At-bt),bt=(Ot=mt+jt)-mt,y[2]=mt-(Ot-bt)+(jt-bt),y[3]=Ot,rt=o(4,M,4,y,A),bt=(wt=(Mt=U-(pt=(ht=n*U)-(ht-U)))*(xt=Y-(yt=(ht=n*Y)-(ht-Y)))-((vt=U*Y)-pt*yt-Mt*yt-pt*xt))-(jt=wt-(Ft=(Mt=V-(pt=(ht=n*V)-(ht-V)))*(xt=X-(yt=(ht=n*X)-(ht-X)))-((At=V*X)-pt*yt-Mt*yt-pt*xt))),P[0]=wt-(jt+bt)+(bt-Ft),bt=(_t=vt-((mt=vt+jt)-(bt=mt-vt))+(jt-bt))-(jt=_t-At),P[1]=_t-(jt+bt)+(bt-At),bt=(Ot=mt+jt)-mt,P[2]=mt-(Ot-bt)+(jt-bt),P[3]=Ot,st=4):(A[0]=0,rt=1,P[0]=0,st=1),0!==W){const t=r(rt,A,W,C);T=K(T,o(r(ot,v,W,z),z,r(t,C,2*kt,D),D,G),G);const n=r(st,P,W,q);T=K(T,f(r(n,q,2*kt,z),z,r(n,q,W,B),B,r(t,C,W,D),D,E,H),H),0!==X&&(T=K(T,r(r(4,h,W,q),q,X,z),z)),0!==Y&&(T=K(T,r(r(4,b,-W,q),q,Y,z),z))}if(0!==Z){const t=r(rt,A,Z,C);T=K(T,o(r(ft,w,Z,z),z,r(t,C,2*Bt,D),D,G),G);const n=r(st,P,Z,q);T=K(T,f(r(n,q,2*Bt,z),z,r(n,q,Z,B),B,r(t,C,Z,D),D,E,H),H)}}return I[T-1]}(t,c,J,L,N,Q,R,S,st)},t.incirclefast=function(t,n,e,o,f,r,c,i){const s=t-c,u=n-i,a=e-c,l=o-i,d=f-c,b=r-i;return(s*s+u*u)*(a*b-d*l)+(a*a+l*l)*(d*u-s*b)+(d*d+b*b)*(s*l-a*u)},Object.defineProperty(t,"__esModule",{value:!0})}); diff --git a/node_modules/robust-predicates/umd/insphere.js b/node_modules/robust-predicates/umd/insphere.js new file mode 100644 index 0000000000000000000000000000000000000000..52feb8104217cc435abaaaae72a3afa64059ae63 --- /dev/null +++ b/node_modules/robust-predicates/umd/insphere.js @@ -0,0 +1,925 @@ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : +typeof define === 'function' && define.amd ? define(['exports'], factory) : +(global = global || self, factory(global.predicates = {})); +}(this, function (exports) { 'use strict'; + +const epsilon = 1.1102230246251565e-16; +const splitter = 134217729; +const resulterrbound = (3 + 8 * epsilon) * epsilon; + +// fast_expansion_sum_zeroelim routine from oritinal code +function sum(elen, e, flen, f, h) { + let Q, Qnew, hh, bvirt; + let enow = e[0]; + let fnow = f[0]; + let eindex = 0; + let findex = 0; + if ((fnow > enow) === (fnow > -enow)) { + Q = enow; + enow = e[++eindex]; + } else { + Q = fnow; + fnow = f[++findex]; + } + let hindex = 0; + if (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = enow + Q; + hh = Q - (Qnew - enow); + enow = e[++eindex]; + } else { + Qnew = fnow + Q; + hh = Q - (Qnew - fnow); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + while (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + } else { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + } + while (eindex < elen) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + while (findex < flen) { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +function sum_three(alen, a, blen, b, clen, c, tmp, out) { + return sum(sum(alen, a, blen, b, tmp), tmp, clen, c, out); +} + +// scale_expansion_zeroelim routine from oritinal code +function scale(elen, e, b, h) { + let Q, sum, hh, product1, product0; + let bvirt, c, ahi, alo, bhi, blo; + + c = splitter * b; + bhi = c - (c - b); + blo = b - bhi; + let enow = e[0]; + Q = enow * b; + c = splitter * enow; + ahi = c - (c - enow); + alo = enow - ahi; + hh = alo * blo - (Q - ahi * bhi - alo * bhi - ahi * blo); + let hindex = 0; + if (hh !== 0) { + h[hindex++] = hh; + } + for (let i = 1; i < elen; i++) { + enow = e[i]; + product1 = enow * b; + c = splitter * enow; + ahi = c - (c - enow); + alo = enow - ahi; + product0 = alo * blo - (product1 - ahi * bhi - alo * bhi - ahi * blo); + sum = Q + product0; + bvirt = sum - Q; + hh = Q - (sum - bvirt) + (product0 - bvirt); + if (hh !== 0) { + h[hindex++] = hh; + } + Q = product1 + sum; + hh = sum - (Q - product1); + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +function negate(elen, e) { + for (let i = 0; i < elen; i++) e[i] = -e[i]; + return elen; +} + +function estimate(elen, e) { + let Q = e[0]; + for (let i = 1; i < elen; i++) Q += e[i]; + return Q; +} + +function vec(n) { + return new Float64Array(n); +} + +const isperrboundA = (16 + 224 * epsilon) * epsilon; +const isperrboundB = (5 + 72 * epsilon) * epsilon; +const isperrboundC = (71 + 1408 * epsilon) * epsilon * epsilon; + +const ab = vec(4); +const bc = vec(4); +const cd = vec(4); +const de = vec(4); +const ea = vec(4); +const ac = vec(4); +const bd = vec(4); +const ce = vec(4); +const da = vec(4); +const eb = vec(4); + +const abc = vec(24); +const bcd = vec(24); +const cde = vec(24); +const dea = vec(24); +const eab = vec(24); +const abd = vec(24); +const bce = vec(24); +const cda = vec(24); +const deb = vec(24); +const eac = vec(24); + +const adet = vec(1152); +const bdet = vec(1152); +const cdet = vec(1152); +const ddet = vec(1152); +const edet = vec(1152); +const abdet = vec(2304); +const cddet = vec(2304); +const cdedet = vec(3456); +const deter = vec(5760); + +const _8 = vec(8); +const _8b = vec(8); +const _8c = vec(8); +const _16 = vec(16); +const _24 = vec(24); +const _48 = vec(48); +const _48b = vec(48); +const _96 = vec(96); +const _192 = vec(192); +const _384x = vec(384); +const _384y = vec(384); +const _384z = vec(384); +const _768 = vec(768); + +function sum_three_scale(a, b, c, az, bz, cz, out) { + return sum_three( + scale(4, a, az, _8), _8, + scale(4, b, bz, _8b), _8b, + scale(4, c, cz, _8c), _8c, _16, out); +} + +function liftexact(alen, a, blen, b, clen, c, dlen, d, x, y, z, out) { + const len = sum( + sum(alen, a, blen, b, _48), _48, + negate(sum(clen, c, dlen, d, _48b), _48b), _48b, _96); + + return sum_three( + scale(scale(len, _96, x, _192), _192, x, _384x), _384x, + scale(scale(len, _96, y, _192), _192, y, _384y), _384y, + scale(scale(len, _96, z, _192), _192, z, _384z), _384z, _768, out); +} + +function insphereexact(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez) { + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + s1 = ax * by; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bx * ay; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ab[2] = _j - (u3 - bvirt) + (_i - bvirt); + ab[3] = u3; + s1 = bx * cy; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cx * by; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bc[2] = _j - (u3 - bvirt) + (_i - bvirt); + bc[3] = u3; + s1 = cx * dy; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dx * cy; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + cd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + cd[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + cd[2] = _j - (u3 - bvirt) + (_i - bvirt); + cd[3] = u3; + s1 = dx * ey; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ex * dy; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + de[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + de[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + de[2] = _j - (u3 - bvirt) + (_i - bvirt); + de[3] = u3; + s1 = ex * ay; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ax * ey; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ea[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ea[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ea[2] = _j - (u3 - bvirt) + (_i - bvirt); + ea[3] = u3; + s1 = ax * cy; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cx * ay; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ac[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ac[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ac[2] = _j - (u3 - bvirt) + (_i - bvirt); + ac[3] = u3; + s1 = bx * dy; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dx * by; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bd[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bd[2] = _j - (u3 - bvirt) + (_i - bvirt); + bd[3] = u3; + s1 = cx * ey; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ex * cy; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ce[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ce[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ce[2] = _j - (u3 - bvirt) + (_i - bvirt); + ce[3] = u3; + s1 = dx * ay; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ax * dy; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + da[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + da[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + da[2] = _j - (u3 - bvirt) + (_i - bvirt); + da[3] = u3; + s1 = ex * by; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bx * ey; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + eb[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + eb[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + eb[2] = _j - (u3 - bvirt) + (_i - bvirt); + eb[3] = u3; + + const abclen = sum_three_scale(ab, bc, ac, cz, az, -bz, abc); + const bcdlen = sum_three_scale(bc, cd, bd, dz, bz, -cz, bcd); + const cdelen = sum_three_scale(cd, de, ce, ez, cz, -dz, cde); + const dealen = sum_three_scale(de, ea, da, az, dz, -ez, dea); + const eablen = sum_three_scale(ea, ab, eb, bz, ez, -az, eab); + const abdlen = sum_three_scale(ab, bd, da, dz, az, bz, abd); + const bcelen = sum_three_scale(bc, ce, eb, ez, bz, cz, bce); + const cdalen = sum_three_scale(cd, da, ac, az, cz, dz, cda); + const deblen = sum_three_scale(de, eb, bd, bz, dz, ez, deb); + const eaclen = sum_three_scale(ea, ac, ce, cz, ez, az, eac); + + const deterlen = sum_three( + liftexact(cdelen, cde, bcelen, bce, deblen, deb, bcdlen, bcd, ax, ay, az, adet), adet, + liftexact(dealen, dea, cdalen, cda, eaclen, eac, cdelen, cde, bx, by, bz, bdet), bdet, + sum_three( + liftexact(eablen, eab, deblen, deb, abdlen, abd, dealen, dea, cx, cy, cz, cdet), cdet, + liftexact(abclen, abc, eaclen, eac, bcelen, bce, eablen, eab, dx, dy, dz, ddet), ddet, + liftexact(bcdlen, bcd, abdlen, abd, cdalen, cda, abclen, abc, ex, ey, ez, edet), edet, cddet, cdedet), cdedet, abdet, deter); + + return deter[deterlen - 1]; +} + +const xdet = vec(96); +const ydet = vec(96); +const zdet = vec(96); +const fin = vec(1152); + +function liftadapt(a, b, c, az, bz, cz, x, y, z, out) { + const len = sum_three_scale(a, b, c, az, bz, cz, _24); + return sum_three( + scale(scale(len, _24, x, _48), _48, x, xdet), xdet, + scale(scale(len, _24, y, _48), _48, y, ydet), ydet, + scale(scale(len, _24, z, _48), _48, z, zdet), zdet, _192, out); +} + +function insphereadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez, permanent) { + let ab3, bc3, cd3, da3, ac3, bd3; + + let aextail, bextail, cextail, dextail; + let aeytail, beytail, ceytail, deytail; + let aeztail, beztail, ceztail, deztail; + + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0; + + const aex = ax - ex; + const bex = bx - ex; + const cex = cx - ex; + const dex = dx - ex; + const aey = ay - ey; + const bey = by - ey; + const cey = cy - ey; + const dey = dy - ey; + const aez = az - ez; + const bez = bz - ez; + const cez = cz - ez; + const dez = dz - ez; + + s1 = aex * bey; + c = splitter * aex; + ahi = c - (c - aex); + alo = aex - ahi; + c = splitter * bey; + bhi = c - (c - bey); + blo = bey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bex * aey; + c = splitter * bex; + ahi = c - (c - bex); + alo = bex - ahi; + c = splitter * aey; + bhi = c - (c - aey); + blo = aey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab[1] = _0 - (_i + bvirt) + (bvirt - t1); + ab3 = _j + _i; + bvirt = ab3 - _j; + ab[2] = _j - (ab3 - bvirt) + (_i - bvirt); + ab[3] = ab3; + s1 = bex * cey; + c = splitter * bex; + ahi = c - (c - bex); + alo = bex - ahi; + c = splitter * cey; + bhi = c - (c - cey); + blo = cey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cex * bey; + c = splitter * cex; + ahi = c - (c - cex); + alo = cex - ahi; + c = splitter * bey; + bhi = c - (c - bey); + blo = bey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc[1] = _0 - (_i + bvirt) + (bvirt - t1); + bc3 = _j + _i; + bvirt = bc3 - _j; + bc[2] = _j - (bc3 - bvirt) + (_i - bvirt); + bc[3] = bc3; + s1 = cex * dey; + c = splitter * cex; + ahi = c - (c - cex); + alo = cex - ahi; + c = splitter * dey; + bhi = c - (c - dey); + blo = dey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dex * cey; + c = splitter * dex; + ahi = c - (c - dex); + alo = dex - ahi; + c = splitter * cey; + bhi = c - (c - cey); + blo = cey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + cd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + cd[1] = _0 - (_i + bvirt) + (bvirt - t1); + cd3 = _j + _i; + bvirt = cd3 - _j; + cd[2] = _j - (cd3 - bvirt) + (_i - bvirt); + cd[3] = cd3; + s1 = dex * aey; + c = splitter * dex; + ahi = c - (c - dex); + alo = dex - ahi; + c = splitter * aey; + bhi = c - (c - aey); + blo = aey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = aex * dey; + c = splitter * aex; + ahi = c - (c - aex); + alo = aex - ahi; + c = splitter * dey; + bhi = c - (c - dey); + blo = dey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + da[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + da[1] = _0 - (_i + bvirt) + (bvirt - t1); + da3 = _j + _i; + bvirt = da3 - _j; + da[2] = _j - (da3 - bvirt) + (_i - bvirt); + da[3] = da3; + s1 = aex * cey; + c = splitter * aex; + ahi = c - (c - aex); + alo = aex - ahi; + c = splitter * cey; + bhi = c - (c - cey); + blo = cey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cex * aey; + c = splitter * cex; + ahi = c - (c - cex); + alo = cex - ahi; + c = splitter * aey; + bhi = c - (c - aey); + blo = aey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ac[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ac[1] = _0 - (_i + bvirt) + (bvirt - t1); + ac3 = _j + _i; + bvirt = ac3 - _j; + ac[2] = _j - (ac3 - bvirt) + (_i - bvirt); + ac[3] = ac3; + s1 = bex * dey; + c = splitter * bex; + ahi = c - (c - bex); + alo = bex - ahi; + c = splitter * dey; + bhi = c - (c - dey); + blo = dey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dex * bey; + c = splitter * dex; + ahi = c - (c - dex); + alo = dex - ahi; + c = splitter * bey; + bhi = c - (c - bey); + blo = bey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bd[1] = _0 - (_i + bvirt) + (bvirt - t1); + bd3 = _j + _i; + bvirt = bd3 - _j; + bd[2] = _j - (bd3 - bvirt) + (_i - bvirt); + bd[3] = bd3; + + const finlen = sum( + sum( + negate(liftadapt(bc, cd, bd, dez, bez, -cez, aex, aey, aez, adet), adet), adet, + liftadapt(cd, da, ac, aez, cez, dez, bex, bey, bez, bdet), bdet, abdet), abdet, + sum( + negate(liftadapt(da, ab, bd, bez, dez, aez, cex, cey, cez, cdet), cdet), cdet, + liftadapt(ab, bc, ac, cez, aez, -bez, dex, dey, dez, ddet), ddet, cddet), cddet, fin); + + let det = estimate(finlen, fin); + let errbound = isperrboundB * permanent; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - aex; + aextail = ax - (aex + bvirt) + (bvirt - ex); + bvirt = ay - aey; + aeytail = ay - (aey + bvirt) + (bvirt - ey); + bvirt = az - aez; + aeztail = az - (aez + bvirt) + (bvirt - ez); + bvirt = bx - bex; + bextail = bx - (bex + bvirt) + (bvirt - ex); + bvirt = by - bey; + beytail = by - (bey + bvirt) + (bvirt - ey); + bvirt = bz - bez; + beztail = bz - (bez + bvirt) + (bvirt - ez); + bvirt = cx - cex; + cextail = cx - (cex + bvirt) + (bvirt - ex); + bvirt = cy - cey; + ceytail = cy - (cey + bvirt) + (bvirt - ey); + bvirt = cz - cez; + ceztail = cz - (cez + bvirt) + (bvirt - ez); + bvirt = dx - dex; + dextail = dx - (dex + bvirt) + (bvirt - ex); + bvirt = dy - dey; + deytail = dy - (dey + bvirt) + (bvirt - ey); + bvirt = dz - dez; + deztail = dz - (dez + bvirt) + (bvirt - ez); + if (aextail === 0 && aeytail === 0 && aeztail === 0 && + bextail === 0 && beytail === 0 && beztail === 0 && + cextail === 0 && ceytail === 0 && ceztail === 0 && + dextail === 0 && deytail === 0 && deztail === 0) { + return det; + } + + errbound = isperrboundC * permanent + resulterrbound * Math.abs(det); + + const abeps = (aex * beytail + bey * aextail) - (aey * bextail + bex * aeytail); + const bceps = (bex * ceytail + cey * bextail) - (bey * cextail + cex * beytail); + const cdeps = (cex * deytail + dey * cextail) - (cey * dextail + dex * ceytail); + const daeps = (dex * aeytail + aey * dextail) - (dey * aextail + aex * deytail); + const aceps = (aex * ceytail + cey * aextail) - (aey * cextail + cex * aeytail); + const bdeps = (bex * deytail + dey * bextail) - (bey * dextail + dex * beytail); + det += + (((bex * bex + bey * bey + bez * bez) * ((cez * daeps + dez * aceps + aez * cdeps) + + (ceztail * da3 + deztail * ac3 + aeztail * cd3)) + (dex * dex + dey * dey + dez * dez) * + ((aez * bceps - bez * aceps + cez * abeps) + (aeztail * bc3 - beztail * ac3 + ceztail * ab3))) - + ((aex * aex + aey * aey + aez * aez) * ((bez * cdeps - cez * bdeps + dez * bceps) + + (beztail * cd3 - ceztail * bd3 + deztail * bc3)) + (cex * cex + cey * cey + cez * cez) * + ((dez * abeps + aez * bdeps + bez * daeps) + (deztail * ab3 + aeztail * bd3 + beztail * da3)))) + + 2 * (((bex * bextail + bey * beytail + bez * beztail) * (cez * da3 + dez * ac3 + aez * cd3) + + (dex * dextail + dey * deytail + dez * deztail) * (aez * bc3 - bez * ac3 + cez * ab3)) - + ((aex * aextail + aey * aeytail + aez * aeztail) * (bez * cd3 - cez * bd3 + dez * bc3) + + (cex * cextail + cey * ceytail + cez * ceztail) * (dez * ab3 + aez * bd3 + bez * da3))); + + if (det >= errbound || -det >= errbound) { + return det; + } + + return insphereexact(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez); +} + +function insphere(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez) { + const aex = ax - ex; + const bex = bx - ex; + const cex = cx - ex; + const dex = dx - ex; + const aey = ay - ey; + const bey = by - ey; + const cey = cy - ey; + const dey = dy - ey; + const aez = az - ez; + const bez = bz - ez; + const cez = cz - ez; + const dez = dz - ez; + + const aexbey = aex * bey; + const bexaey = bex * aey; + const ab = aexbey - bexaey; + const bexcey = bex * cey; + const cexbey = cex * bey; + const bc = bexcey - cexbey; + const cexdey = cex * dey; + const dexcey = dex * cey; + const cd = cexdey - dexcey; + const dexaey = dex * aey; + const aexdey = aex * dey; + const da = dexaey - aexdey; + const aexcey = aex * cey; + const cexaey = cex * aey; + const ac = aexcey - cexaey; + const bexdey = bex * dey; + const dexbey = dex * bey; + const bd = bexdey - dexbey; + + const abc = aez * bc - bez * ac + cez * ab; + const bcd = bez * cd - cez * bd + dez * bc; + const cda = cez * da + dez * ac + aez * cd; + const dab = dez * ab + aez * bd + bez * da; + + const alift = aex * aex + aey * aey + aez * aez; + const blift = bex * bex + bey * bey + bez * bez; + const clift = cex * cex + cey * cey + cez * cez; + const dlift = dex * dex + dey * dey + dez * dez; + + const det = (clift * dab - dlift * abc) + (alift * bcd - blift * cda); + + const aezplus = Math.abs(aez); + const bezplus = Math.abs(bez); + const cezplus = Math.abs(cez); + const dezplus = Math.abs(dez); + const aexbeyplus = Math.abs(aexbey); + const bexaeyplus = Math.abs(bexaey); + const bexceyplus = Math.abs(bexcey); + const cexbeyplus = Math.abs(cexbey); + const cexdeyplus = Math.abs(cexdey); + const dexceyplus = Math.abs(dexcey); + const dexaeyplus = Math.abs(dexaey); + const aexdeyplus = Math.abs(aexdey); + const aexceyplus = Math.abs(aexcey); + const cexaeyplus = Math.abs(cexaey); + const bexdeyplus = Math.abs(bexdey); + const dexbeyplus = Math.abs(dexbey); + const permanent = + ((cexdeyplus + dexceyplus) * bezplus + (dexbeyplus + bexdeyplus) * cezplus + (bexceyplus + cexbeyplus) * dezplus) * alift + + ((dexaeyplus + aexdeyplus) * cezplus + (aexceyplus + cexaeyplus) * dezplus + (cexdeyplus + dexceyplus) * aezplus) * blift + + ((aexbeyplus + bexaeyplus) * dezplus + (bexdeyplus + dexbeyplus) * aezplus + (dexaeyplus + aexdeyplus) * bezplus) * clift + + ((bexceyplus + cexbeyplus) * aezplus + (cexaeyplus + aexceyplus) * bezplus + (aexbeyplus + bexaeyplus) * cezplus) * dlift; + + const errbound = isperrboundA * permanent; + if (det > errbound || -det > errbound) { + return det; + } + return -insphereadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez, permanent); +} + +function inspherefast(pax, pay, paz, pbx, pby, pbz, pcx, pcy, pcz, pdx, pdy, pdz, pex, pey, pez) { + const aex = pax - pex; + const bex = pbx - pex; + const cex = pcx - pex; + const dex = pdx - pex; + const aey = pay - pey; + const bey = pby - pey; + const cey = pcy - pey; + const dey = pdy - pey; + const aez = paz - pez; + const bez = pbz - pez; + const cez = pcz - pez; + const dez = pdz - pez; + + const ab = aex * bey - bex * aey; + const bc = bex * cey - cex * bey; + const cd = cex * dey - dex * cey; + const da = dex * aey - aex * dey; + const ac = aex * cey - cex * aey; + const bd = bex * dey - dex * bey; + + const abc = aez * bc - bez * ac + cez * ab; + const bcd = bez * cd - cez * bd + dez * bc; + const cda = cez * da + dez * ac + aez * cd; + const dab = dez * ab + aez * bd + bez * da; + + const alift = aex * aex + aey * aey + aez * aez; + const blift = bex * bex + bey * bey + bez * bez; + const clift = cex * cex + cey * cey + cez * cez; + const dlift = dex * dex + dey * dey + dez * dez; + + return (clift * dab - dlift * abc) + (alift * bcd - blift * cda); +} + +exports.insphere = insphere; +exports.inspherefast = inspherefast; + +Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/robust-predicates/umd/insphere.min.js b/node_modules/robust-predicates/umd/insphere.min.js new file mode 100644 index 0000000000000000000000000000000000000000..faf4cc52c18f40635cc40f2c915c07393c0f1dec --- /dev/null +++ b/node_modules/robust-predicates/umd/insphere.min.js @@ -0,0 +1 @@ +!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t=t||self).predicates={})}(this,function(t){"use strict";const n=134217729,e=33306690738754706e-32;function r(t,n,e,r,o){let a,s,u,f,c=n[0],i=r[0],h=0,b=0;i>c==i>-c?(a=c,c=n[++h]):(a=i,i=r[++b]);let M=0;if(hc==i>-c?(u=a-((s=c+a)-c),c=n[++h]):(u=a-((s=i+a)-i),i=r[++b]),a=s,0!==u&&(o[M++]=u);hc==i>-c?(u=a-((s=a+c)-(f=s-a))+(c-f),c=n[++h]):(u=a-((s=a+i)-(f=s-a))+(i-f),i=r[++b]),a=s,0!==u&&(o[M++]=u);for(;h=Tt||-St>=Tt)return St;if(ft=t-(Ct+(mt=t-Ct))+(mt-V),bt=a-(Ht+(mt=a-Ht))+(mt-W),pt=u-(Lt+(mt=u-Lt))+(mt-X),ct=f-(Dt+(mt=f-Dt))+(mt-V),Mt=K-(It+(mt=K-It))+(mt-W),yt=L-(Nt+(mt=L-Nt))+(mt-X),it=N-(Et+(mt=N-Et))+(mt-V),lt=Q-(Jt+(mt=Q-Jt))+(mt-W),xt=R-(Qt+(mt=R-Qt))+(mt-X),ht=S-(Gt+(mt=S-Gt))+(mt-V),dt=T-(Kt+(mt=T-Kt))+(mt-W),jt=U-(Rt+(mt=U-Rt))+(mt-X),0===ft&&0===bt&&0===pt&&0===ct&&0===Mt&&0===yt&&0===it&&0===lt&&0===xt&&0===ht&&0===dt&&0===jt)return St;Tt=i*Y+e*Math.abs(St);const Ut=Ct*Mt+It*ft-(Ht*ct+Dt*bt),Vt=Dt*lt+Jt*ct-(It*it+Et*Mt),Wt=Et*dt+Kt*it-(Jt*ht+Gt*lt),Xt=Gt*bt+Ht*ht-(Kt*ft+Ct*dt),Yt=Ct*lt+Jt*ft-(Ht*it+Et*bt),Zt=Dt*dt+Kt*ct-(It*ht+Gt*Mt);return(St+=(Dt*Dt+It*It+Nt*Nt)*(Qt*Xt+Rt*Yt+Lt*Wt+(xt*rt+jt*st+pt*et))+(Gt*Gt+Kt*Kt+Rt*Rt)*(Lt*Vt-Nt*Yt+Qt*Ut+(pt*nt-yt*st+xt*Z))-((Ct*Ct+Ht*Ht+Lt*Lt)*(Nt*Wt-Qt*Zt+Rt*Vt+(yt*et-xt*ut+jt*nt))+(Et*Et+Jt*Jt+Qt*Qt)*(Rt*Ut+Lt*Zt+Nt*Xt+(jt*Z+pt*ut+yt*rt)))+2*((Dt*ct+It*Mt+Nt*yt)*(Qt*rt+Rt*st+Lt*et)+(Gt*ht+Kt*dt+Rt*jt)*(Lt*nt-Nt*st+Qt*Z)-((Ct*ft+Ht*bt+Lt*pt)*(Nt*et-Qt*ut+Rt*nt)+(Et*it+Jt*lt+Qt*xt)*(Rt*Z+Lt*ut+Nt*rt))))>=Tt||-St>=Tt?St:function(t,e,r,a,s,u,f,c,i,K,L,N,Q,R,S){let T,U,V,W,X,Y,Z,nt,et,rt,ot,at,st,ut;T=(ot=(W=t-(V=(U=n*t)-(U-t)))*(Y=s-(X=(U=n*s)-(U-s)))-((rt=t*s)-V*X-W*X-V*Y))-(Z=ot-(st=(W=a-(V=(U=n*a)-(U-a)))*(Y=e-(X=(U=n*e)-(U-e)))-((at=a*e)-V*X-W*X-V*Y))),h[0]=ot-(Z+T)+(T-st),T=(et=rt-((nt=rt+Z)-(T=nt-rt))+(Z-T))-(Z=et-at),h[1]=et-(Z+T)+(T-at),T=(ut=nt+Z)-nt,h[2]=nt-(ut-T)+(Z-T),h[3]=ut,T=(ot=(W=a-(V=(U=n*a)-(U-a)))*(Y=c-(X=(U=n*c)-(U-c)))-((rt=a*c)-V*X-W*X-V*Y))-(Z=ot-(st=(W=f-(V=(U=n*f)-(U-f)))*(Y=s-(X=(U=n*s)-(U-s)))-((at=f*s)-V*X-W*X-V*Y))),b[0]=ot-(Z+T)+(T-st),T=(et=rt-((nt=rt+Z)-(T=nt-rt))+(Z-T))-(Z=et-at),b[1]=et-(Z+T)+(T-at),T=(ut=nt+Z)-nt,b[2]=nt-(ut-T)+(Z-T),b[3]=ut,T=(ot=(W=f-(V=(U=n*f)-(U-f)))*(Y=L-(X=(U=n*L)-(U-L)))-((rt=f*L)-V*X-W*X-V*Y))-(Z=ot-(st=(W=K-(V=(U=n*K)-(U-K)))*(Y=c-(X=(U=n*c)-(U-c)))-((at=K*c)-V*X-W*X-V*Y))),M[0]=ot-(Z+T)+(T-st),T=(et=rt-((nt=rt+Z)-(T=nt-rt))+(Z-T))-(Z=et-at),M[1]=et-(Z+T)+(T-at),T=(ut=nt+Z)-nt,M[2]=nt-(ut-T)+(Z-T),M[3]=ut,T=(ot=(W=K-(V=(U=n*K)-(U-K)))*(Y=R-(X=(U=n*R)-(U-R)))-((rt=K*R)-V*X-W*X-V*Y))-(Z=ot-(st=(W=Q-(V=(U=n*Q)-(U-Q)))*(Y=L-(X=(U=n*L)-(U-L)))-((at=Q*L)-V*X-W*X-V*Y))),l[0]=ot-(Z+T)+(T-st),T=(et=rt-((nt=rt+Z)-(T=nt-rt))+(Z-T))-(Z=et-at),l[1]=et-(Z+T)+(T-at),T=(ut=nt+Z)-nt,l[2]=nt-(ut-T)+(Z-T),l[3]=ut,T=(ot=(W=Q-(V=(U=n*Q)-(U-Q)))*(Y=e-(X=(U=n*e)-(U-e)))-((rt=Q*e)-V*X-W*X-V*Y))-(Z=ot-(st=(W=t-(V=(U=n*t)-(U-t)))*(Y=R-(X=(U=n*R)-(U-R)))-((at=t*R)-V*X-W*X-V*Y))),d[0]=ot-(Z+T)+(T-st),T=(et=rt-((nt=rt+Z)-(T=nt-rt))+(Z-T))-(Z=et-at),d[1]=et-(Z+T)+(T-at),T=(ut=nt+Z)-nt,d[2]=nt-(ut-T)+(Z-T),d[3]=ut,T=(ot=(W=t-(V=(U=n*t)-(U-t)))*(Y=c-(X=(U=n*c)-(U-c)))-((rt=t*c)-V*X-W*X-V*Y))-(Z=ot-(st=(W=f-(V=(U=n*f)-(U-f)))*(Y=e-(X=(U=n*e)-(U-e)))-((at=f*e)-V*X-W*X-V*Y))),p[0]=ot-(Z+T)+(T-st),T=(et=rt-((nt=rt+Z)-(T=nt-rt))+(Z-T))-(Z=et-at),p[1]=et-(Z+T)+(T-at),T=(ut=nt+Z)-nt,p[2]=nt-(ut-T)+(Z-T),p[3]=ut,T=(ot=(W=a-(V=(U=n*a)-(U-a)))*(Y=L-(X=(U=n*L)-(U-L)))-((rt=a*L)-V*X-W*X-V*Y))-(Z=ot-(st=(W=K-(V=(U=n*K)-(U-K)))*(Y=s-(X=(U=n*s)-(U-s)))-((at=K*s)-V*X-W*X-V*Y))),y[0]=ot-(Z+T)+(T-st),T=(et=rt-((nt=rt+Z)-(T=nt-rt))+(Z-T))-(Z=et-at),y[1]=et-(Z+T)+(T-at),T=(ut=nt+Z)-nt,y[2]=nt-(ut-T)+(Z-T),y[3]=ut,T=(ot=(W=f-(V=(U=n*f)-(U-f)))*(Y=R-(X=(U=n*R)-(U-R)))-((rt=f*R)-V*X-W*X-V*Y))-(Z=ot-(st=(W=Q-(V=(U=n*Q)-(U-Q)))*(Y=c-(X=(U=n*c)-(U-c)))-((at=Q*c)-V*X-W*X-V*Y))),x[0]=ot-(Z+T)+(T-st),T=(et=rt-((nt=rt+Z)-(T=nt-rt))+(Z-T))-(Z=et-at),x[1]=et-(Z+T)+(T-at),T=(ut=nt+Z)-nt,x[2]=nt-(ut-T)+(Z-T),x[3]=ut,T=(ot=(W=K-(V=(U=n*K)-(U-K)))*(Y=e-(X=(U=n*e)-(U-e)))-((rt=K*e)-V*X-W*X-V*Y))-(Z=ot-(st=(W=t-(V=(U=n*t)-(U-t)))*(Y=L-(X=(U=n*L)-(U-L)))-((at=t*L)-V*X-W*X-V*Y))),j[0]=ot-(Z+T)+(T-st),T=(et=rt-((nt=rt+Z)-(T=nt-rt))+(Z-T))-(Z=et-at),j[1]=et-(Z+T)+(T-at),T=(ut=nt+Z)-nt,j[2]=nt-(ut-T)+(Z-T),j[3]=ut,T=(ot=(W=Q-(V=(U=n*Q)-(U-Q)))*(Y=s-(X=(U=n*s)-(U-s)))-((rt=Q*s)-V*X-W*X-V*Y))-(Z=ot-(st=(W=a-(V=(U=n*a)-(U-a)))*(Y=R-(X=(U=n*R)-(U-R)))-((at=a*R)-V*X-W*X-V*Y))),m[0]=ot-(Z+T)+(T-st),T=(et=rt-((nt=rt+Z)-(T=nt-rt))+(Z-T))-(Z=et-at),m[1]=et-(Z+T)+(T-at),T=(ut=nt+Z)-nt,m[2]=nt-(ut-T)+(Z-T),m[3]=ut;const ft=$(h,b,p,i,r,-u,_),ct=$(b,M,y,N,u,-i,v),it=$(M,l,x,S,i,-N,w),ht=$(l,d,j,r,N,-S,A),bt=$(d,h,m,u,S,-r,F),Mt=$(h,y,j,N,r,u,O),lt=$(b,x,m,S,u,i,P),dt=$(M,j,p,r,i,N,g),pt=$(l,m,y,u,N,S,k),yt=$(d,p,x,i,S,r,q),xt=o(tt(it,w,lt,P,pt,k,ct,v,t,e,r,z),z,tt(ht,A,dt,g,yt,q,it,w,a,s,u,B),B,o(tt(bt,F,pt,k,Mt,O,ht,A,f,c,i,C),C,tt(ft,_,yt,q,lt,P,bt,F,K,L,N,D),D,tt(ct,v,Mt,O,dt,g,ft,_,Q,R,S,E),E,H,I),I,G,J);return J[xt-1]}(t,a,u,f,K,L,N,Q,R,S,T,U,V,W,X)}t.insphere=function(t,n,e,r,o,a,s,u,c,i,h,b,M,l,d){const p=t-M,y=r-M,x=s-M,j=i-M,m=n-l,_=o-l,v=u-l,w=h-l,A=e-d,F=a-d,O=c-d,P=b-d,g=p*_,k=y*m,q=g-k,z=y*v,B=x*_,C=z-B,D=x*w,E=j*v,G=D-E,H=j*m,I=p*w,J=H-I,K=p*v,L=x*m,N=K-L,Q=y*w,R=j*_,S=Q-R,T=p*p+m*m+A*A,U=y*y+_*_+F*F,V=x*x+v*v+O*O,W=j*j+w*w+P*P,X=V*(P*q+A*S+F*J)-W*(A*C-F*N+O*q)+(T*(F*G-O*S+P*C)-U*(O*J+P*N+A*G)),Y=Math.abs(A),Z=Math.abs(F),$=Math.abs(O),tt=Math.abs(P),nt=Math.abs(g),et=Math.abs(k),rt=Math.abs(z),ot=Math.abs(B),at=Math.abs(D),ut=Math.abs(E),ft=Math.abs(H),ct=Math.abs(I),it=Math.abs(K),ht=Math.abs(L),bt=Math.abs(Q),Mt=Math.abs(R),lt=((at+ut)*Z+(Mt+bt)*$+(rt+ot)*tt)*T+((ft+ct)*$+(it+ht)*tt+(at+ut)*Y)*U+((nt+et)*tt+(bt+Mt)*Y+(ft+ct)*Z)*V+((rt+ot)*Y+(ht+it)*Z+(nt+et)*$)*W,dt=f*lt;return X>dt||-X>dt?X:-st(t,n,e,r,o,a,s,u,c,i,h,b,M,l,d,lt)},t.inspherefast=function(t,n,e,r,o,a,s,u,f,c,i,h,b,M,l){const d=t-b,p=r-b,y=s-b,x=c-b,j=n-M,m=o-M,_=u-M,v=i-M,w=e-l,A=a-l,F=f-l,O=h-l,P=d*m-p*j,g=p*_-y*m,k=y*v-x*_,q=x*j-d*v,z=d*_-y*j,B=p*v-x*m;return(y*y+_*_+F*F)*(O*P+w*B+A*q)-(x*x+v*v+O*O)*(w*g-A*z+F*P)+((d*d+j*j+w*w)*(A*k-F*B+O*g)-(p*p+m*m+A*A)*(F*q+O*z+w*k))},Object.defineProperty(t,"__esModule",{value:!0})}); diff --git a/node_modules/robust-predicates/umd/orient2d.js b/node_modules/robust-predicates/umd/orient2d.js new file mode 100644 index 0000000000000000000000000000000000000000..22f2c43f9bc8705d0017d6cf55ef6951bb3bb37e --- /dev/null +++ b/node_modules/robust-predicates/umd/orient2d.js @@ -0,0 +1,284 @@ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : +typeof define === 'function' && define.amd ? define(['exports'], factory) : +(global = global || self, factory(global.predicates = {})); +}(this, function (exports) { 'use strict'; + +const epsilon = 1.1102230246251565e-16; +const splitter = 134217729; +const resulterrbound = (3 + 8 * epsilon) * epsilon; + +// fast_expansion_sum_zeroelim routine from oritinal code +function sum(elen, e, flen, f, h) { + let Q, Qnew, hh, bvirt; + let enow = e[0]; + let fnow = f[0]; + let eindex = 0; + let findex = 0; + if ((fnow > enow) === (fnow > -enow)) { + Q = enow; + enow = e[++eindex]; + } else { + Q = fnow; + fnow = f[++findex]; + } + let hindex = 0; + if (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = enow + Q; + hh = Q - (Qnew - enow); + enow = e[++eindex]; + } else { + Qnew = fnow + Q; + hh = Q - (Qnew - fnow); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + while (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + } else { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + } + while (eindex < elen) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + while (findex < flen) { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +function estimate(elen, e) { + let Q = e[0]; + for (let i = 1; i < elen; i++) Q += e[i]; + return Q; +} + +function vec(n) { + return new Float64Array(n); +} + +const ccwerrboundA = (3 + 16 * epsilon) * epsilon; +const ccwerrboundB = (2 + 12 * epsilon) * epsilon; +const ccwerrboundC = (9 + 64 * epsilon) * epsilon * epsilon; + +const B = vec(4); +const C1 = vec(8); +const C2 = vec(12); +const D = vec(16); +const u = vec(4); + +function orient2dadapt(ax, ay, bx, by, cx, cy, detsum) { + let acxtail, acytail, bcxtail, bcytail; + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + const acx = ax - cx; + const bcx = bx - cx; + const acy = ay - cy; + const bcy = by - cy; + + s1 = acx * bcy; + c = splitter * acx; + ahi = c - (c - acx); + alo = acx - ahi; + c = splitter * bcy; + bhi = c - (c - bcy); + blo = bcy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acy * bcx; + c = splitter * acy; + ahi = c - (c - acy); + alo = acy - ahi; + c = splitter * bcx; + bhi = c - (c - bcx); + blo = bcx - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + B[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + B[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + B[2] = _j - (u3 - bvirt) + (_i - bvirt); + B[3] = u3; + + let det = estimate(4, B); + let errbound = ccwerrboundB * detsum; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - acx; + acxtail = ax - (acx + bvirt) + (bvirt - cx); + bvirt = bx - bcx; + bcxtail = bx - (bcx + bvirt) + (bvirt - cx); + bvirt = ay - acy; + acytail = ay - (acy + bvirt) + (bvirt - cy); + bvirt = by - bcy; + bcytail = by - (bcy + bvirt) + (bvirt - cy); + + if (acxtail === 0 && acytail === 0 && bcxtail === 0 && bcytail === 0) { + return det; + } + + errbound = ccwerrboundC * detsum + resulterrbound * Math.abs(det); + det += (acx * bcytail + bcy * acxtail) - (acy * bcxtail + bcx * acytail); + if (det >= errbound || -det >= errbound) return det; + + s1 = acxtail * bcy; + c = splitter * acxtail; + ahi = c - (c - acxtail); + alo = acxtail - ahi; + c = splitter * bcy; + bhi = c - (c - bcy); + blo = bcy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acytail * bcx; + c = splitter * acytail; + ahi = c - (c - acytail); + alo = acytail - ahi; + c = splitter * bcx; + bhi = c - (c - bcx); + blo = bcx - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + const C1len = sum(4, B, 4, u, C1); + + s1 = acx * bcytail; + c = splitter * acx; + ahi = c - (c - acx); + alo = acx - ahi; + c = splitter * bcytail; + bhi = c - (c - bcytail); + blo = bcytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acy * bcxtail; + c = splitter * acy; + ahi = c - (c - acy); + alo = acy - ahi; + c = splitter * bcxtail; + bhi = c - (c - bcxtail); + blo = bcxtail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + const C2len = sum(C1len, C1, 4, u, C2); + + s1 = acxtail * bcytail; + c = splitter * acxtail; + ahi = c - (c - acxtail); + alo = acxtail - ahi; + c = splitter * bcytail; + bhi = c - (c - bcytail); + blo = bcytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acytail * bcxtail; + c = splitter * acytail; + ahi = c - (c - acytail); + alo = acytail - ahi; + c = splitter * bcxtail; + bhi = c - (c - bcxtail); + blo = bcxtail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + const Dlen = sum(C2len, C2, 4, u, D); + + return D[Dlen - 1]; +} + +function orient2d(ax, ay, bx, by, cx, cy) { + const detleft = (ay - cy) * (bx - cx); + const detright = (ax - cx) * (by - cy); + const det = detleft - detright; + + if (detleft === 0 || detright === 0 || (detleft > 0) !== (detright > 0)) return det; + + const detsum = Math.abs(detleft + detright); + if (Math.abs(det) >= ccwerrboundA * detsum) return det; + + return -orient2dadapt(ax, ay, bx, by, cx, cy, detsum); +} + +function orient2dfast(ax, ay, bx, by, cx, cy) { + return (ay - cy) * (bx - cx) - (ax - cx) * (by - cy); +} + +exports.orient2d = orient2d; +exports.orient2dfast = orient2dfast; + +Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/robust-predicates/umd/orient2d.min.js b/node_modules/robust-predicates/umd/orient2d.min.js new file mode 100644 index 0000000000000000000000000000000000000000..149e1479c07821379f6fb913f28844d5ea316ecc --- /dev/null +++ b/node_modules/robust-predicates/umd/orient2d.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).predicates={})}(this,function(t){"use strict";const e=134217729,n=33306690738754706e-32;function r(t,e,n,r,o){let f,i,u,c,s=e[0],a=r[0],d=0,l=0;a>s==a>-s?(f=s,s=e[++d]):(f=a,a=r[++l]);let p=0;if(ds==a>-s?(u=f-((i=s+f)-s),s=e[++d]):(u=f-((i=a+f)-a),a=r[++l]),f=i,0!==u&&(o[p++]=u);ds==a>-s?(u=f-((i=f+s)-(c=i-f))+(s-c),s=e[++d]):(u=f-((i=f+a)-(c=i-f))+(a-c),a=r[++l]),f=i,0!==u&&(o[p++]=u);for(;d0!=x>0)return j;const m=Math.abs(M+x);return Math.abs(j)>=f*m?j:-function(t,o,f,p,b,y,h){let M,x,j,m,_,v,w,A,F,O,P,g,k,q,z,B,C,D;const E=t-b,G=f-b,H=o-y,I=p-y;_=(z=(A=E-(w=(v=e*E)-(v-E)))*(O=I-(F=(v=e*I)-(v-I)))-((q=E*I)-w*F-A*F-w*O))-(P=z-(C=(A=H-(w=(v=e*H)-(v-H)))*(O=G-(F=(v=e*G)-(v-G)))-((B=H*G)-w*F-A*F-w*O))),c[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B),c[1]=k-(P+_)+(_-B),_=(D=g+P)-g,c[2]=g-(D-_)+(P-_),c[3]=D;let J=function(t,e){let n=e[0];for(let r=1;r=K||-J>=K)return J;if(M=t-(E+(_=t-E))+(_-b),j=f-(G+(_=f-G))+(_-b),x=o-(H+(_=o-H))+(_-y),m=p-(I+(_=p-I))+(_-y),0===M&&0===x&&0===j&&0===m)return J;if(K=u*h+n*Math.abs(J),(J+=E*m+I*M-(H*j+G*x))>=K||-J>=K)return J;_=(z=(A=M-(w=(v=e*M)-(v-M)))*(O=I-(F=(v=e*I)-(v-I)))-((q=M*I)-w*F-A*F-w*O))-(P=z-(C=(A=x-(w=(v=e*x)-(v-x)))*(O=G-(F=(v=e*G)-(v-G)))-((B=x*G)-w*F-A*F-w*O))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B),l[1]=k-(P+_)+(_-B),_=(D=g+P)-g,l[2]=g-(D-_)+(P-_),l[3]=D;const L=r(4,c,4,l,s);_=(z=(A=E-(w=(v=e*E)-(v-E)))*(O=m-(F=(v=e*m)-(v-m)))-((q=E*m)-w*F-A*F-w*O))-(P=z-(C=(A=H-(w=(v=e*H)-(v-H)))*(O=j-(F=(v=e*j)-(v-j)))-((B=H*j)-w*F-A*F-w*O))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B),l[1]=k-(P+_)+(_-B),_=(D=g+P)-g,l[2]=g-(D-_)+(P-_),l[3]=D;const N=r(L,s,4,l,a);_=(z=(A=M-(w=(v=e*M)-(v-M)))*(O=m-(F=(v=e*m)-(v-m)))-((q=M*m)-w*F-A*F-w*O))-(P=z-(C=(A=x-(w=(v=e*x)-(v-x)))*(O=j-(F=(v=e*j)-(v-j)))-((B=x*j)-w*F-A*F-w*O))),l[0]=z-(P+_)+(_-C),_=(k=q-((g=q+P)-(_=g-q))+(P-_))-(P=k-B),l[1]=k-(P+_)+(_-B),_=(D=g+P)-g,l[2]=g-(D-_)+(P-_),l[3]=D;const Q=r(N,a,4,l,d);return d[Q-1]}(t,o,p,b,y,h,m)},t.orient2dfast=function(t,e,n,r,o,f){return(e-f)*(n-o)-(t-o)*(r-f)},Object.defineProperty(t,"__esModule",{value:!0})}); diff --git a/node_modules/robust-predicates/umd/orient3d.js b/node_modules/robust-predicates/umd/orient3d.js new file mode 100644 index 0000000000000000000000000000000000000000..915f78899252fc3a34911899ddbfe7939530c803 --- /dev/null +++ b/node_modules/robust-predicates/umd/orient3d.js @@ -0,0 +1,603 @@ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : +typeof define === 'function' && define.amd ? define(['exports'], factory) : +(global = global || self, factory(global.predicates = {})); +}(this, function (exports) { 'use strict'; + +const epsilon = 1.1102230246251565e-16; +const splitter = 134217729; +const resulterrbound = (3 + 8 * epsilon) * epsilon; + +// fast_expansion_sum_zeroelim routine from oritinal code +function sum(elen, e, flen, f, h) { + let Q, Qnew, hh, bvirt; + let enow = e[0]; + let fnow = f[0]; + let eindex = 0; + let findex = 0; + if ((fnow > enow) === (fnow > -enow)) { + Q = enow; + enow = e[++eindex]; + } else { + Q = fnow; + fnow = f[++findex]; + } + let hindex = 0; + if (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = enow + Q; + hh = Q - (Qnew - enow); + enow = e[++eindex]; + } else { + Qnew = fnow + Q; + hh = Q - (Qnew - fnow); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + while (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + } else { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + } + while (eindex < elen) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + while (findex < flen) { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +// scale_expansion_zeroelim routine from oritinal code +function scale(elen, e, b, h) { + let Q, sum, hh, product1, product0; + let bvirt, c, ahi, alo, bhi, blo; + + c = splitter * b; + bhi = c - (c - b); + blo = b - bhi; + let enow = e[0]; + Q = enow * b; + c = splitter * enow; + ahi = c - (c - enow); + alo = enow - ahi; + hh = alo * blo - (Q - ahi * bhi - alo * bhi - ahi * blo); + let hindex = 0; + if (hh !== 0) { + h[hindex++] = hh; + } + for (let i = 1; i < elen; i++) { + enow = e[i]; + product1 = enow * b; + c = splitter * enow; + ahi = c - (c - enow); + alo = enow - ahi; + product0 = alo * blo - (product1 - ahi * bhi - alo * bhi - ahi * blo); + sum = Q + product0; + bvirt = sum - Q; + hh = Q - (sum - bvirt) + (product0 - bvirt); + if (hh !== 0) { + h[hindex++] = hh; + } + Q = product1 + sum; + hh = sum - (Q - product1); + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +function estimate(elen, e) { + let Q = e[0]; + for (let i = 1; i < elen; i++) Q += e[i]; + return Q; +} + +function vec(n) { + return new Float64Array(n); +} + +const o3derrboundA = (7 + 56 * epsilon) * epsilon; +const o3derrboundB = (3 + 28 * epsilon) * epsilon; +const o3derrboundC = (26 + 288 * epsilon) * epsilon * epsilon; + +const bc = vec(4); +const ca = vec(4); +const ab = vec(4); +const at_b = vec(4); +const at_c = vec(4); +const bt_c = vec(4); +const bt_a = vec(4); +const ct_a = vec(4); +const ct_b = vec(4); +const bct = vec(8); +const cat = vec(8); +const abt = vec(8); +const u = vec(4); + +const _8 = vec(8); +const _8b = vec(8); +const _16 = vec(8); +const _12 = vec(12); + +let fin = vec(192); +let fin2 = vec(192); + +function finadd(finlen, alen, a) { + finlen = sum(finlen, fin, alen, a, fin2); + const tmp = fin; fin = fin2; fin2 = tmp; + return finlen; +} + +function tailinit(xtail, ytail, ax, ay, bx, by, a, b) { + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3, negate; + if (xtail === 0) { + if (ytail === 0) { + a[0] = 0; + b[0] = 0; + return 1; + } else { + negate = -ytail; + s1 = negate * ax; + c = splitter * negate; + ahi = c - (c - negate); + alo = negate - ahi; + c = splitter * ax; + bhi = c - (c - ax); + blo = ax - bhi; + a[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + a[1] = s1; + s1 = ytail * bx; + c = splitter * ytail; + ahi = c - (c - ytail); + alo = ytail - ahi; + c = splitter * bx; + bhi = c - (c - bx); + blo = bx - bhi; + b[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + b[1] = s1; + return 2; + } + } else { + if (ytail === 0) { + s1 = xtail * ay; + c = splitter * xtail; + ahi = c - (c - xtail); + alo = xtail - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + a[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + a[1] = s1; + negate = -xtail; + s1 = negate * by; + c = splitter * negate; + ahi = c - (c - negate); + alo = negate - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + b[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + b[1] = s1; + return 2; + } else { + s1 = xtail * ay; + c = splitter * xtail; + ahi = c - (c - xtail); + alo = xtail - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ytail * ax; + c = splitter * ytail; + ahi = c - (c - ytail); + alo = ytail - ahi; + c = splitter * ax; + bhi = c - (c - ax); + blo = ax - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + a[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + a[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + a[2] = _j - (u3 - bvirt) + (_i - bvirt); + a[3] = u3; + s1 = ytail * bx; + c = splitter * ytail; + ahi = c - (c - ytail); + alo = ytail - ahi; + c = splitter * bx; + bhi = c - (c - bx); + blo = bx - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = xtail * by; + c = splitter * xtail; + ahi = c - (c - xtail); + alo = xtail - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + b[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + b[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + b[2] = _j - (u3 - bvirt) + (_i - bvirt); + b[3] = u3; + return 4; + } + } +} + +function tailadd(finlen, a, b, k, z) { + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _k, _0, s1, s0, u3; + s1 = a * b; + c = splitter * a; + ahi = c - (c - a); + alo = a - ahi; + c = splitter * b; + bhi = c - (c - b); + blo = b - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + c = splitter * k; + bhi = c - (c - k); + blo = k - bhi; + _i = s0 * k; + c = splitter * s0; + ahi = c - (c - s0); + alo = s0 - ahi; + u[0] = alo * blo - (_i - ahi * bhi - alo * bhi - ahi * blo); + _j = s1 * k; + c = splitter * s1; + ahi = c - (c - s1); + alo = s1 - ahi; + _0 = alo * blo - (_j - ahi * bhi - alo * bhi - ahi * blo); + _k = _i + _0; + bvirt = _k - _i; + u[1] = _i - (_k - bvirt) + (_0 - bvirt); + u3 = _j + _k; + u[2] = _k - (u3 - _j); + u[3] = u3; + finlen = finadd(finlen, 4, u); + if (z !== 0) { + c = splitter * z; + bhi = c - (c - z); + blo = z - bhi; + _i = s0 * z; + c = splitter * s0; + ahi = c - (c - s0); + alo = s0 - ahi; + u[0] = alo * blo - (_i - ahi * bhi - alo * bhi - ahi * blo); + _j = s1 * z; + c = splitter * s1; + ahi = c - (c - s1); + alo = s1 - ahi; + _0 = alo * blo - (_j - ahi * bhi - alo * bhi - ahi * blo); + _k = _i + _0; + bvirt = _k - _i; + u[1] = _i - (_k - bvirt) + (_0 - bvirt); + u3 = _j + _k; + u[2] = _k - (u3 - _j); + u[3] = u3; + finlen = finadd(finlen, 4, u); + } + return finlen; +} + +function orient3dadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, permanent) { + let finlen; + let adxtail, bdxtail, cdxtail; + let adytail, bdytail, cdytail; + let adztail, bdztail, cdztail; + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + const adz = az - dz; + const bdz = bz - dz; + const cdz = cz - dz; + + s1 = bdx * cdy; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * bdy; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bc[2] = _j - (u3 - bvirt) + (_i - bvirt); + bc[3] = u3; + s1 = cdx * ady; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * cdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ca[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ca[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ca[2] = _j - (u3 - bvirt) + (_i - bvirt); + ca[3] = u3; + s1 = adx * bdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * ady; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ab[2] = _j - (u3 - bvirt) + (_i - bvirt); + ab[3] = u3; + + finlen = sum( + sum( + scale(4, bc, adz, _8), _8, + scale(4, ca, bdz, _8b), _8b, _16), _16, + scale(4, ab, cdz, _8), _8, fin); + + let det = estimate(finlen, fin); + let errbound = o3derrboundB * permanent; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - adx; + adxtail = ax - (adx + bvirt) + (bvirt - dx); + bvirt = bx - bdx; + bdxtail = bx - (bdx + bvirt) + (bvirt - dx); + bvirt = cx - cdx; + cdxtail = cx - (cdx + bvirt) + (bvirt - dx); + bvirt = ay - ady; + adytail = ay - (ady + bvirt) + (bvirt - dy); + bvirt = by - bdy; + bdytail = by - (bdy + bvirt) + (bvirt - dy); + bvirt = cy - cdy; + cdytail = cy - (cdy + bvirt) + (bvirt - dy); + bvirt = az - adz; + adztail = az - (adz + bvirt) + (bvirt - dz); + bvirt = bz - bdz; + bdztail = bz - (bdz + bvirt) + (bvirt - dz); + bvirt = cz - cdz; + cdztail = cz - (cdz + bvirt) + (bvirt - dz); + + if (adxtail === 0 && bdxtail === 0 && cdxtail === 0 && + adytail === 0 && bdytail === 0 && cdytail === 0 && + adztail === 0 && bdztail === 0 && cdztail === 0) { + return det; + } + + errbound = o3derrboundC * permanent + resulterrbound * Math.abs(det); + det += + adz * (bdx * cdytail + cdy * bdxtail - (bdy * cdxtail + cdx * bdytail)) + adztail * (bdx * cdy - bdy * cdx) + + bdz * (cdx * adytail + ady * cdxtail - (cdy * adxtail + adx * cdytail)) + bdztail * (cdx * ady - cdy * adx) + + cdz * (adx * bdytail + bdy * adxtail - (ady * bdxtail + bdx * adytail)) + cdztail * (adx * bdy - ady * bdx); + if (det >= errbound || -det >= errbound) { + return det; + } + + const at_len = tailinit(adxtail, adytail, bdx, bdy, cdx, cdy, at_b, at_c); + const bt_len = tailinit(bdxtail, bdytail, cdx, cdy, adx, ady, bt_c, bt_a); + const ct_len = tailinit(cdxtail, cdytail, adx, ady, bdx, bdy, ct_a, ct_b); + + const bctlen = sum(bt_len, bt_c, ct_len, ct_b, bct); + finlen = finadd(finlen, scale(bctlen, bct, adz, _16), _16); + + const catlen = sum(ct_len, ct_a, at_len, at_c, cat); + finlen = finadd(finlen, scale(catlen, cat, bdz, _16), _16); + + const abtlen = sum(at_len, at_b, bt_len, bt_a, abt); + finlen = finadd(finlen, scale(abtlen, abt, cdz, _16), _16); + + if (adztail !== 0) { + finlen = finadd(finlen, scale(4, bc, adztail, _12), _12); + finlen = finadd(finlen, scale(bctlen, bct, adztail, _16), _16); + } + if (bdztail !== 0) { + finlen = finadd(finlen, scale(4, ca, bdztail, _12), _12); + finlen = finadd(finlen, scale(catlen, cat, bdztail, _16), _16); + } + if (cdztail !== 0) { + finlen = finadd(finlen, scale(4, ab, cdztail, _12), _12); + finlen = finadd(finlen, scale(abtlen, abt, cdztail, _16), _16); + } + + if (adxtail !== 0) { + if (bdytail !== 0) { + finlen = tailadd(finlen, adxtail, bdytail, cdz, cdztail); + } + if (cdytail !== 0) { + finlen = tailadd(finlen, -adxtail, cdytail, bdz, bdztail); + } + } + if (bdxtail !== 0) { + if (cdytail !== 0) { + finlen = tailadd(finlen, bdxtail, cdytail, adz, adztail); + } + if (adytail !== 0) { + finlen = tailadd(finlen, -bdxtail, adytail, cdz, cdztail); + } + } + if (cdxtail !== 0) { + if (adytail !== 0) { + finlen = tailadd(finlen, cdxtail, adytail, bdz, bdztail); + } + if (bdytail !== 0) { + finlen = tailadd(finlen, -cdxtail, bdytail, adz, adztail); + } + } + + return fin[finlen - 1]; +} + +function orient3d(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz) { + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + const adz = az - dz; + const bdz = bz - dz; + const cdz = cz - dz; + + const bdxcdy = bdx * cdy; + const cdxbdy = cdx * bdy; + + const cdxady = cdx * ady; + const adxcdy = adx * cdy; + + const adxbdy = adx * bdy; + const bdxady = bdx * ady; + + const det = + adz * (bdxcdy - cdxbdy) + + bdz * (cdxady - adxcdy) + + cdz * (adxbdy - bdxady); + + const permanent = + (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) + + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) + + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz); + + const errbound = o3derrboundA * permanent; + if (det > errbound || -det > errbound) { + return det; + } + + return orient3dadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, permanent); +} + +function orient3dfast(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz) { + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + const adz = az - dz; + const bdz = bz - dz; + const cdz = cz - dz; + + return adx * (bdy * cdz - bdz * cdy) + + bdx * (cdy * adz - cdz * ady) + + cdx * (ady * bdz - adz * bdy); +} + +exports.orient3d = orient3d; +exports.orient3dfast = orient3dfast; + +Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/robust-predicates/umd/orient3d.min.js b/node_modules/robust-predicates/umd/orient3d.min.js new file mode 100644 index 0000000000000000000000000000000000000000..ce0d56b0f417e0a3a44b03532853aff56cc49f2e --- /dev/null +++ b/node_modules/robust-predicates/umd/orient3d.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t=t||self).predicates={})}(this,function(t){"use strict";const e=134217729,n=33306690738754706e-32;function r(t,e,n,r,o){let f,u,s,i,a=e[0],c=r[0],l=0,b=0;c>a==c>-a?(f=a,a=e[++l]):(f=c,c=r[++b]);let d=0;if(la==c>-a?(s=f-((u=a+f)-a),a=e[++l]):(s=f-((u=c+f)-c),c=r[++b]),f=u,0!==s&&(o[d++]=s);la==c>-a?(s=f-((u=f+a)-(i=u-f))+(a-i),a=e[++l]):(s=f-((u=f+c)-(i=u-f))+(c-i),c=r[++b]),f=u,0!==s&&(o[d++]=s);for(;lnt||-tt>nt?tt:function(t,f,u,_,P,z,B,C,D,E,G,H,I){let J,K,L,N,Q,R,S,T,U,V,W,X,Y,Z,$,tt,et,nt,rt,ot,ft,ut,st,it;const at=t-E,ct=_-E,lt=B-E,bt=f-G,dt=P-G,ht=C-G,Mt=u-H,pt=z-H,yt=D-H;W=(ft=(Z=ct-(Y=(X=e*ct)-(X-ct)))*(tt=ht-($=(X=e*ht)-(X-ht)))-((ot=ct*ht)-Y*$-Z*$-Y*tt))-(et=ft-(st=(Z=lt-(Y=(X=e*lt)-(X-lt)))*(tt=dt-($=(X=e*dt)-(X-dt)))-((ut=lt*dt)-Y*$-Z*$-Y*tt))),a[0]=ft-(et+W)+(W-st),W=(rt=ot-((nt=ot+et)-(W=nt-ot))+(et-W))-(et=rt-ut),a[1]=rt-(et+W)+(W-ut),W=(it=nt+et)-nt,a[2]=nt-(it-W)+(et-W),a[3]=it,W=(ft=(Z=lt-(Y=(X=e*lt)-(X-lt)))*(tt=bt-($=(X=e*bt)-(X-bt)))-((ot=lt*bt)-Y*$-Z*$-Y*tt))-(et=ft-(st=(Z=at-(Y=(X=e*at)-(X-at)))*(tt=ht-($=(X=e*ht)-(X-ht)))-((ut=at*ht)-Y*$-Z*$-Y*tt))),c[0]=ft-(et+W)+(W-st),W=(rt=ot-((nt=ot+et)-(W=nt-ot))+(et-W))-(et=rt-ut),c[1]=rt-(et+W)+(W-ut),W=(it=nt+et)-nt,c[2]=nt-(it-W)+(et-W),c[3]=it,W=(ft=(Z=at-(Y=(X=e*at)-(X-at)))*(tt=dt-($=(X=e*dt)-(X-dt)))-((ot=at*dt)-Y*$-Z*$-Y*tt))-(et=ft-(st=(Z=ct-(Y=(X=e*ct)-(X-ct)))*(tt=bt-($=(X=e*bt)-(X-bt)))-((ut=ct*bt)-Y*$-Z*$-Y*tt))),l[0]=ft-(et+W)+(W-st),W=(rt=ot-((nt=ot+et)-(W=nt-ot))+(et-W))-(et=rt-ut),l[1]=rt-(et+W)+(W-ut),W=(it=nt+et)-nt,l[2]=nt-(it-W)+(et-W),l[3]=it;let xt=function(t,e){let n=e[0];for(let r=1;r=jt||-xt>=jt)return xt;if(K=t-(at+(W=t-at))+(W-E),L=_-(ct+(W=_-ct))+(W-E),N=B-(lt+(W=B-lt))+(W-E),Q=f-(bt+(W=f-bt))+(W-G),R=P-(dt+(W=P-dt))+(W-G),S=C-(ht+(W=C-ht))+(W-G),T=u-(Mt+(W=u-Mt))+(W-H),U=z-(pt+(W=z-pt))+(W-H),V=D-(yt+(W=D-yt))+(W-H),0===K&&0===L&&0===N&&0===Q&&0===R&&0===S&&0===T&&0===U&&0===V)return xt;if(jt=i*I+n*Math.abs(xt),(xt+=Mt*(ct*S+ht*L-(dt*N+lt*R))+T*(ct*ht-dt*lt)+pt*(lt*Q+bt*N-(ht*K+at*S))+U*(lt*bt-ht*at)+yt*(at*R+dt*K-(bt*L+ct*Q))+V*(at*dt-bt*ct))>=jt||-xt>=jt)return xt;const mt=k(K,Q,ct,dt,lt,ht,b,d),_t=k(L,R,lt,ht,at,bt,h,M),vt=k(N,S,at,bt,ct,dt,p,y),wt=r(_t,h,vt,y,x);J=g(J,o(wt,x,Mt,A),A);const At=r(vt,p,mt,d,j);J=g(J,o(At,j,pt,A),A);const Ft=r(mt,b,_t,M,m);return J=g(J,o(Ft,m,yt,A),A),0!==T&&(J=g(J,o(4,a,T,F),F),J=g(J,o(wt,x,T,A),A)),0!==U&&(J=g(J,o(4,c,U,F),F),J=g(J,o(At,j,U,A),A)),0!==V&&(J=g(J,o(4,l,V,F),F),J=g(J,o(Ft,m,V,A),A)),0!==K&&(0!==R&&(J=q(J,K,R,yt,V)),0!==S&&(J=q(J,-K,S,pt,U))),0!==L&&(0!==S&&(J=q(J,L,S,Mt,T)),0!==Q&&(J=q(J,-L,Q,yt,V))),0!==N&&(0!==Q&&(J=q(J,N,Q,pt,U)),0!==R&&(J=q(J,-N,R,Mt,T))),O[J-1]}(t,f,_,P,z,B,C,D,E,G,H,I,et)},t.orient3dfast=function(t,e,n,r,o,f,u,s,i,a,c,l){const b=e-c,d=o-c,h=s-c,M=n-l,p=f-l,y=i-l;return(t-a)*(d*y-p*h)+(r-a)*(h*M-y*b)+(u-a)*(b*p-M*d)},Object.defineProperty(t,"__esModule",{value:!0})}); diff --git a/node_modules/robust-predicates/umd/predicates.js b/node_modules/robust-predicates/umd/predicates.js new file mode 100644 index 0000000000000000000000000000000000000000..44216e77f07ef21c1dfc9f1bb5279791e96114f2 --- /dev/null +++ b/node_modules/robust-predicates/umd/predicates.js @@ -0,0 +1,2341 @@ +(function (global, factory) { +typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : +typeof define === 'function' && define.amd ? define(['exports'], factory) : +(global = global || self, factory(global.predicates = {})); +}(this, function (exports) { 'use strict'; + +const epsilon = 1.1102230246251565e-16; +const splitter = 134217729; +const resulterrbound = (3 + 8 * epsilon) * epsilon; + +// fast_expansion_sum_zeroelim routine from oritinal code +function sum(elen, e, flen, f, h) { + let Q, Qnew, hh, bvirt; + let enow = e[0]; + let fnow = f[0]; + let eindex = 0; + let findex = 0; + if ((fnow > enow) === (fnow > -enow)) { + Q = enow; + enow = e[++eindex]; + } else { + Q = fnow; + fnow = f[++findex]; + } + let hindex = 0; + if (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = enow + Q; + hh = Q - (Qnew - enow); + enow = e[++eindex]; + } else { + Qnew = fnow + Q; + hh = Q - (Qnew - fnow); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + while (eindex < elen && findex < flen) { + if ((fnow > enow) === (fnow > -enow)) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + } else { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + } + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + } + while (eindex < elen) { + Qnew = Q + enow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (enow - bvirt); + enow = e[++eindex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + while (findex < flen) { + Qnew = Q + fnow; + bvirt = Qnew - Q; + hh = Q - (Qnew - bvirt) + (fnow - bvirt); + fnow = f[++findex]; + Q = Qnew; + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +function sum_three(alen, a, blen, b, clen, c, tmp, out) { + return sum(sum(alen, a, blen, b, tmp), tmp, clen, c, out); +} + +// scale_expansion_zeroelim routine from oritinal code +function scale(elen, e, b, h) { + let Q, sum, hh, product1, product0; + let bvirt, c, ahi, alo, bhi, blo; + + c = splitter * b; + bhi = c - (c - b); + blo = b - bhi; + let enow = e[0]; + Q = enow * b; + c = splitter * enow; + ahi = c - (c - enow); + alo = enow - ahi; + hh = alo * blo - (Q - ahi * bhi - alo * bhi - ahi * blo); + let hindex = 0; + if (hh !== 0) { + h[hindex++] = hh; + } + for (let i = 1; i < elen; i++) { + enow = e[i]; + product1 = enow * b; + c = splitter * enow; + ahi = c - (c - enow); + alo = enow - ahi; + product0 = alo * blo - (product1 - ahi * bhi - alo * bhi - ahi * blo); + sum = Q + product0; + bvirt = sum - Q; + hh = Q - (sum - bvirt) + (product0 - bvirt); + if (hh !== 0) { + h[hindex++] = hh; + } + Q = product1 + sum; + hh = sum - (Q - product1); + if (hh !== 0) { + h[hindex++] = hh; + } + } + if (Q !== 0 || hindex === 0) { + h[hindex++] = Q; + } + return hindex; +} + +function negate(elen, e) { + for (let i = 0; i < elen; i++) e[i] = -e[i]; + return elen; +} + +function estimate(elen, e) { + let Q = e[0]; + for (let i = 1; i < elen; i++) Q += e[i]; + return Q; +} + +function vec(n) { + return new Float64Array(n); +} + +const ccwerrboundA = (3 + 16 * epsilon) * epsilon; +const ccwerrboundB = (2 + 12 * epsilon) * epsilon; +const ccwerrboundC = (9 + 64 * epsilon) * epsilon * epsilon; + +const B = vec(4); +const C1 = vec(8); +const C2 = vec(12); +const D = vec(16); +const u = vec(4); + +function orient2dadapt(ax, ay, bx, by, cx, cy, detsum) { + let acxtail, acytail, bcxtail, bcytail; + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + const acx = ax - cx; + const bcx = bx - cx; + const acy = ay - cy; + const bcy = by - cy; + + s1 = acx * bcy; + c = splitter * acx; + ahi = c - (c - acx); + alo = acx - ahi; + c = splitter * bcy; + bhi = c - (c - bcy); + blo = bcy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acy * bcx; + c = splitter * acy; + ahi = c - (c - acy); + alo = acy - ahi; + c = splitter * bcx; + bhi = c - (c - bcx); + blo = bcx - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + B[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + B[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + B[2] = _j - (u3 - bvirt) + (_i - bvirt); + B[3] = u3; + + let det = estimate(4, B); + let errbound = ccwerrboundB * detsum; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - acx; + acxtail = ax - (acx + bvirt) + (bvirt - cx); + bvirt = bx - bcx; + bcxtail = bx - (bcx + bvirt) + (bvirt - cx); + bvirt = ay - acy; + acytail = ay - (acy + bvirt) + (bvirt - cy); + bvirt = by - bcy; + bcytail = by - (bcy + bvirt) + (bvirt - cy); + + if (acxtail === 0 && acytail === 0 && bcxtail === 0 && bcytail === 0) { + return det; + } + + errbound = ccwerrboundC * detsum + resulterrbound * Math.abs(det); + det += (acx * bcytail + bcy * acxtail) - (acy * bcxtail + bcx * acytail); + if (det >= errbound || -det >= errbound) return det; + + s1 = acxtail * bcy; + c = splitter * acxtail; + ahi = c - (c - acxtail); + alo = acxtail - ahi; + c = splitter * bcy; + bhi = c - (c - bcy); + blo = bcy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acytail * bcx; + c = splitter * acytail; + ahi = c - (c - acytail); + alo = acytail - ahi; + c = splitter * bcx; + bhi = c - (c - bcx); + blo = bcx - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + const C1len = sum(4, B, 4, u, C1); + + s1 = acx * bcytail; + c = splitter * acx; + ahi = c - (c - acx); + alo = acx - ahi; + c = splitter * bcytail; + bhi = c - (c - bcytail); + blo = bcytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acy * bcxtail; + c = splitter * acy; + ahi = c - (c - acy); + alo = acy - ahi; + c = splitter * bcxtail; + bhi = c - (c - bcxtail); + blo = bcxtail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + const C2len = sum(C1len, C1, 4, u, C2); + + s1 = acxtail * bcytail; + c = splitter * acxtail; + ahi = c - (c - acxtail); + alo = acxtail - ahi; + c = splitter * bcytail; + bhi = c - (c - bcytail); + blo = bcytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = acytail * bcxtail; + c = splitter * acytail; + ahi = c - (c - acytail); + alo = acytail - ahi; + c = splitter * bcxtail; + bhi = c - (c - bcxtail); + blo = bcxtail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + u[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + u[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + u[2] = _j - (u3 - bvirt) + (_i - bvirt); + u[3] = u3; + const Dlen = sum(C2len, C2, 4, u, D); + + return D[Dlen - 1]; +} + +function orient2d(ax, ay, bx, by, cx, cy) { + const detleft = (ay - cy) * (bx - cx); + const detright = (ax - cx) * (by - cy); + const det = detleft - detright; + + if (detleft === 0 || detright === 0 || (detleft > 0) !== (detright > 0)) return det; + + const detsum = Math.abs(detleft + detright); + if (Math.abs(det) >= ccwerrboundA * detsum) return det; + + return -orient2dadapt(ax, ay, bx, by, cx, cy, detsum); +} + +function orient2dfast(ax, ay, bx, by, cx, cy) { + return (ay - cy) * (bx - cx) - (ax - cx) * (by - cy); +} + +const o3derrboundA = (7 + 56 * epsilon) * epsilon; +const o3derrboundB = (3 + 28 * epsilon) * epsilon; +const o3derrboundC = (26 + 288 * epsilon) * epsilon * epsilon; + +const bc = vec(4); +const ca = vec(4); +const ab = vec(4); +const at_b = vec(4); +const at_c = vec(4); +const bt_c = vec(4); +const bt_a = vec(4); +const ct_a = vec(4); +const ct_b = vec(4); +const bct = vec(8); +const cat = vec(8); +const abt = vec(8); +const u$1 = vec(4); + +const _8 = vec(8); +const _8b = vec(8); +const _16 = vec(8); +const _12 = vec(12); + +let fin = vec(192); +let fin2 = vec(192); + +function finadd(finlen, alen, a) { + finlen = sum(finlen, fin, alen, a, fin2); + const tmp = fin; fin = fin2; fin2 = tmp; + return finlen; +} + +function tailinit(xtail, ytail, ax, ay, bx, by, a, b) { + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3, negate; + if (xtail === 0) { + if (ytail === 0) { + a[0] = 0; + b[0] = 0; + return 1; + } else { + negate = -ytail; + s1 = negate * ax; + c = splitter * negate; + ahi = c - (c - negate); + alo = negate - ahi; + c = splitter * ax; + bhi = c - (c - ax); + blo = ax - bhi; + a[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + a[1] = s1; + s1 = ytail * bx; + c = splitter * ytail; + ahi = c - (c - ytail); + alo = ytail - ahi; + c = splitter * bx; + bhi = c - (c - bx); + blo = bx - bhi; + b[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + b[1] = s1; + return 2; + } + } else { + if (ytail === 0) { + s1 = xtail * ay; + c = splitter * xtail; + ahi = c - (c - xtail); + alo = xtail - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + a[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + a[1] = s1; + negate = -xtail; + s1 = negate * by; + c = splitter * negate; + ahi = c - (c - negate); + alo = negate - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + b[0] = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + b[1] = s1; + return 2; + } else { + s1 = xtail * ay; + c = splitter * xtail; + ahi = c - (c - xtail); + alo = xtail - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ytail * ax; + c = splitter * ytail; + ahi = c - (c - ytail); + alo = ytail - ahi; + c = splitter * ax; + bhi = c - (c - ax); + blo = ax - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + a[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + a[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + a[2] = _j - (u3 - bvirt) + (_i - bvirt); + a[3] = u3; + s1 = ytail * bx; + c = splitter * ytail; + ahi = c - (c - ytail); + alo = ytail - ahi; + c = splitter * bx; + bhi = c - (c - bx); + blo = bx - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = xtail * by; + c = splitter * xtail; + ahi = c - (c - xtail); + alo = xtail - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + b[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + b[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + b[2] = _j - (u3 - bvirt) + (_i - bvirt); + b[3] = u3; + return 4; + } + } +} + +function tailadd(finlen, a, b, k, z) { + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _k, _0, s1, s0, u3; + s1 = a * b; + c = splitter * a; + ahi = c - (c - a); + alo = a - ahi; + c = splitter * b; + bhi = c - (c - b); + blo = b - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + c = splitter * k; + bhi = c - (c - k); + blo = k - bhi; + _i = s0 * k; + c = splitter * s0; + ahi = c - (c - s0); + alo = s0 - ahi; + u$1[0] = alo * blo - (_i - ahi * bhi - alo * bhi - ahi * blo); + _j = s1 * k; + c = splitter * s1; + ahi = c - (c - s1); + alo = s1 - ahi; + _0 = alo * blo - (_j - ahi * bhi - alo * bhi - ahi * blo); + _k = _i + _0; + bvirt = _k - _i; + u$1[1] = _i - (_k - bvirt) + (_0 - bvirt); + u3 = _j + _k; + u$1[2] = _k - (u3 - _j); + u$1[3] = u3; + finlen = finadd(finlen, 4, u$1); + if (z !== 0) { + c = splitter * z; + bhi = c - (c - z); + blo = z - bhi; + _i = s0 * z; + c = splitter * s0; + ahi = c - (c - s0); + alo = s0 - ahi; + u$1[0] = alo * blo - (_i - ahi * bhi - alo * bhi - ahi * blo); + _j = s1 * z; + c = splitter * s1; + ahi = c - (c - s1); + alo = s1 - ahi; + _0 = alo * blo - (_j - ahi * bhi - alo * bhi - ahi * blo); + _k = _i + _0; + bvirt = _k - _i; + u$1[1] = _i - (_k - bvirt) + (_0 - bvirt); + u3 = _j + _k; + u$1[2] = _k - (u3 - _j); + u$1[3] = u3; + finlen = finadd(finlen, 4, u$1); + } + return finlen; +} + +function orient3dadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, permanent) { + let finlen; + let adxtail, bdxtail, cdxtail; + let adytail, bdytail, cdytail; + let adztail, bdztail, cdztail; + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + const adz = az - dz; + const bdz = bz - dz; + const cdz = cz - dz; + + s1 = bdx * cdy; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * bdy; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bc[2] = _j - (u3 - bvirt) + (_i - bvirt); + bc[3] = u3; + s1 = cdx * ady; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * cdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ca[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ca[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ca[2] = _j - (u3 - bvirt) + (_i - bvirt); + ca[3] = u3; + s1 = adx * bdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * ady; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ab[2] = _j - (u3 - bvirt) + (_i - bvirt); + ab[3] = u3; + + finlen = sum( + sum( + scale(4, bc, adz, _8), _8, + scale(4, ca, bdz, _8b), _8b, _16), _16, + scale(4, ab, cdz, _8), _8, fin); + + let det = estimate(finlen, fin); + let errbound = o3derrboundB * permanent; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - adx; + adxtail = ax - (adx + bvirt) + (bvirt - dx); + bvirt = bx - bdx; + bdxtail = bx - (bdx + bvirt) + (bvirt - dx); + bvirt = cx - cdx; + cdxtail = cx - (cdx + bvirt) + (bvirt - dx); + bvirt = ay - ady; + adytail = ay - (ady + bvirt) + (bvirt - dy); + bvirt = by - bdy; + bdytail = by - (bdy + bvirt) + (bvirt - dy); + bvirt = cy - cdy; + cdytail = cy - (cdy + bvirt) + (bvirt - dy); + bvirt = az - adz; + adztail = az - (adz + bvirt) + (bvirt - dz); + bvirt = bz - bdz; + bdztail = bz - (bdz + bvirt) + (bvirt - dz); + bvirt = cz - cdz; + cdztail = cz - (cdz + bvirt) + (bvirt - dz); + + if (adxtail === 0 && bdxtail === 0 && cdxtail === 0 && + adytail === 0 && bdytail === 0 && cdytail === 0 && + adztail === 0 && bdztail === 0 && cdztail === 0) { + return det; + } + + errbound = o3derrboundC * permanent + resulterrbound * Math.abs(det); + det += + adz * (bdx * cdytail + cdy * bdxtail - (bdy * cdxtail + cdx * bdytail)) + adztail * (bdx * cdy - bdy * cdx) + + bdz * (cdx * adytail + ady * cdxtail - (cdy * adxtail + adx * cdytail)) + bdztail * (cdx * ady - cdy * adx) + + cdz * (adx * bdytail + bdy * adxtail - (ady * bdxtail + bdx * adytail)) + cdztail * (adx * bdy - ady * bdx); + if (det >= errbound || -det >= errbound) { + return det; + } + + const at_len = tailinit(adxtail, adytail, bdx, bdy, cdx, cdy, at_b, at_c); + const bt_len = tailinit(bdxtail, bdytail, cdx, cdy, adx, ady, bt_c, bt_a); + const ct_len = tailinit(cdxtail, cdytail, adx, ady, bdx, bdy, ct_a, ct_b); + + const bctlen = sum(bt_len, bt_c, ct_len, ct_b, bct); + finlen = finadd(finlen, scale(bctlen, bct, adz, _16), _16); + + const catlen = sum(ct_len, ct_a, at_len, at_c, cat); + finlen = finadd(finlen, scale(catlen, cat, bdz, _16), _16); + + const abtlen = sum(at_len, at_b, bt_len, bt_a, abt); + finlen = finadd(finlen, scale(abtlen, abt, cdz, _16), _16); + + if (adztail !== 0) { + finlen = finadd(finlen, scale(4, bc, adztail, _12), _12); + finlen = finadd(finlen, scale(bctlen, bct, adztail, _16), _16); + } + if (bdztail !== 0) { + finlen = finadd(finlen, scale(4, ca, bdztail, _12), _12); + finlen = finadd(finlen, scale(catlen, cat, bdztail, _16), _16); + } + if (cdztail !== 0) { + finlen = finadd(finlen, scale(4, ab, cdztail, _12), _12); + finlen = finadd(finlen, scale(abtlen, abt, cdztail, _16), _16); + } + + if (adxtail !== 0) { + if (bdytail !== 0) { + finlen = tailadd(finlen, adxtail, bdytail, cdz, cdztail); + } + if (cdytail !== 0) { + finlen = tailadd(finlen, -adxtail, cdytail, bdz, bdztail); + } + } + if (bdxtail !== 0) { + if (cdytail !== 0) { + finlen = tailadd(finlen, bdxtail, cdytail, adz, adztail); + } + if (adytail !== 0) { + finlen = tailadd(finlen, -bdxtail, adytail, cdz, cdztail); + } + } + if (cdxtail !== 0) { + if (adytail !== 0) { + finlen = tailadd(finlen, cdxtail, adytail, bdz, bdztail); + } + if (bdytail !== 0) { + finlen = tailadd(finlen, -cdxtail, bdytail, adz, adztail); + } + } + + return fin[finlen - 1]; +} + +function orient3d(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz) { + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + const adz = az - dz; + const bdz = bz - dz; + const cdz = cz - dz; + + const bdxcdy = bdx * cdy; + const cdxbdy = cdx * bdy; + + const cdxady = cdx * ady; + const adxcdy = adx * cdy; + + const adxbdy = adx * bdy; + const bdxady = bdx * ady; + + const det = + adz * (bdxcdy - cdxbdy) + + bdz * (cdxady - adxcdy) + + cdz * (adxbdy - bdxady); + + const permanent = + (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * Math.abs(adz) + + (Math.abs(cdxady) + Math.abs(adxcdy)) * Math.abs(bdz) + + (Math.abs(adxbdy) + Math.abs(bdxady)) * Math.abs(cdz); + + const errbound = o3derrboundA * permanent; + if (det > errbound || -det > errbound) { + return det; + } + + return orient3dadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, permanent); +} + +function orient3dfast(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz) { + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + const adz = az - dz; + const bdz = bz - dz; + const cdz = cz - dz; + + return adx * (bdy * cdz - bdz * cdy) + + bdx * (cdy * adz - cdz * ady) + + cdx * (ady * bdz - adz * bdy); +} + +const iccerrboundA = (10 + 96 * epsilon) * epsilon; +const iccerrboundB = (4 + 48 * epsilon) * epsilon; +const iccerrboundC = (44 + 576 * epsilon) * epsilon * epsilon; + +const bc$1 = vec(4); +const ca$1 = vec(4); +const ab$1 = vec(4); +const aa = vec(4); +const bb = vec(4); +const cc = vec(4); +const u$2 = vec(4); +const v = vec(4); +const axtbc = vec(8); +const aytbc = vec(8); +const bxtca = vec(8); +const bytca = vec(8); +const cxtab = vec(8); +const cytab = vec(8); +const abt$1 = vec(8); +const bct$1 = vec(8); +const cat$1 = vec(8); +const abtt = vec(4); +const bctt = vec(4); +const catt = vec(4); + +const _8$1 = vec(8); +const _16$1 = vec(16); +const _16b = vec(16); +const _16c = vec(16); +const _32 = vec(32); +const _32b = vec(32); +const _48 = vec(48); +const _64 = vec(64); + +let fin$1 = vec(1152); +let fin2$1 = vec(1152); + +function finadd$1(finlen, a, alen) { + finlen = sum(finlen, fin$1, a, alen, fin2$1); + const tmp = fin$1; fin$1 = fin2$1; fin2$1 = tmp; + return finlen; +} + +function incircleadapt(ax, ay, bx, by, cx, cy, dx, dy, permanent) { + let finlen; + let adxtail, bdxtail, cdxtail, adytail, bdytail, cdytail; + let axtbclen, aytbclen, bxtcalen, bytcalen, cxtablen, cytablen; + let abtlen, bctlen, catlen; + let abttlen, bcttlen, cattlen; + let n1, n0; + + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + + s1 = bdx * cdy; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * bdy; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc$1[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc$1[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bc$1[2] = _j - (u3 - bvirt) + (_i - bvirt); + bc$1[3] = u3; + s1 = cdx * ady; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * cdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ca$1[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ca$1[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ca$1[2] = _j - (u3 - bvirt) + (_i - bvirt); + ca$1[3] = u3; + s1 = adx * bdy; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * ady; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab$1[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab$1[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ab$1[2] = _j - (u3 - bvirt) + (_i - bvirt); + ab$1[3] = u3; + + finlen = sum( + sum( + sum( + scale(scale(4, bc$1, adx, _8$1), _8$1, adx, _16$1), _16$1, + scale(scale(4, bc$1, ady, _8$1), _8$1, ady, _16b), _16b, _32), _32, + sum( + scale(scale(4, ca$1, bdx, _8$1), _8$1, bdx, _16$1), _16$1, + scale(scale(4, ca$1, bdy, _8$1), _8$1, bdy, _16b), _16b, _32b), _32b, _64), _64, + sum( + scale(scale(4, ab$1, cdx, _8$1), _8$1, cdx, _16$1), _16$1, + scale(scale(4, ab$1, cdy, _8$1), _8$1, cdy, _16b), _16b, _32), _32, fin$1); + + let det = estimate(finlen, fin$1); + let errbound = iccerrboundB * permanent; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - adx; + adxtail = ax - (adx + bvirt) + (bvirt - dx); + bvirt = ay - ady; + adytail = ay - (ady + bvirt) + (bvirt - dy); + bvirt = bx - bdx; + bdxtail = bx - (bdx + bvirt) + (bvirt - dx); + bvirt = by - bdy; + bdytail = by - (bdy + bvirt) + (bvirt - dy); + bvirt = cx - cdx; + cdxtail = cx - (cdx + bvirt) + (bvirt - dx); + bvirt = cy - cdy; + cdytail = cy - (cdy + bvirt) + (bvirt - dy); + if (adxtail === 0 && bdxtail === 0 && cdxtail === 0 && adytail === 0 && bdytail === 0 && cdytail === 0) { + return det; + } + + errbound = iccerrboundC * permanent + resulterrbound * Math.abs(det); + det += ((adx * adx + ady * ady) * ((bdx * cdytail + cdy * bdxtail) - (bdy * cdxtail + cdx * bdytail)) + + 2 * (adx * adxtail + ady * adytail) * (bdx * cdy - bdy * cdx)) + + ((bdx * bdx + bdy * bdy) * ((cdx * adytail + ady * cdxtail) - (cdy * adxtail + adx * cdytail)) + + 2 * (bdx * bdxtail + bdy * bdytail) * (cdx * ady - cdy * adx)) + + ((cdx * cdx + cdy * cdy) * ((adx * bdytail + bdy * adxtail) - (ady * bdxtail + bdx * adytail)) + + 2 * (cdx * cdxtail + cdy * cdytail) * (adx * bdy - ady * bdx)); + + if (det >= errbound || -det >= errbound) { + return det; + } + + if (bdxtail !== 0 || bdytail !== 0 || cdxtail !== 0 || cdytail !== 0) { + s1 = adx * adx; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo); + t1 = ady * ady; + c = splitter * ady; + ahi = c - (c - ady); + alo = ady - ahi; + t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo); + _i = s0 + t0; + bvirt = _i - s0; + aa[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + aa[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + aa[2] = _j - (u3 - bvirt) + (_i - bvirt); + aa[3] = u3; + } + if (cdxtail !== 0 || cdytail !== 0 || adxtail !== 0 || adytail !== 0) { + s1 = bdx * bdx; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo); + t1 = bdy * bdy; + c = splitter * bdy; + ahi = c - (c - bdy); + alo = bdy - ahi; + t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo); + _i = s0 + t0; + bvirt = _i - s0; + bb[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + bb[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + bb[2] = _j - (u3 - bvirt) + (_i - bvirt); + bb[3] = u3; + } + if (adxtail !== 0 || adytail !== 0 || bdxtail !== 0 || bdytail !== 0) { + s1 = cdx * cdx; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + s0 = alo * alo - (s1 - ahi * ahi - (ahi + ahi) * alo); + t1 = cdy * cdy; + c = splitter * cdy; + ahi = c - (c - cdy); + alo = cdy - ahi; + t0 = alo * alo - (t1 - ahi * ahi - (ahi + ahi) * alo); + _i = s0 + t0; + bvirt = _i - s0; + cc[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + cc[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + cc[2] = _j - (u3 - bvirt) + (_i - bvirt); + cc[3] = u3; + } + + if (adxtail !== 0) { + axtbclen = scale(4, bc$1, adxtail, axtbc); + finlen = finadd$1(finlen, sum_three( + scale(axtbclen, axtbc, 2 * adx, _16$1), _16$1, + scale(scale(4, cc, adxtail, _8$1), _8$1, bdy, _16b), _16b, + scale(scale(4, bb, adxtail, _8$1), _8$1, -cdy, _16c), _16c, _32, _48), _48); + } + if (adytail !== 0) { + aytbclen = scale(4, bc$1, adytail, aytbc); + finlen = finadd$1(finlen, sum_three( + scale(aytbclen, aytbc, 2 * ady, _16$1), _16$1, + scale(scale(4, bb, adytail, _8$1), _8$1, cdx, _16b), _16b, + scale(scale(4, cc, adytail, _8$1), _8$1, -bdx, _16c), _16c, _32, _48), _48); + } + if (bdxtail !== 0) { + bxtcalen = scale(4, ca$1, bdxtail, bxtca); + finlen = finadd$1(finlen, sum_three( + scale(bxtcalen, bxtca, 2 * bdx, _16$1), _16$1, + scale(scale(4, aa, bdxtail, _8$1), _8$1, cdy, _16b), _16b, + scale(scale(4, cc, bdxtail, _8$1), _8$1, -ady, _16c), _16c, _32, _48), _48); + } + if (bdytail !== 0) { + bytcalen = scale(4, ca$1, bdytail, bytca); + finlen = finadd$1(finlen, sum_three( + scale(bytcalen, bytca, 2 * bdy, _16$1), _16$1, + scale(scale(4, cc, bdytail, _8$1), _8$1, adx, _16b), _16b, + scale(scale(4, aa, bdytail, _8$1), _8$1, -cdx, _16c), _16c, _32, _48), _48); + } + if (cdxtail !== 0) { + cxtablen = scale(4, ab$1, cdxtail, cxtab); + finlen = finadd$1(finlen, sum_three( + scale(cxtablen, cxtab, 2 * cdx, _16$1), _16$1, + scale(scale(4, bb, cdxtail, _8$1), _8$1, ady, _16b), _16b, + scale(scale(4, aa, cdxtail, _8$1), _8$1, -bdy, _16c), _16c, _32, _48), _48); + } + if (cdytail !== 0) { + cytablen = scale(4, ab$1, cdytail, cytab); + finlen = finadd$1(finlen, sum_three( + scale(cytablen, cytab, 2 * cdy, _16$1), _16$1, + scale(scale(4, aa, cdytail, _8$1), _8$1, bdx, _16b), _16b, + scale(scale(4, bb, cdytail, _8$1), _8$1, -adx, _16c), _16c, _32, _48), _48); + } + + if (adxtail !== 0 || adytail !== 0) { + if (bdxtail !== 0 || bdytail !== 0 || cdxtail !== 0 || cdytail !== 0) { + s1 = bdxtail * cdy; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * cdy; + bhi = c - (c - cdy); + blo = cdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * cdytail; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * cdytail; + bhi = c - (c - cdytail); + blo = cdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + u$2[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + u$2[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + u$2[2] = _j - (u3 - bvirt) + (_i - bvirt); + u$2[3] = u3; + s1 = cdxtail * -bdy; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * -bdy; + bhi = c - (c - -bdy); + blo = -bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * -bdytail; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * -bdytail; + bhi = c - (c - -bdytail); + blo = -bdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + v[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + v[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + v[2] = _j - (u3 - bvirt) + (_i - bvirt); + v[3] = u3; + bctlen = sum(4, u$2, 4, v, bct$1); + s1 = bdxtail * cdytail; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * cdytail; + bhi = c - (c - cdytail); + blo = cdytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdxtail * bdytail; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * bdytail; + bhi = c - (c - bdytail); + blo = bdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bctt[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bctt[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bctt[2] = _j - (u3 - bvirt) + (_i - bvirt); + bctt[3] = u3; + bcttlen = 4; + } else { + bct$1[0] = 0; + bctlen = 1; + bctt[0] = 0; + bcttlen = 1; + } + if (adxtail !== 0) { + const len = scale(bctlen, bct$1, adxtail, _16c); + finlen = finadd$1(finlen, sum( + scale(axtbclen, axtbc, adxtail, _16$1), _16$1, + scale(len, _16c, 2 * adx, _32), _32, _48), _48); + + const len2 = scale(bcttlen, bctt, adxtail, _8$1); + finlen = finadd$1(finlen, sum_three( + scale(len2, _8$1, 2 * adx, _16$1), _16$1, + scale(len2, _8$1, adxtail, _16b), _16b, + scale(len, _16c, adxtail, _32), _32, _32b, _64), _64); + + if (bdytail !== 0) { + finlen = finadd$1(finlen, scale(scale(4, cc, adxtail, _8$1), _8$1, bdytail, _16$1), _16$1); + } + if (cdytail !== 0) { + finlen = finadd$1(finlen, scale(scale(4, bb, -adxtail, _8$1), _8$1, cdytail, _16$1), _16$1); + } + } + if (adytail !== 0) { + const len = scale(bctlen, bct$1, adytail, _16c); + finlen = finadd$1(finlen, sum( + scale(aytbclen, aytbc, adytail, _16$1), _16$1, + scale(len, _16c, 2 * ady, _32), _32, _48), _48); + + const len2 = scale(bcttlen, bctt, adytail, _8$1); + finlen = finadd$1(finlen, sum_three( + scale(len2, _8$1, 2 * ady, _16$1), _16$1, + scale(len2, _8$1, adytail, _16b), _16b, + scale(len, _16c, adytail, _32), _32, _32b, _64), _64); + } + } + if (bdxtail !== 0 || bdytail !== 0) { + if (cdxtail !== 0 || cdytail !== 0 || adxtail !== 0 || adytail !== 0) { + s1 = cdxtail * ady; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * ady; + bhi = c - (c - ady); + blo = ady - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cdx * adytail; + c = splitter * cdx; + ahi = c - (c - cdx); + alo = cdx - ahi; + c = splitter * adytail; + bhi = c - (c - adytail); + blo = adytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + u$2[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + u$2[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + u$2[2] = _j - (u3 - bvirt) + (_i - bvirt); + u$2[3] = u3; + n1 = -cdy; + n0 = -cdytail; + s1 = adxtail * n1; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * n1; + bhi = c - (c - n1); + blo = n1 - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * n0; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * n0; + bhi = c - (c - n0); + blo = n0 - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + v[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + v[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + v[2] = _j - (u3 - bvirt) + (_i - bvirt); + v[3] = u3; + catlen = sum(4, u$2, 4, v, cat$1); + s1 = cdxtail * adytail; + c = splitter * cdxtail; + ahi = c - (c - cdxtail); + alo = cdxtail - ahi; + c = splitter * adytail; + bhi = c - (c - adytail); + blo = adytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adxtail * cdytail; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * cdytail; + bhi = c - (c - cdytail); + blo = cdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + catt[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + catt[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + catt[2] = _j - (u3 - bvirt) + (_i - bvirt); + catt[3] = u3; + cattlen = 4; + } else { + cat$1[0] = 0; + catlen = 1; + catt[0] = 0; + cattlen = 1; + } + if (bdxtail !== 0) { + const len = scale(catlen, cat$1, bdxtail, _16c); + finlen = finadd$1(finlen, sum( + scale(bxtcalen, bxtca, bdxtail, _16$1), _16$1, + scale(len, _16c, 2 * bdx, _32), _32, _48), _48); + + const len2 = scale(cattlen, catt, bdxtail, _8$1); + finlen = finadd$1(finlen, sum_three( + scale(len2, _8$1, 2 * bdx, _16$1), _16$1, + scale(len2, _8$1, bdxtail, _16b), _16b, + scale(len, _16c, bdxtail, _32), _32, _32b, _64), _64); + + if (cdytail !== 0) { + finlen = finadd$1(finlen, scale(scale(4, aa, bdxtail, _8$1), _8$1, cdytail, _16$1), _16$1); + } + if (adytail !== 0) { + finlen = finadd$1(finlen, scale(scale(4, cc, -bdxtail, _8$1), _8$1, adytail, _16$1), _16$1); + } + } + if (bdytail !== 0) { + const len = scale(catlen, cat$1, bdytail, _16c); + finlen = finadd$1(finlen, sum( + scale(bytcalen, bytca, bdytail, _16$1), _16$1, + scale(len, _16c, 2 * bdy, _32), _32, _48), _48); + + const len2 = scale(cattlen, catt, bdytail, _8$1); + finlen = finadd$1(finlen, sum_three( + scale(len2, _8$1, 2 * bdy, _16$1), _16$1, + scale(len2, _8$1, bdytail, _16b), _16b, + scale(len, _16c, bdytail, _32), _32, _32b, _64), _64); + } + } + if (cdxtail !== 0 || cdytail !== 0) { + if (adxtail !== 0 || adytail !== 0 || bdxtail !== 0 || bdytail !== 0) { + s1 = adxtail * bdy; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * bdy; + bhi = c - (c - bdy); + blo = bdy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = adx * bdytail; + c = splitter * adx; + ahi = c - (c - adx); + alo = adx - ahi; + c = splitter * bdytail; + bhi = c - (c - bdytail); + blo = bdytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + u$2[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + u$2[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + u$2[2] = _j - (u3 - bvirt) + (_i - bvirt); + u$2[3] = u3; + n1 = -ady; + n0 = -adytail; + s1 = bdxtail * n1; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * n1; + bhi = c - (c - n1); + blo = n1 - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdx * n0; + c = splitter * bdx; + ahi = c - (c - bdx); + alo = bdx - ahi; + c = splitter * n0; + bhi = c - (c - n0); + blo = n0 - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 + t0; + bvirt = _i - s0; + v[0] = s0 - (_i - bvirt) + (t0 - bvirt); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 + t1; + bvirt = _i - _0; + v[1] = _0 - (_i - bvirt) + (t1 - bvirt); + u3 = _j + _i; + bvirt = u3 - _j; + v[2] = _j - (u3 - bvirt) + (_i - bvirt); + v[3] = u3; + abtlen = sum(4, u$2, 4, v, abt$1); + s1 = adxtail * bdytail; + c = splitter * adxtail; + ahi = c - (c - adxtail); + alo = adxtail - ahi; + c = splitter * bdytail; + bhi = c - (c - bdytail); + blo = bdytail - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bdxtail * adytail; + c = splitter * bdxtail; + ahi = c - (c - bdxtail); + alo = bdxtail - ahi; + c = splitter * adytail; + bhi = c - (c - adytail); + blo = adytail - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + abtt[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + abtt[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + abtt[2] = _j - (u3 - bvirt) + (_i - bvirt); + abtt[3] = u3; + abttlen = 4; + } else { + abt$1[0] = 0; + abtlen = 1; + abtt[0] = 0; + abttlen = 1; + } + if (cdxtail !== 0) { + const len = scale(abtlen, abt$1, cdxtail, _16c); + finlen = finadd$1(finlen, sum( + scale(cxtablen, cxtab, cdxtail, _16$1), _16$1, + scale(len, _16c, 2 * cdx, _32), _32, _48), _48); + + const len2 = scale(abttlen, abtt, cdxtail, _8$1); + finlen = finadd$1(finlen, sum_three( + scale(len2, _8$1, 2 * cdx, _16$1), _16$1, + scale(len2, _8$1, cdxtail, _16b), _16b, + scale(len, _16c, cdxtail, _32), _32, _32b, _64), _64); + + if (adytail !== 0) { + finlen = finadd$1(finlen, scale(scale(4, bb, cdxtail, _8$1), _8$1, adytail, _16$1), _16$1); + } + if (bdytail !== 0) { + finlen = finadd$1(finlen, scale(scale(4, aa, -cdxtail, _8$1), _8$1, bdytail, _16$1), _16$1); + } + } + if (cdytail !== 0) { + const len = scale(abtlen, abt$1, cdytail, _16c); + finlen = finadd$1(finlen, sum( + scale(cytablen, cytab, cdytail, _16$1), _16$1, + scale(len, _16c, 2 * cdy, _32), _32, _48), _48); + + const len2 = scale(abttlen, abtt, cdytail, _8$1); + finlen = finadd$1(finlen, sum_three( + scale(len2, _8$1, 2 * cdy, _16$1), _16$1, + scale(len2, _8$1, cdytail, _16b), _16b, + scale(len, _16c, cdytail, _32), _32, _32b, _64), _64); + } + } + + return fin$1[finlen - 1]; +} + +function incircle(ax, ay, bx, by, cx, cy, dx, dy) { + const adx = ax - dx; + const bdx = bx - dx; + const cdx = cx - dx; + const ady = ay - dy; + const bdy = by - dy; + const cdy = cy - dy; + + const bdxcdy = bdx * cdy; + const cdxbdy = cdx * bdy; + const alift = adx * adx + ady * ady; + + const cdxady = cdx * ady; + const adxcdy = adx * cdy; + const blift = bdx * bdx + bdy * bdy; + + const adxbdy = adx * bdy; + const bdxady = bdx * ady; + const clift = cdx * cdx + cdy * cdy; + + const det = + alift * (bdxcdy - cdxbdy) + + blift * (cdxady - adxcdy) + + clift * (adxbdy - bdxady); + + const permanent = + (Math.abs(bdxcdy) + Math.abs(cdxbdy)) * alift + + (Math.abs(cdxady) + Math.abs(adxcdy)) * blift + + (Math.abs(adxbdy) + Math.abs(bdxady)) * clift; + + const errbound = iccerrboundA * permanent; + + if (det > errbound || -det > errbound) { + return det; + } + return incircleadapt(ax, ay, bx, by, cx, cy, dx, dy, permanent); +} + +function incirclefast(ax, ay, bx, by, cx, cy, dx, dy) { + const adx = ax - dx; + const ady = ay - dy; + const bdx = bx - dx; + const bdy = by - dy; + const cdx = cx - dx; + const cdy = cy - dy; + + const abdet = adx * bdy - bdx * ady; + const bcdet = bdx * cdy - cdx * bdy; + const cadet = cdx * ady - adx * cdy; + const alift = adx * adx + ady * ady; + const blift = bdx * bdx + bdy * bdy; + const clift = cdx * cdx + cdy * cdy; + + return alift * bcdet + blift * cadet + clift * abdet; +} + +const isperrboundA = (16 + 224 * epsilon) * epsilon; +const isperrboundB = (5 + 72 * epsilon) * epsilon; +const isperrboundC = (71 + 1408 * epsilon) * epsilon * epsilon; + +const ab$2 = vec(4); +const bc$2 = vec(4); +const cd = vec(4); +const de = vec(4); +const ea = vec(4); +const ac = vec(4); +const bd = vec(4); +const ce = vec(4); +const da = vec(4); +const eb = vec(4); + +const abc = vec(24); +const bcd = vec(24); +const cde = vec(24); +const dea = vec(24); +const eab = vec(24); +const abd = vec(24); +const bce = vec(24); +const cda = vec(24); +const deb = vec(24); +const eac = vec(24); + +const adet = vec(1152); +const bdet = vec(1152); +const cdet = vec(1152); +const ddet = vec(1152); +const edet = vec(1152); +const abdet = vec(2304); +const cddet = vec(2304); +const cdedet = vec(3456); +const deter = vec(5760); + +const _8$2 = vec(8); +const _8b$1 = vec(8); +const _8c = vec(8); +const _16$2 = vec(16); +const _24 = vec(24); +const _48$1 = vec(48); +const _48b = vec(48); +const _96 = vec(96); +const _192 = vec(192); +const _384x = vec(384); +const _384y = vec(384); +const _384z = vec(384); +const _768 = vec(768); + +function sum_three_scale(a, b, c, az, bz, cz, out) { + return sum_three( + scale(4, a, az, _8$2), _8$2, + scale(4, b, bz, _8b$1), _8b$1, + scale(4, c, cz, _8c), _8c, _16$2, out); +} + +function liftexact(alen, a, blen, b, clen, c, dlen, d, x, y, z, out) { + const len = sum( + sum(alen, a, blen, b, _48$1), _48$1, + negate(sum(clen, c, dlen, d, _48b), _48b), _48b, _96); + + return sum_three( + scale(scale(len, _96, x, _192), _192, x, _384x), _384x, + scale(scale(len, _96, y, _192), _192, y, _384y), _384y, + scale(scale(len, _96, z, _192), _192, z, _384z), _384z, _768, out); +} + +function insphereexact(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez) { + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0, u3; + + s1 = ax * by; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bx * ay; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab$2[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab$2[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ab$2[2] = _j - (u3 - bvirt) + (_i - bvirt); + ab$2[3] = u3; + s1 = bx * cy; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cx * by; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc$2[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc$2[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bc$2[2] = _j - (u3 - bvirt) + (_i - bvirt); + bc$2[3] = u3; + s1 = cx * dy; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dx * cy; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + cd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + cd[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + cd[2] = _j - (u3 - bvirt) + (_i - bvirt); + cd[3] = u3; + s1 = dx * ey; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ex * dy; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + de[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + de[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + de[2] = _j - (u3 - bvirt) + (_i - bvirt); + de[3] = u3; + s1 = ex * ay; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ax * ey; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ea[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ea[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ea[2] = _j - (u3 - bvirt) + (_i - bvirt); + ea[3] = u3; + s1 = ax * cy; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cx * ay; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ac[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ac[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ac[2] = _j - (u3 - bvirt) + (_i - bvirt); + ac[3] = u3; + s1 = bx * dy; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dx * by; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bd[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + bd[2] = _j - (u3 - bvirt) + (_i - bvirt); + bd[3] = u3; + s1 = cx * ey; + c = splitter * cx; + ahi = c - (c - cx); + alo = cx - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ex * cy; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * cy; + bhi = c - (c - cy); + blo = cy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ce[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ce[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + ce[2] = _j - (u3 - bvirt) + (_i - bvirt); + ce[3] = u3; + s1 = dx * ay; + c = splitter * dx; + ahi = c - (c - dx); + alo = dx - ahi; + c = splitter * ay; + bhi = c - (c - ay); + blo = ay - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = ax * dy; + c = splitter * ax; + ahi = c - (c - ax); + alo = ax - ahi; + c = splitter * dy; + bhi = c - (c - dy); + blo = dy - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + da[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + da[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + da[2] = _j - (u3 - bvirt) + (_i - bvirt); + da[3] = u3; + s1 = ex * by; + c = splitter * ex; + ahi = c - (c - ex); + alo = ex - ahi; + c = splitter * by; + bhi = c - (c - by); + blo = by - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bx * ey; + c = splitter * bx; + ahi = c - (c - bx); + alo = bx - ahi; + c = splitter * ey; + bhi = c - (c - ey); + blo = ey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + eb[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + eb[1] = _0 - (_i + bvirt) + (bvirt - t1); + u3 = _j + _i; + bvirt = u3 - _j; + eb[2] = _j - (u3 - bvirt) + (_i - bvirt); + eb[3] = u3; + + const abclen = sum_three_scale(ab$2, bc$2, ac, cz, az, -bz, abc); + const bcdlen = sum_three_scale(bc$2, cd, bd, dz, bz, -cz, bcd); + const cdelen = sum_three_scale(cd, de, ce, ez, cz, -dz, cde); + const dealen = sum_three_scale(de, ea, da, az, dz, -ez, dea); + const eablen = sum_three_scale(ea, ab$2, eb, bz, ez, -az, eab); + const abdlen = sum_three_scale(ab$2, bd, da, dz, az, bz, abd); + const bcelen = sum_three_scale(bc$2, ce, eb, ez, bz, cz, bce); + const cdalen = sum_three_scale(cd, da, ac, az, cz, dz, cda); + const deblen = sum_three_scale(de, eb, bd, bz, dz, ez, deb); + const eaclen = sum_three_scale(ea, ac, ce, cz, ez, az, eac); + + const deterlen = sum_three( + liftexact(cdelen, cde, bcelen, bce, deblen, deb, bcdlen, bcd, ax, ay, az, adet), adet, + liftexact(dealen, dea, cdalen, cda, eaclen, eac, cdelen, cde, bx, by, bz, bdet), bdet, + sum_three( + liftexact(eablen, eab, deblen, deb, abdlen, abd, dealen, dea, cx, cy, cz, cdet), cdet, + liftexact(abclen, abc, eaclen, eac, bcelen, bce, eablen, eab, dx, dy, dz, ddet), ddet, + liftexact(bcdlen, bcd, abdlen, abd, cdalen, cda, abclen, abc, ex, ey, ez, edet), edet, cddet, cdedet), cdedet, abdet, deter); + + return deter[deterlen - 1]; +} + +const xdet = vec(96); +const ydet = vec(96); +const zdet = vec(96); +const fin$2 = vec(1152); + +function liftadapt(a, b, c, az, bz, cz, x, y, z, out) { + const len = sum_three_scale(a, b, c, az, bz, cz, _24); + return sum_three( + scale(scale(len, _24, x, _48$1), _48$1, x, xdet), xdet, + scale(scale(len, _24, y, _48$1), _48$1, y, ydet), ydet, + scale(scale(len, _24, z, _48$1), _48$1, z, zdet), zdet, _192, out); +} + +function insphereadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez, permanent) { + let ab3, bc3, cd3, da3, ac3, bd3; + + let aextail, bextail, cextail, dextail; + let aeytail, beytail, ceytail, deytail; + let aeztail, beztail, ceztail, deztail; + + let bvirt, c, ahi, alo, bhi, blo, _i, _j, _0, s1, s0, t1, t0; + + const aex = ax - ex; + const bex = bx - ex; + const cex = cx - ex; + const dex = dx - ex; + const aey = ay - ey; + const bey = by - ey; + const cey = cy - ey; + const dey = dy - ey; + const aez = az - ez; + const bez = bz - ez; + const cez = cz - ez; + const dez = dz - ez; + + s1 = aex * bey; + c = splitter * aex; + ahi = c - (c - aex); + alo = aex - ahi; + c = splitter * bey; + bhi = c - (c - bey); + blo = bey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = bex * aey; + c = splitter * bex; + ahi = c - (c - bex); + alo = bex - ahi; + c = splitter * aey; + bhi = c - (c - aey); + blo = aey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ab$2[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ab$2[1] = _0 - (_i + bvirt) + (bvirt - t1); + ab3 = _j + _i; + bvirt = ab3 - _j; + ab$2[2] = _j - (ab3 - bvirt) + (_i - bvirt); + ab$2[3] = ab3; + s1 = bex * cey; + c = splitter * bex; + ahi = c - (c - bex); + alo = bex - ahi; + c = splitter * cey; + bhi = c - (c - cey); + blo = cey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cex * bey; + c = splitter * cex; + ahi = c - (c - cex); + alo = cex - ahi; + c = splitter * bey; + bhi = c - (c - bey); + blo = bey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bc$2[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bc$2[1] = _0 - (_i + bvirt) + (bvirt - t1); + bc3 = _j + _i; + bvirt = bc3 - _j; + bc$2[2] = _j - (bc3 - bvirt) + (_i - bvirt); + bc$2[3] = bc3; + s1 = cex * dey; + c = splitter * cex; + ahi = c - (c - cex); + alo = cex - ahi; + c = splitter * dey; + bhi = c - (c - dey); + blo = dey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dex * cey; + c = splitter * dex; + ahi = c - (c - dex); + alo = dex - ahi; + c = splitter * cey; + bhi = c - (c - cey); + blo = cey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + cd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + cd[1] = _0 - (_i + bvirt) + (bvirt - t1); + cd3 = _j + _i; + bvirt = cd3 - _j; + cd[2] = _j - (cd3 - bvirt) + (_i - bvirt); + cd[3] = cd3; + s1 = dex * aey; + c = splitter * dex; + ahi = c - (c - dex); + alo = dex - ahi; + c = splitter * aey; + bhi = c - (c - aey); + blo = aey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = aex * dey; + c = splitter * aex; + ahi = c - (c - aex); + alo = aex - ahi; + c = splitter * dey; + bhi = c - (c - dey); + blo = dey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + da[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + da[1] = _0 - (_i + bvirt) + (bvirt - t1); + da3 = _j + _i; + bvirt = da3 - _j; + da[2] = _j - (da3 - bvirt) + (_i - bvirt); + da[3] = da3; + s1 = aex * cey; + c = splitter * aex; + ahi = c - (c - aex); + alo = aex - ahi; + c = splitter * cey; + bhi = c - (c - cey); + blo = cey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = cex * aey; + c = splitter * cex; + ahi = c - (c - cex); + alo = cex - ahi; + c = splitter * aey; + bhi = c - (c - aey); + blo = aey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + ac[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + ac[1] = _0 - (_i + bvirt) + (bvirt - t1); + ac3 = _j + _i; + bvirt = ac3 - _j; + ac[2] = _j - (ac3 - bvirt) + (_i - bvirt); + ac[3] = ac3; + s1 = bex * dey; + c = splitter * bex; + ahi = c - (c - bex); + alo = bex - ahi; + c = splitter * dey; + bhi = c - (c - dey); + blo = dey - bhi; + s0 = alo * blo - (s1 - ahi * bhi - alo * bhi - ahi * blo); + t1 = dex * bey; + c = splitter * dex; + ahi = c - (c - dex); + alo = dex - ahi; + c = splitter * bey; + bhi = c - (c - bey); + blo = bey - bhi; + t0 = alo * blo - (t1 - ahi * bhi - alo * bhi - ahi * blo); + _i = s0 - t0; + bvirt = s0 - _i; + bd[0] = s0 - (_i + bvirt) + (bvirt - t0); + _j = s1 + _i; + bvirt = _j - s1; + _0 = s1 - (_j - bvirt) + (_i - bvirt); + _i = _0 - t1; + bvirt = _0 - _i; + bd[1] = _0 - (_i + bvirt) + (bvirt - t1); + bd3 = _j + _i; + bvirt = bd3 - _j; + bd[2] = _j - (bd3 - bvirt) + (_i - bvirt); + bd[3] = bd3; + + const finlen = sum( + sum( + negate(liftadapt(bc$2, cd, bd, dez, bez, -cez, aex, aey, aez, adet), adet), adet, + liftadapt(cd, da, ac, aez, cez, dez, bex, bey, bez, bdet), bdet, abdet), abdet, + sum( + negate(liftadapt(da, ab$2, bd, bez, dez, aez, cex, cey, cez, cdet), cdet), cdet, + liftadapt(ab$2, bc$2, ac, cez, aez, -bez, dex, dey, dez, ddet), ddet, cddet), cddet, fin$2); + + let det = estimate(finlen, fin$2); + let errbound = isperrboundB * permanent; + if (det >= errbound || -det >= errbound) { + return det; + } + + bvirt = ax - aex; + aextail = ax - (aex + bvirt) + (bvirt - ex); + bvirt = ay - aey; + aeytail = ay - (aey + bvirt) + (bvirt - ey); + bvirt = az - aez; + aeztail = az - (aez + bvirt) + (bvirt - ez); + bvirt = bx - bex; + bextail = bx - (bex + bvirt) + (bvirt - ex); + bvirt = by - bey; + beytail = by - (bey + bvirt) + (bvirt - ey); + bvirt = bz - bez; + beztail = bz - (bez + bvirt) + (bvirt - ez); + bvirt = cx - cex; + cextail = cx - (cex + bvirt) + (bvirt - ex); + bvirt = cy - cey; + ceytail = cy - (cey + bvirt) + (bvirt - ey); + bvirt = cz - cez; + ceztail = cz - (cez + bvirt) + (bvirt - ez); + bvirt = dx - dex; + dextail = dx - (dex + bvirt) + (bvirt - ex); + bvirt = dy - dey; + deytail = dy - (dey + bvirt) + (bvirt - ey); + bvirt = dz - dez; + deztail = dz - (dez + bvirt) + (bvirt - ez); + if (aextail === 0 && aeytail === 0 && aeztail === 0 && + bextail === 0 && beytail === 0 && beztail === 0 && + cextail === 0 && ceytail === 0 && ceztail === 0 && + dextail === 0 && deytail === 0 && deztail === 0) { + return det; + } + + errbound = isperrboundC * permanent + resulterrbound * Math.abs(det); + + const abeps = (aex * beytail + bey * aextail) - (aey * bextail + bex * aeytail); + const bceps = (bex * ceytail + cey * bextail) - (bey * cextail + cex * beytail); + const cdeps = (cex * deytail + dey * cextail) - (cey * dextail + dex * ceytail); + const daeps = (dex * aeytail + aey * dextail) - (dey * aextail + aex * deytail); + const aceps = (aex * ceytail + cey * aextail) - (aey * cextail + cex * aeytail); + const bdeps = (bex * deytail + dey * bextail) - (bey * dextail + dex * beytail); + det += + (((bex * bex + bey * bey + bez * bez) * ((cez * daeps + dez * aceps + aez * cdeps) + + (ceztail * da3 + deztail * ac3 + aeztail * cd3)) + (dex * dex + dey * dey + dez * dez) * + ((aez * bceps - bez * aceps + cez * abeps) + (aeztail * bc3 - beztail * ac3 + ceztail * ab3))) - + ((aex * aex + aey * aey + aez * aez) * ((bez * cdeps - cez * bdeps + dez * bceps) + + (beztail * cd3 - ceztail * bd3 + deztail * bc3)) + (cex * cex + cey * cey + cez * cez) * + ((dez * abeps + aez * bdeps + bez * daeps) + (deztail * ab3 + aeztail * bd3 + beztail * da3)))) + + 2 * (((bex * bextail + bey * beytail + bez * beztail) * (cez * da3 + dez * ac3 + aez * cd3) + + (dex * dextail + dey * deytail + dez * deztail) * (aez * bc3 - bez * ac3 + cez * ab3)) - + ((aex * aextail + aey * aeytail + aez * aeztail) * (bez * cd3 - cez * bd3 + dez * bc3) + + (cex * cextail + cey * ceytail + cez * ceztail) * (dez * ab3 + aez * bd3 + bez * da3))); + + if (det >= errbound || -det >= errbound) { + return det; + } + + return insphereexact(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez); +} + +function insphere(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez) { + const aex = ax - ex; + const bex = bx - ex; + const cex = cx - ex; + const dex = dx - ex; + const aey = ay - ey; + const bey = by - ey; + const cey = cy - ey; + const dey = dy - ey; + const aez = az - ez; + const bez = bz - ez; + const cez = cz - ez; + const dez = dz - ez; + + const aexbey = aex * bey; + const bexaey = bex * aey; + const ab = aexbey - bexaey; + const bexcey = bex * cey; + const cexbey = cex * bey; + const bc = bexcey - cexbey; + const cexdey = cex * dey; + const dexcey = dex * cey; + const cd = cexdey - dexcey; + const dexaey = dex * aey; + const aexdey = aex * dey; + const da = dexaey - aexdey; + const aexcey = aex * cey; + const cexaey = cex * aey; + const ac = aexcey - cexaey; + const bexdey = bex * dey; + const dexbey = dex * bey; + const bd = bexdey - dexbey; + + const abc = aez * bc - bez * ac + cez * ab; + const bcd = bez * cd - cez * bd + dez * bc; + const cda = cez * da + dez * ac + aez * cd; + const dab = dez * ab + aez * bd + bez * da; + + const alift = aex * aex + aey * aey + aez * aez; + const blift = bex * bex + bey * bey + bez * bez; + const clift = cex * cex + cey * cey + cez * cez; + const dlift = dex * dex + dey * dey + dez * dez; + + const det = (clift * dab - dlift * abc) + (alift * bcd - blift * cda); + + const aezplus = Math.abs(aez); + const bezplus = Math.abs(bez); + const cezplus = Math.abs(cez); + const dezplus = Math.abs(dez); + const aexbeyplus = Math.abs(aexbey); + const bexaeyplus = Math.abs(bexaey); + const bexceyplus = Math.abs(bexcey); + const cexbeyplus = Math.abs(cexbey); + const cexdeyplus = Math.abs(cexdey); + const dexceyplus = Math.abs(dexcey); + const dexaeyplus = Math.abs(dexaey); + const aexdeyplus = Math.abs(aexdey); + const aexceyplus = Math.abs(aexcey); + const cexaeyplus = Math.abs(cexaey); + const bexdeyplus = Math.abs(bexdey); + const dexbeyplus = Math.abs(dexbey); + const permanent = + ((cexdeyplus + dexceyplus) * bezplus + (dexbeyplus + bexdeyplus) * cezplus + (bexceyplus + cexbeyplus) * dezplus) * alift + + ((dexaeyplus + aexdeyplus) * cezplus + (aexceyplus + cexaeyplus) * dezplus + (cexdeyplus + dexceyplus) * aezplus) * blift + + ((aexbeyplus + bexaeyplus) * dezplus + (bexdeyplus + dexbeyplus) * aezplus + (dexaeyplus + aexdeyplus) * bezplus) * clift + + ((bexceyplus + cexbeyplus) * aezplus + (cexaeyplus + aexceyplus) * bezplus + (aexbeyplus + bexaeyplus) * cezplus) * dlift; + + const errbound = isperrboundA * permanent; + if (det > errbound || -det > errbound) { + return det; + } + return -insphereadapt(ax, ay, az, bx, by, bz, cx, cy, cz, dx, dy, dz, ex, ey, ez, permanent); +} + +function inspherefast(pax, pay, paz, pbx, pby, pbz, pcx, pcy, pcz, pdx, pdy, pdz, pex, pey, pez) { + const aex = pax - pex; + const bex = pbx - pex; + const cex = pcx - pex; + const dex = pdx - pex; + const aey = pay - pey; + const bey = pby - pey; + const cey = pcy - pey; + const dey = pdy - pey; + const aez = paz - pez; + const bez = pbz - pez; + const cez = pcz - pez; + const dez = pdz - pez; + + const ab = aex * bey - bex * aey; + const bc = bex * cey - cex * bey; + const cd = cex * dey - dex * cey; + const da = dex * aey - aex * dey; + const ac = aex * cey - cex * aey; + const bd = bex * dey - dex * bey; + + const abc = aez * bc - bez * ac + cez * ab; + const bcd = bez * cd - cez * bd + dez * bc; + const cda = cez * da + dez * ac + aez * cd; + const dab = dez * ab + aez * bd + bez * da; + + const alift = aex * aex + aey * aey + aez * aez; + const blift = bex * bex + bey * bey + bez * bez; + const clift = cex * cex + cey * cey + cez * cez; + const dlift = dex * dex + dey * dey + dez * dez; + + return (clift * dab - dlift * abc) + (alift * bcd - blift * cda); +} + +exports.incircle = incircle; +exports.incirclefast = incirclefast; +exports.insphere = insphere; +exports.inspherefast = inspherefast; +exports.orient2d = orient2d; +exports.orient2dfast = orient2dfast; +exports.orient3d = orient3d; +exports.orient3dfast = orient3dfast; + +Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/robust-predicates/umd/predicates.min.js b/node_modules/robust-predicates/umd/predicates.min.js new file mode 100644 index 0000000000000000000000000000000000000000..ae993d2bfaf9c4939e95355dedd940286c13b8dc --- /dev/null +++ b/node_modules/robust-predicates/umd/predicates.min.js @@ -0,0 +1 @@ +!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t=t||self).predicates={})}(this,function(t){"use strict";const n=134217729,e=33306690738754706e-32;function r(t,n,e,r,s){let o,a,c,u,f=n[0],i=r[0],h=0,b=0;i>f==i>-f?(o=f,f=n[++h]):(o=i,i=r[++b]);let M=0;if(hf==i>-f?(c=o-((a=f+o)-f),f=n[++h]):(c=o-((a=i+o)-i),i=r[++b]),o=a,0!==c&&(s[M++]=c);hf==i>-f?(c=o-((a=o+f)-(u=a-o))+(f-u),f=n[++h]):(c=o-((a=o+i)-(u=a-o))+(i-u),i=r[++b]),o=a,0!==c&&(s[M++]=c);for(;h=bt||-ht>=bt)return ht;if(g=t-($+(K=t-$))+(K-x),B=o-(rt+(K=o-rt))+(K-j),G=u-(ct+(K=u-ct))+(K-m),k=f-(tt+(K=f-tt))+(K-x),C=i-(st+(K=i-st))+(K-j),H=h-(ut+(K=h-ut))+(K-m),q=b-(nt+(K=b-nt))+(K-x),D=M-(ot+(K=M-ot))+(K-j),I=l-(ft+(K=l-ft))+(K-m),z=d-(et+(K=d-et))+(K-x),E=p-(at+(K=p-at))+(K-j),J=y-(it+(K=y-it))+(K-m),0===g&&0===B&&0===G&&0===k&&0===C&&0===H&&0===q&&0===D&&0===I&&0===z&&0===E&&0===J)return ht;bt=At*_+e*Math.abs(ht);const Mt=$*C+st*g-(rt*k+tt*B),lt=tt*D+ot*k-(st*q+nt*C),dt=nt*E+at*q-(ot*z+et*D),pt=et*B+rt*z-(at*g+$*E),yt=$*D+ot*g-(rt*q+nt*B),xt=tt*E+at*k-(st*z+et*C);return(ht+=(tt*tt+st*st+ut*ut)*(ft*pt+it*yt+ct*dt+(I*F+J*O+G*A))+(et*et+at*at+it*it)*(ct*lt-ut*yt+ft*Mt+(G*w-H*O+I*v))-(($*$+rt*rt+ct*ct)*(ut*dt-ft*xt+it*lt+(H*A-I*P+J*w))+(nt*nt+ot*ot+ft*ft)*(it*Mt+ct*xt+ut*pt+(J*v+G*P+H*F)))+2*((tt*k+st*C+ut*H)*(ft*F+it*O+ct*A)+(et*z+at*E+it*J)*(ct*w-ut*O+ft*v)-(($*g+rt*B+ct*G)*(ut*A-ft*P+it*w)+(nt*q+ot*D+ft*I)*(it*v+ct*P+ut*F))))>=bt||-ht>=bt?ht:function(t,e,r,o,a,c,u,f,i,h,b,M,l,d,p){let y,x,j,m,_,v,w,A,F,O,P,g,k,q;y=(P=(m=t-(j=(x=n*t)-(x-t)))*(v=a-(_=(x=n*a)-(x-a)))-((O=t*a)-j*_-m*_-j*v))-(w=P-(k=(m=o-(j=(x=n*o)-(x-o)))*(v=e-(_=(x=n*e)-(x-e)))-((g=o*e)-j*_-m*_-j*v))),Ft[0]=P-(w+y)+(y-k),y=(F=O-((A=O+w)-(y=A-O))+(w-y))-(w=F-g),Ft[1]=F-(w+y)+(y-g),y=(q=A+w)-A,Ft[2]=A-(q-y)+(w-y),Ft[3]=q,y=(P=(m=o-(j=(x=n*o)-(x-o)))*(v=f-(_=(x=n*f)-(x-f)))-((O=o*f)-j*_-m*_-j*v))-(w=P-(k=(m=u-(j=(x=n*u)-(x-u)))*(v=a-(_=(x=n*a)-(x-a)))-((g=u*a)-j*_-m*_-j*v))),Ot[0]=P-(w+y)+(y-k),y=(F=O-((A=O+w)-(y=A-O))+(w-y))-(w=F-g),Ot[1]=F-(w+y)+(y-g),y=(q=A+w)-A,Ot[2]=A-(q-y)+(w-y),Ot[3]=q,y=(P=(m=u-(j=(x=n*u)-(x-u)))*(v=b-(_=(x=n*b)-(x-b)))-((O=u*b)-j*_-m*_-j*v))-(w=P-(k=(m=h-(j=(x=n*h)-(x-h)))*(v=f-(_=(x=n*f)-(x-f)))-((g=h*f)-j*_-m*_-j*v))),Pt[0]=P-(w+y)+(y-k),y=(F=O-((A=O+w)-(y=A-O))+(w-y))-(w=F-g),Pt[1]=F-(w+y)+(y-g),y=(q=A+w)-A,Pt[2]=A-(q-y)+(w-y),Pt[3]=q,y=(P=(m=h-(j=(x=n*h)-(x-h)))*(v=d-(_=(x=n*d)-(x-d)))-((O=h*d)-j*_-m*_-j*v))-(w=P-(k=(m=l-(j=(x=n*l)-(x-l)))*(v=b-(_=(x=n*b)-(x-b)))-((g=l*b)-j*_-m*_-j*v))),gt[0]=P-(w+y)+(y-k),y=(F=O-((A=O+w)-(y=A-O))+(w-y))-(w=F-g),gt[1]=F-(w+y)+(y-g),y=(q=A+w)-A,gt[2]=A-(q-y)+(w-y),gt[3]=q,y=(P=(m=l-(j=(x=n*l)-(x-l)))*(v=e-(_=(x=n*e)-(x-e)))-((O=l*e)-j*_-m*_-j*v))-(w=P-(k=(m=t-(j=(x=n*t)-(x-t)))*(v=d-(_=(x=n*d)-(x-d)))-((g=t*d)-j*_-m*_-j*v))),kt[0]=P-(w+y)+(y-k),y=(F=O-((A=O+w)-(y=A-O))+(w-y))-(w=F-g),kt[1]=F-(w+y)+(y-g),y=(q=A+w)-A,kt[2]=A-(q-y)+(w-y),kt[3]=q,y=(P=(m=t-(j=(x=n*t)-(x-t)))*(v=f-(_=(x=n*f)-(x-f)))-((O=t*f)-j*_-m*_-j*v))-(w=P-(k=(m=u-(j=(x=n*u)-(x-u)))*(v=e-(_=(x=n*e)-(x-e)))-((g=u*e)-j*_-m*_-j*v))),qt[0]=P-(w+y)+(y-k),y=(F=O-((A=O+w)-(y=A-O))+(w-y))-(w=F-g),qt[1]=F-(w+y)+(y-g),y=(q=A+w)-A,qt[2]=A-(q-y)+(w-y),qt[3]=q,y=(P=(m=o-(j=(x=n*o)-(x-o)))*(v=b-(_=(x=n*b)-(x-b)))-((O=o*b)-j*_-m*_-j*v))-(w=P-(k=(m=h-(j=(x=n*h)-(x-h)))*(v=a-(_=(x=n*a)-(x-a)))-((g=h*a)-j*_-m*_-j*v))),zt[0]=P-(w+y)+(y-k),y=(F=O-((A=O+w)-(y=A-O))+(w-y))-(w=F-g),zt[1]=F-(w+y)+(y-g),y=(q=A+w)-A,zt[2]=A-(q-y)+(w-y),zt[3]=q,y=(P=(m=u-(j=(x=n*u)-(x-u)))*(v=d-(_=(x=n*d)-(x-d)))-((O=u*d)-j*_-m*_-j*v))-(w=P-(k=(m=l-(j=(x=n*l)-(x-l)))*(v=f-(_=(x=n*f)-(x-f)))-((g=l*f)-j*_-m*_-j*v))),Bt[0]=P-(w+y)+(y-k),y=(F=O-((A=O+w)-(y=A-O))+(w-y))-(w=F-g),Bt[1]=F-(w+y)+(y-g),y=(q=A+w)-A,Bt[2]=A-(q-y)+(w-y),Bt[3]=q,y=(P=(m=h-(j=(x=n*h)-(x-h)))*(v=e-(_=(x=n*e)-(x-e)))-((O=h*e)-j*_-m*_-j*v))-(w=P-(k=(m=t-(j=(x=n*t)-(x-t)))*(v=b-(_=(x=n*b)-(x-b)))-((g=t*b)-j*_-m*_-j*v))),Ct[0]=P-(w+y)+(y-k),y=(F=O-((A=O+w)-(y=A-O))+(w-y))-(w=F-g),Ct[1]=F-(w+y)+(y-g),y=(q=A+w)-A,Ct[2]=A-(q-y)+(w-y),Ct[3]=q,y=(P=(m=l-(j=(x=n*l)-(x-l)))*(v=a-(_=(x=n*a)-(x-a)))-((O=l*a)-j*_-m*_-j*v))-(w=P-(k=(m=o-(j=(x=n*o)-(x-o)))*(v=d-(_=(x=n*d)-(x-d)))-((g=o*d)-j*_-m*_-j*v))),Dt[0]=P-(w+y)+(y-k),y=(F=O-((A=O+w)-(y=A-O))+(w-y))-(w=F-g),Dt[1]=F-(w+y)+(y-g),y=(q=A+w)-A,Dt[2]=A-(q-y)+(w-y),Dt[3]=q;const z=ln(Ft,Ot,qt,i,r,-c,Et),B=ln(Ot,Pt,zt,M,c,-i,Gt),C=ln(Pt,gt,Bt,p,i,-M,Ht),D=ln(gt,kt,Ct,r,M,-p,It),E=ln(kt,Ft,Dt,c,p,-r,Jt),G=ln(Ft,zt,Ct,M,r,c,Kt),H=ln(Ot,Bt,Dt,p,c,i,Lt),I=ln(Pt,Ct,qt,r,i,M,Nt),J=ln(gt,Dt,zt,c,M,p,Qt),K=ln(kt,qt,Bt,i,p,r,Rt),L=s(dn(C,Ht,H,Lt,J,Qt,B,Gt,t,e,r,St),St,dn(D,It,I,Nt,K,Rt,C,Ht,o,a,c,Tt),Tt,s(dn(E,Jt,J,Qt,G,Kt,D,It,u,f,i,Ut),Ut,dn(z,Et,K,Rt,H,Lt,E,Jt,h,b,M,Vt),Vt,dn(B,Gt,G,Kt,I,Nt,z,Et,l,d,p,Wt),Wt,Yt,Zt),Zt,Xt,$t);return $t[L-1]}(t,o,u,f,i,h,b,M,l,d,p,y,x,j,m)}t.incircle=function(t,a,u,f,i,h,b,M){const l=t-b,d=u-b,p=i-b,y=a-M,x=f-M,j=h-M,m=d*j,_=p*x,v=l*l+y*y,w=p*y,A=l*j,F=d*d+x*x,O=l*x,P=d*y,g=p*p+j*j,k=v*(m-_)+F*(w-A)+g*(O-P),q=(Math.abs(m)+Math.abs(_))*v+(Math.abs(w)+Math.abs(A))*F+(Math.abs(O)+Math.abs(P))*g,z=N*q;return k>z||-k>z?k:function(t,a,u,f,i,h,b,M,l){let d,p,y,x,j,m,_,v,w,A,F,O,P,g,k,q,z,B,C,D,E,G,H,I,J,K,L,N,mt,vt,wt,At,Ft,Ot,Pt;const gt=t-b,kt=u-b,qt=i-b,zt=a-M,Bt=f-M,Ct=h-M;G=(At=(J=kt-(I=(H=n*kt)-(H-kt)))*(L=Ct-(K=(H=n*Ct)-(H-Ct)))-((wt=kt*Ct)-I*K-J*K-I*L))-(N=At-(Ot=(J=qt-(I=(H=n*qt)-(H-qt)))*(L=Bt-(K=(H=n*Bt)-(H-Bt)))-((Ft=qt*Bt)-I*K-J*K-I*L))),S[0]=At-(N+G)+(G-Ot),G=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))-(N=vt-Ft),S[1]=vt-(N+G)+(G-Ft),G=(Pt=mt+N)-mt,S[2]=mt-(Pt-G)+(N-G),S[3]=Pt,G=(At=(J=qt-(I=(H=n*qt)-(H-qt)))*(L=zt-(K=(H=n*zt)-(H-zt)))-((wt=qt*zt)-I*K-J*K-I*L))-(N=At-(Ot=(J=gt-(I=(H=n*gt)-(H-gt)))*(L=Ct-(K=(H=n*Ct)-(H-Ct)))-((Ft=gt*Ct)-I*K-J*K-I*L))),T[0]=At-(N+G)+(G-Ot),G=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))-(N=vt-Ft),T[1]=vt-(N+G)+(G-Ft),G=(Pt=mt+N)-mt,T[2]=mt-(Pt-G)+(N-G),T[3]=Pt,G=(At=(J=gt-(I=(H=n*gt)-(H-gt)))*(L=Bt-(K=(H=n*Bt)-(H-Bt)))-((wt=gt*Bt)-I*K-J*K-I*L))-(N=At-(Ot=(J=kt-(I=(H=n*kt)-(H-kt)))*(L=zt-(K=(H=n*zt)-(H-zt)))-((Ft=kt*zt)-I*K-J*K-I*L))),U[0]=At-(N+G)+(G-Ot),G=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))-(N=vt-Ft),U[1]=vt-(N+G)+(G-Ft),G=(Pt=mt+N)-mt,U[2]=mt-(Pt-G)+(N-G),U[3]=Pt;let Dt=c(d=r(r(r(o(o(4,S,gt,ht),ht,gt,bt),bt,o(o(4,S,zt,ht),ht,zt,Mt),Mt,dt),dt,r(o(o(4,T,kt,ht),ht,kt,bt),bt,o(o(4,T,Bt,ht),ht,Bt,Mt),Mt,pt),pt,xt),xt,r(o(o(4,U,qt,ht),ht,qt,bt),bt,o(o(4,U,Ct,ht),ht,Ct,Mt),Mt,dt),dt,jt),jt),Et=Q*l;if(Dt>=Et||-Dt>=Et)return Dt;if(p=t-(gt+(G=t-gt))+(G-b),j=a-(zt+(G=a-zt))+(G-M),y=u-(kt+(G=u-kt))+(G-b),m=f-(Bt+(G=f-Bt))+(G-M),x=i-(qt+(G=i-qt))+(G-b),_=h-(Ct+(G=h-Ct))+(G-M),0===p&&0===y&&0===x&&0===j&&0===m&&0===_)return Dt;if(Et=R*l+e*Math.abs(Dt),(Dt+=(gt*gt+zt*zt)*(kt*_+Ct*y-(Bt*x+qt*m))+2*(gt*p+zt*j)*(kt*Ct-Bt*qt)+((kt*kt+Bt*Bt)*(qt*j+zt*x-(Ct*p+gt*_))+2*(kt*y+Bt*m)*(qt*zt-Ct*gt))+((qt*qt+Ct*Ct)*(gt*m+Bt*p-(zt*y+kt*j))+2*(qt*x+Ct*_)*(gt*Bt-zt*kt)))>=Et||-Dt>=Et)return Dt;if(0===y&&0===m&&0===x&&0===_||(G=(N=(At=(J=gt-(I=(H=n*gt)-(H-gt)))*J-((wt=gt*gt)-I*I-(I+I)*J))+(Ot=(J=zt-(I=(H=n*zt)-(H-zt)))*J-((Ft=zt*zt)-I*I-(I+I)*J)))-At,V[0]=At-(N-G)+(Ot-G),G=(N=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))+Ft)-vt,V[1]=vt-(N-G)+(Ft-G),G=(Pt=mt+N)-mt,V[2]=mt-(Pt-G)+(N-G),V[3]=Pt),0===x&&0===_&&0===p&&0===j||(G=(N=(At=(J=kt-(I=(H=n*kt)-(H-kt)))*J-((wt=kt*kt)-I*I-(I+I)*J))+(Ot=(J=Bt-(I=(H=n*Bt)-(H-Bt)))*J-((Ft=Bt*Bt)-I*I-(I+I)*J)))-At,W[0]=At-(N-G)+(Ot-G),G=(N=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))+Ft)-vt,W[1]=vt-(N-G)+(Ft-G),G=(Pt=mt+N)-mt,W[2]=mt-(Pt-G)+(N-G),W[3]=Pt),0===p&&0===j&&0===y&&0===m||(G=(N=(At=(J=qt-(I=(H=n*qt)-(H-qt)))*J-((wt=qt*qt)-I*I-(I+I)*J))+(Ot=(J=Ct-(I=(H=n*Ct)-(H-Ct)))*J-((Ft=Ct*Ct)-I*I-(I+I)*J)))-At,X[0]=At-(N-G)+(Ot-G),G=(N=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))+Ft)-vt,X[1]=vt-(N-G)+(Ft-G),G=(Pt=mt+N)-mt,X[2]=mt-(Pt-G)+(N-G),X[3]=Pt),0!==p&&(v=o(4,S,p,$),d=_t(d,s(o(v,$,2*gt,bt),bt,o(o(4,X,p,ht),ht,Bt,Mt),Mt,o(o(4,W,p,ht),ht,-Ct,lt),lt,dt,yt),yt)),0!==j&&(w=o(4,S,j,tt),d=_t(d,s(o(w,tt,2*zt,bt),bt,o(o(4,W,j,ht),ht,qt,Mt),Mt,o(o(4,X,j,ht),ht,-kt,lt),lt,dt,yt),yt)),0!==y&&(A=o(4,T,y,nt),d=_t(d,s(o(A,nt,2*kt,bt),bt,o(o(4,V,y,ht),ht,Ct,Mt),Mt,o(o(4,X,y,ht),ht,-zt,lt),lt,dt,yt),yt)),0!==m&&(F=o(4,T,m,et),d=_t(d,s(o(F,et,2*Bt,bt),bt,o(o(4,X,m,ht),ht,gt,Mt),Mt,o(o(4,V,m,ht),ht,-qt,lt),lt,dt,yt),yt)),0!==x&&(O=o(4,U,x,rt),d=_t(d,s(o(O,rt,2*qt,bt),bt,o(o(4,W,x,ht),ht,zt,Mt),Mt,o(o(4,V,x,ht),ht,-Bt,lt),lt,dt,yt),yt)),0!==_&&(P=o(4,U,_,st),d=_t(d,s(o(P,st,2*Ct,bt),bt,o(o(4,V,_,ht),ht,kt,Mt),Mt,o(o(4,W,_,ht),ht,-gt,lt),lt,dt,yt),yt)),0!==p||0!==j){if(0!==y||0!==m||0!==x||0!==_?(G=(N=(At=(J=y-(I=(H=n*y)-(H-y)))*(L=Ct-(K=(H=n*Ct)-(H-Ct)))-((wt=y*Ct)-I*K-J*K-I*L))+(Ot=(J=kt-(I=(H=n*kt)-(H-kt)))*(L=_-(K=(H=n*_)-(H-_)))-((Ft=kt*_)-I*K-J*K-I*L)))-At,Y[0]=At-(N-G)+(Ot-G),G=(N=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))+Ft)-vt,Y[1]=vt-(N-G)+(Ft-G),G=(Pt=mt+N)-mt,Y[2]=mt-(Pt-G)+(N-G),Y[3]=Pt,G=(N=(At=(J=x-(I=(H=n*x)-(H-x)))*(L=-Bt-(K=(H=n*-Bt)-(H- -Bt)))-((wt=x*-Bt)-I*K-J*K-I*L))+(Ot=(J=qt-(I=(H=n*qt)-(H-qt)))*(L=-m-(K=(H=n*-m)-(H- -m)))-((Ft=qt*-m)-I*K-J*K-I*L)))-At,Z[0]=At-(N-G)+(Ot-G),G=(N=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))+Ft)-vt,Z[1]=vt-(N-G)+(Ft-G),G=(Pt=mt+N)-mt,Z[2]=mt-(Pt-G)+(N-G),Z[3]=Pt,k=r(4,Y,4,Z,at),G=(At=(J=y-(I=(H=n*y)-(H-y)))*(L=_-(K=(H=n*_)-(H-_)))-((wt=y*_)-I*K-J*K-I*L))-(N=At-(Ot=(J=x-(I=(H=n*x)-(H-x)))*(L=m-(K=(H=n*m)-(H-m)))-((Ft=x*m)-I*K-J*K-I*L))),ft[0]=At-(N+G)+(G-Ot),G=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))-(N=vt-Ft),ft[1]=vt-(N+G)+(G-Ft),G=(Pt=mt+N)-mt,ft[2]=mt-(Pt-G)+(N-G),ft[3]=Pt,B=4):(at[0]=0,k=1,ft[0]=0,B=1),0!==p){const t=o(k,at,p,lt);d=_t(d,r(o(v,$,p,bt),bt,o(t,lt,2*gt,dt),dt,yt),yt);const n=o(B,ft,p,ht);d=_t(d,s(o(n,ht,2*gt,bt),bt,o(n,ht,p,Mt),Mt,o(t,lt,p,dt),dt,pt,xt),xt),0!==m&&(d=_t(d,o(o(4,X,p,ht),ht,m,bt),bt)),0!==_&&(d=_t(d,o(o(4,W,-p,ht),ht,_,bt),bt))}if(0!==j){const t=o(k,at,j,lt);d=_t(d,r(o(w,tt,j,bt),bt,o(t,lt,2*zt,dt),dt,yt),yt);const n=o(B,ft,j,ht);d=_t(d,s(o(n,ht,2*zt,bt),bt,o(n,ht,j,Mt),Mt,o(t,lt,j,dt),dt,pt,xt),xt)}}if(0!==y||0!==m){if(0!==x||0!==_||0!==p||0!==j?(G=(N=(At=(J=x-(I=(H=n*x)-(H-x)))*(L=zt-(K=(H=n*zt)-(H-zt)))-((wt=x*zt)-I*K-J*K-I*L))+(Ot=(J=qt-(I=(H=n*qt)-(H-qt)))*(L=j-(K=(H=n*j)-(H-j)))-((Ft=qt*j)-I*K-J*K-I*L)))-At,Y[0]=At-(N-G)+(Ot-G),G=(N=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))+Ft)-vt,Y[1]=vt-(N-G)+(Ft-G),G=(Pt=mt+N)-mt,Y[2]=mt-(Pt-G)+(N-G),Y[3]=Pt,G=(N=(At=(J=p-(I=(H=n*p)-(H-p)))*(L=(D=-Ct)-(K=(H=n*D)-(H-D)))-((wt=p*D)-I*K-J*K-I*L))+(Ot=(J=gt-(I=(H=n*gt)-(H-gt)))*(L=(E=-_)-(K=(H=n*E)-(H-E)))-((Ft=gt*E)-I*K-J*K-I*L)))-At,Z[0]=At-(N-G)+(Ot-G),G=(N=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))+Ft)-vt,Z[1]=vt-(N-G)+(Ft-G),G=(Pt=mt+N)-mt,Z[2]=mt-(Pt-G)+(N-G),Z[3]=Pt,q=r(4,Y,4,Z,ct),G=(At=(J=x-(I=(H=n*x)-(H-x)))*(L=j-(K=(H=n*j)-(H-j)))-((wt=x*j)-I*K-J*K-I*L))-(N=At-(Ot=(J=p-(I=(H=n*p)-(H-p)))*(L=_-(K=(H=n*_)-(H-_)))-((Ft=p*_)-I*K-J*K-I*L))),it[0]=At-(N+G)+(G-Ot),G=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))-(N=vt-Ft),it[1]=vt-(N+G)+(G-Ft),G=(Pt=mt+N)-mt,it[2]=mt-(Pt-G)+(N-G),it[3]=Pt,C=4):(ct[0]=0,q=1,it[0]=0,C=1),0!==y){const t=o(q,ct,y,lt);d=_t(d,r(o(A,nt,y,bt),bt,o(t,lt,2*kt,dt),dt,yt),yt);const n=o(C,it,y,ht);d=_t(d,s(o(n,ht,2*kt,bt),bt,o(n,ht,y,Mt),Mt,o(t,lt,y,dt),dt,pt,xt),xt),0!==_&&(d=_t(d,o(o(4,V,y,ht),ht,_,bt),bt)),0!==j&&(d=_t(d,o(o(4,X,-y,ht),ht,j,bt),bt))}if(0!==m){const t=o(q,ct,m,lt);d=_t(d,r(o(F,et,m,bt),bt,o(t,lt,2*Bt,dt),dt,yt),yt);const n=o(C,it,m,ht);d=_t(d,s(o(n,ht,2*Bt,bt),bt,o(n,ht,m,Mt),Mt,o(t,lt,m,dt),dt,pt,xt),xt)}}if(0!==x||0!==_){if(0!==p||0!==j||0!==y||0!==m?(G=(N=(At=(J=p-(I=(H=n*p)-(H-p)))*(L=Bt-(K=(H=n*Bt)-(H-Bt)))-((wt=p*Bt)-I*K-J*K-I*L))+(Ot=(J=gt-(I=(H=n*gt)-(H-gt)))*(L=m-(K=(H=n*m)-(H-m)))-((Ft=gt*m)-I*K-J*K-I*L)))-At,Y[0]=At-(N-G)+(Ot-G),G=(N=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))+Ft)-vt,Y[1]=vt-(N-G)+(Ft-G),G=(Pt=mt+N)-mt,Y[2]=mt-(Pt-G)+(N-G),Y[3]=Pt,G=(N=(At=(J=y-(I=(H=n*y)-(H-y)))*(L=(D=-zt)-(K=(H=n*D)-(H-D)))-((wt=y*D)-I*K-J*K-I*L))+(Ot=(J=kt-(I=(H=n*kt)-(H-kt)))*(L=(E=-j)-(K=(H=n*E)-(H-E)))-((Ft=kt*E)-I*K-J*K-I*L)))-At,Z[0]=At-(N-G)+(Ot-G),G=(N=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))+Ft)-vt,Z[1]=vt-(N-G)+(Ft-G),G=(Pt=mt+N)-mt,Z[2]=mt-(Pt-G)+(N-G),Z[3]=Pt,g=r(4,Y,4,Z,ot),G=(At=(J=p-(I=(H=n*p)-(H-p)))*(L=m-(K=(H=n*m)-(H-m)))-((wt=p*m)-I*K-J*K-I*L))-(N=At-(Ot=(J=y-(I=(H=n*y)-(H-y)))*(L=j-(K=(H=n*j)-(H-j)))-((Ft=y*j)-I*K-J*K-I*L))),ut[0]=At-(N+G)+(G-Ot),G=(vt=wt-((mt=wt+N)-(G=mt-wt))+(N-G))-(N=vt-Ft),ut[1]=vt-(N+G)+(G-Ft),G=(Pt=mt+N)-mt,ut[2]=mt-(Pt-G)+(N-G),ut[3]=Pt,z=4):(ot[0]=0,g=1,ut[0]=0,z=1),0!==x){const t=o(g,ot,x,lt);d=_t(d,r(o(O,rt,x,bt),bt,o(t,lt,2*qt,dt),dt,yt),yt);const n=o(z,ut,x,ht);d=_t(d,s(o(n,ht,2*qt,bt),bt,o(n,ht,x,Mt),Mt,o(t,lt,x,dt),dt,pt,xt),xt),0!==j&&(d=_t(d,o(o(4,W,x,ht),ht,j,bt),bt)),0!==m&&(d=_t(d,o(o(4,V,-x,ht),ht,m,bt),bt))}if(0!==_){const t=o(g,ot,_,lt);d=_t(d,r(o(P,st,_,bt),bt,o(t,lt,2*Ct,dt),dt,yt),yt);const n=o(z,ut,_,ht);d=_t(d,s(o(n,ht,2*Ct,bt),bt,o(n,ht,_,Mt),Mt,o(t,lt,_,dt),dt,pt,xt),xt)}}return jt[d-1]}(t,a,u,f,i,h,b,M,q)},t.incirclefast=function(t,n,e,r,s,o,a,c){const u=t-a,f=n-c,i=e-a,h=r-c,b=s-a,M=o-c;return(u*u+f*f)*(i*M-b*h)+(i*i+h*h)*(b*f-u*M)+(b*b+M*M)*(u*h-i*f)},t.insphere=function(t,n,e,r,s,o,a,c,u,f,i,h,b,M,l){const d=t-b,p=r-b,y=a-b,x=f-b,j=n-M,m=s-M,_=c-M,v=i-M,w=e-l,A=o-l,F=u-l,O=h-l,P=d*m,g=p*j,k=P-g,q=p*_,z=y*m,B=q-z,C=y*v,D=x*_,E=C-D,G=x*j,H=d*v,I=G-H,J=d*_,K=y*j,L=J-K,N=p*v,Q=x*m,R=N-Q,S=d*d+j*j+w*w,T=p*p+m*m+A*A,U=y*y+_*_+F*F,V=x*x+v*v+O*O,W=U*(O*k+w*R+A*I)-V*(w*B-A*L+F*k)+(S*(A*E-F*R+O*B)-T*(F*I+O*L+w*E)),X=Math.abs(w),Y=Math.abs(A),Z=Math.abs(F),$=Math.abs(O),tt=Math.abs(P),nt=Math.abs(g),et=Math.abs(q),rt=Math.abs(z),st=Math.abs(C),ot=Math.abs(D),at=Math.abs(G),ct=Math.abs(H),ut=Math.abs(J),ft=Math.abs(K),it=Math.abs(N),ht=Math.abs(Q),bt=((st+ot)*Y+(ht+it)*Z+(et+rt)*$)*S+((at+ct)*Z+(ut+ft)*$+(st+ot)*X)*T+((tt+nt)*$+(it+ht)*X+(at+ct)*Y)*U+((et+rt)*X+(ft+ut)*Y+(tt+nt)*Z)*V,Mt=vt*bt;return W>Mt||-W>Mt?W:-_n(t,n,e,r,s,o,a,c,u,f,i,h,b,M,l,bt)},t.inspherefast=function(t,n,e,r,s,o,a,c,u,f,i,h,b,M,l){const d=t-b,p=r-b,y=a-b,x=f-b,j=n-M,m=s-M,_=c-M,v=i-M,w=e-l,A=o-l,F=u-l,O=h-l,P=d*m-p*j,g=p*_-y*m,k=y*v-x*_,q=x*j-d*v,z=d*_-y*j,B=p*v-x*m;return(y*y+_*_+F*F)*(O*P+w*B+A*q)-(x*x+v*v+O*O)*(w*g-A*z+F*P)+((d*d+j*j+w*w)*(A*k-F*B+O*g)-(p*p+m*m+A*A)*(F*q+O*z+w*k))},t.orient2d=function(t,s,o,a,u,y){const x=(s-y)*(o-u),j=(t-u)*(a-y),m=x-j;if(0===x||0===j||x>0!=j>0)return m;const _=Math.abs(x+j);return Math.abs(m)>=f*_?m:-function(t,s,o,a,u,f,y){let x,j,m,_,v,w,A,F,O,P,g,k,q,z,B,C,D,E;const G=t-u,H=o-u,I=s-f,J=a-f;v=(B=(F=G-(A=(w=n*G)-(w-G)))*(P=J-(O=(w=n*J)-(w-J)))-((z=G*J)-A*O-F*O-A*P))-(g=B-(D=(F=I-(A=(w=n*I)-(w-I)))*(P=H-(O=(w=n*H)-(w-H)))-((C=I*H)-A*O-F*O-A*P))),b[0]=B-(g+v)+(v-D),v=(q=z-((k=z+g)-(v=k-z))+(g-v))-(g=q-C),b[1]=q-(g+v)+(v-C),v=(E=k+g)-k,b[2]=k-(E-v)+(g-v),b[3]=E;let K=c(4,b),L=i*y;if(K>=L||-K>=L)return K;if(x=t-(G+(v=t-G))+(v-u),m=o-(H+(v=o-H))+(v-u),j=s-(I+(v=s-I))+(v-f),_=a-(J+(v=a-J))+(v-f),0===x&&0===j&&0===m&&0===_)return K;if(L=h*y+e*Math.abs(K),(K+=G*_+J*x-(I*m+H*j))>=L||-K>=L)return K;v=(B=(F=x-(A=(w=n*x)-(w-x)))*(P=J-(O=(w=n*J)-(w-J)))-((z=x*J)-A*O-F*O-A*P))-(g=B-(D=(F=j-(A=(w=n*j)-(w-j)))*(P=H-(O=(w=n*H)-(w-H)))-((C=j*H)-A*O-F*O-A*P))),p[0]=B-(g+v)+(v-D),v=(q=z-((k=z+g)-(v=k-z))+(g-v))-(g=q-C),p[1]=q-(g+v)+(v-C),v=(E=k+g)-k,p[2]=k-(E-v)+(g-v),p[3]=E;const N=r(4,b,4,p,M);v=(B=(F=G-(A=(w=n*G)-(w-G)))*(P=_-(O=(w=n*_)-(w-_)))-((z=G*_)-A*O-F*O-A*P))-(g=B-(D=(F=I-(A=(w=n*I)-(w-I)))*(P=m-(O=(w=n*m)-(w-m)))-((C=I*m)-A*O-F*O-A*P))),p[0]=B-(g+v)+(v-D),v=(q=z-((k=z+g)-(v=k-z))+(g-v))-(g=q-C),p[1]=q-(g+v)+(v-C),v=(E=k+g)-k,p[2]=k-(E-v)+(g-v),p[3]=E;const Q=r(N,M,4,p,l);v=(B=(F=x-(A=(w=n*x)-(w-x)))*(P=_-(O=(w=n*_)-(w-_)))-((z=x*_)-A*O-F*O-A*P))-(g=B-(D=(F=j-(A=(w=n*j)-(w-j)))*(P=m-(O=(w=n*m)-(w-m)))-((C=j*m)-A*O-F*O-A*P))),p[0]=B-(g+v)+(v-D),v=(q=z-((k=z+g)-(v=k-z))+(g-v))-(g=q-C),p[1]=q-(g+v)+(v-C),v=(E=k+g)-k,p[2]=k-(E-v)+(g-v),p[3]=E;const R=r(Q,l,4,p,d);return d[R-1]}(t,s,o,a,u,y,_)},t.orient2dfast=function(t,n,e,r,s,o){return(n-o)*(e-s)-(t-s)*(r-o)},t.orient3d=function(t,s,a,u,f,i,h,b,M,l,d,p){const B=t-l,I=u-l,N=h-l,Q=s-d,R=f-d,S=b-d,T=a-p,U=i-p,V=M-p,W=I*S,X=N*R,Y=N*Q,Z=B*S,$=B*R,tt=I*Q,nt=T*(W-X)+U*(Y-Z)+V*($-tt),et=(Math.abs(W)+Math.abs(X))*Math.abs(T)+(Math.abs(Y)+Math.abs(Z))*Math.abs(U)+(Math.abs($)+Math.abs(tt))*Math.abs(V),rt=y*et;return nt>rt||-nt>rt?nt:function(t,s,a,u,f,i,h,b,M,l,d,p,y){let B,I,N,Q,R,S,T,U,V,W,X,Y,Z,$,tt,nt,et,rt,st,ot,at,ct,ut,ft;const it=t-l,ht=u-l,bt=h-l,Mt=s-d,lt=f-d,dt=b-d,pt=a-p,yt=i-p,xt=M-p;X=(at=($=ht-(Z=(Y=n*ht)-(Y-ht)))*(nt=dt-(tt=(Y=n*dt)-(Y-dt)))-((ot=ht*dt)-Z*tt-$*tt-Z*nt))-(et=at-(ut=($=bt-(Z=(Y=n*bt)-(Y-bt)))*(nt=lt-(tt=(Y=n*lt)-(Y-lt)))-((ct=bt*lt)-Z*tt-$*tt-Z*nt))),m[0]=at-(et+X)+(X-ut),X=(st=ot-((rt=ot+et)-(X=rt-ot))+(et-X))-(et=st-ct),m[1]=st-(et+X)+(X-ct),X=(ft=rt+et)-rt,m[2]=rt-(ft-X)+(et-X),m[3]=ft,X=(at=($=bt-(Z=(Y=n*bt)-(Y-bt)))*(nt=Mt-(tt=(Y=n*Mt)-(Y-Mt)))-((ot=bt*Mt)-Z*tt-$*tt-Z*nt))-(et=at-(ut=($=it-(Z=(Y=n*it)-(Y-it)))*(nt=dt-(tt=(Y=n*dt)-(Y-dt)))-((ct=it*dt)-Z*tt-$*tt-Z*nt))),_[0]=at-(et+X)+(X-ut),X=(st=ot-((rt=ot+et)-(X=rt-ot))+(et-X))-(et=st-ct),_[1]=st-(et+X)+(X-ct),X=(ft=rt+et)-rt,_[2]=rt-(ft-X)+(et-X),_[3]=ft,X=(at=($=it-(Z=(Y=n*it)-(Y-it)))*(nt=lt-(tt=(Y=n*lt)-(Y-lt)))-((ot=it*lt)-Z*tt-$*tt-Z*nt))-(et=at-(ut=($=ht-(Z=(Y=n*ht)-(Y-ht)))*(nt=Mt-(tt=(Y=n*Mt)-(Y-Mt)))-((ct=ht*Mt)-Z*tt-$*tt-Z*nt))),v[0]=at-(et+X)+(X-ut),X=(st=ot-((rt=ot+et)-(X=rt-ot))+(et-X))-(et=st-ct),v[1]=st-(et+X)+(X-ct),X=(ft=rt+et)-rt,v[2]=rt-(ft-X)+(et-X),v[3]=ft;let jt=c(B=r(r(o(4,m,pt,C),C,o(4,_,yt,D),D,E),E,o(4,v,xt,C),C,H),H),mt=x*y;if(jt>=mt||-jt>=mt)return jt;if(I=t-(it+(X=t-it))+(X-l),N=u-(ht+(X=u-ht))+(X-l),Q=h-(bt+(X=h-bt))+(X-l),R=s-(Mt+(X=s-Mt))+(X-d),S=f-(lt+(X=f-lt))+(X-d),T=b-(dt+(X=b-dt))+(X-d),U=a-(pt+(X=a-pt))+(X-p),V=i-(yt+(X=i-yt))+(X-p),W=M-(xt+(X=M-xt))+(X-p),0===I&&0===N&&0===Q&&0===R&&0===S&&0===T&&0===U&&0===V&&0===W)return jt;if(mt=j*y+e*Math.abs(jt),(jt+=pt*(ht*T+dt*N-(lt*Q+bt*S))+U*(ht*dt-lt*bt)+yt*(bt*R+Mt*Q-(dt*I+it*T))+V*(bt*Mt-dt*it)+xt*(it*S+lt*I-(Mt*N+ht*R))+W*(it*lt-Mt*ht))>=mt||-jt>=mt)return jt;const _t=K(I,R,ht,lt,bt,dt,w,A),vt=K(N,S,bt,dt,it,Mt,F,O),wt=K(Q,T,it,Mt,ht,lt,P,g),At=r(vt,F,wt,g,k);B=J(B,o(At,k,pt,E),E);const Ft=r(wt,P,_t,A,q);B=J(B,o(Ft,q,yt,E),E);const Ot=r(_t,w,vt,O,z);return B=J(B,o(Ot,z,xt,E),E),0!==U&&(B=J(B,o(4,m,U,G),G),B=J(B,o(At,k,U,E),E)),0!==V&&(B=J(B,o(4,_,V,G),G),B=J(B,o(Ft,q,V,E),E)),0!==W&&(B=J(B,o(4,v,W,G),G),B=J(B,o(Ot,z,W,E),E)),0!==I&&(0!==S&&(B=L(B,I,S,xt,W)),0!==T&&(B=L(B,-I,T,yt,V))),0!==N&&(0!==T&&(B=L(B,N,T,pt,U)),0!==R&&(B=L(B,-N,R,xt,W))),0!==Q&&(0!==R&&(B=L(B,Q,R,yt,V)),0!==S&&(B=L(B,-Q,S,pt,U))),H[B-1]}(t,s,a,u,f,i,h,b,M,l,d,p,et)},t.orient3dfast=function(t,n,e,r,s,o,a,c,u,f,i,h){const b=n-i,M=s-i,l=c-i,d=e-h,p=o-h,y=u-h;return(t-f)*(M*y-p*l)+(r-f)*(l*d-y*b)+(a-f)*(b*p-d*M)},Object.defineProperty(t,"__esModule",{value:!0})}); diff --git a/node_modules/rolldown-plugin-dts/LICENSE b/node_modules/rolldown-plugin-dts/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8701f9fe69eb9e01d8a4ade1c51bc5b8a4a7e315 --- /dev/null +++ b/node_modules/rolldown-plugin-dts/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright © 2025-PRESENT Kevin Deng (https://github.com/sxzz) + +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. diff --git a/node_modules/rolldown-plugin-dts/README.md b/node_modules/rolldown-plugin-dts/README.md new file mode 100644 index 0000000000000000000000000000000000000000..89c98f694d88b830c971735c5a42fdba7061c942 --- /dev/null +++ b/node_modules/rolldown-plugin-dts/README.md @@ -0,0 +1,288 @@ +# rolldown-plugin-dts + +[![npm version][npm-version-src]][npm-version-href] +[![npm downloads][npm-downloads-src]][npm-downloads-href] +[![Unit Test][unit-test-src]][unit-test-href] + +A Rolldown plugin to generate and bundle dts files. + +## Install + +Requires Rolldown 1.0.0 or later. + +```bash +npm i -D rolldown-plugin-dts + +npm i -D typescript # install TypeScript if isolatedDeclarations is not enabled +npm i -D @typescript/native-preview # install TypeScript Go if tsgo is enabled +``` + +## Usage + +Add the plugin to your `rolldown.config.js`: + +```js +// rolldown.config.js +import { dts } from 'rolldown-plugin-dts' + +export default { + input: './src/index.ts', + plugins: [dts()], + output: [{ dir: 'dist', format: 'es' }], +} +``` + +You can find an example in [here](./rolldown.config.ts). + +### Vite + +When using this plugin with Vite, exclude declaration files from Oxc +transformation to avoid processing generated outputs. Since `oxc.exclude` +overrides the default exclude list, include JavaScript files as well: + +```ts +// vite.config.ts + +export default defineConfig({ + oxc: { + exclude: [/\.js$/, /\.d\.[cm]?ts$/], + }, +}) +``` + +## Options + +Configuration options for the plugin. + +### General Options + +#### `entry` + +Glob pattern(s) to filter which files get `.d.ts` generation. + +When specified, only files matching these patterns will emit `.d.ts` chunks — even if they are not Rolldown entry points. Supports negation patterns for exclusion. Patterns are matched against file paths relative to `cwd`. + +```ts +dts({ + entry: ['src/**/*.ts', '!src/icons/**'], +}) +``` + +#### `cwd` + +The directory in which the plugin will search for the `tsconfig.json` file. + +#### `dtsInput` + +Set to `true` if your entry files are `.d.ts` files instead of `.ts` files. + +When enabled, the plugin will skip generating a `.d.ts` file for the entry point. + +#### `emitDtsOnly` + +If `true`, the plugin will emit only `.d.ts` files and remove all other output chunks. + +This is especially useful when generating `.d.ts` files for the CommonJS format as part of a separate build step. + +#### `tsconfig` + +The path to the `tsconfig.json` file. + +- If set to `false`, the plugin will ignore any `tsconfig.json` file. +- You can still specify `compilerOptions` directly in the options. + +**Default:** `'tsconfig.json'` + +#### `tsconfigRaw` + +Pass a raw `tsconfig.json` object directly to the plugin. + +See: [TypeScript tsconfig documentation](https://www.typescriptlang.org/tsconfig) + +#### `compilerOptions` + +Override the `compilerOptions` specified in `tsconfig.json`. + +See: [TypeScript compilerOptions documentation](https://www.typescriptlang.org/tsconfig/#compilerOptions) + +#### `sourcemap` + +If `true`, the plugin will generate declaration maps (`.d.ts.map`) for `.d.ts` files. + +#### `resolver` + +Specifies a resolver to resolve type definitions, especially for `node_modules`. + +- `'oxc'`: Uses Oxc's module resolution, which is faster and more efficient. +- `'tsc'`: Uses TypeScript's native module resolution, which may be more compatible with complex setups, but slower. + +Defaults to `'oxc'`. + +#### `cjsDefault` + +Determines how the default export is emitted. + +If set to `true`, and you are only exporting a single item using `export default ...`, +the output will use `export = ...` instead of the standard ES module syntax. +This is useful for compatibility with CommonJS. +This option only controls the output format and does not enable support for +CommonJS-style `.d.ts` input. + +#### `sideEffects` + +Indicates whether the generated `.d.ts` files have side effects. + +- If set to `true`, Rolldown will treat the `.d.ts` files as having side effects during tree-shaking. +- If set to `false`, Rolldown may consider the `.d.ts` files as side-effect-free, potentially removing them if they are not imported. + +**Default:** false + +### `tsc` Options + +> [!NOTE] +> These options are only applicable when `oxc` and `tsgo` are not enabled. + +#### `build` + +Build mode for the TypeScript compiler: + +- If `true`, the plugin will use [`tsc -b`](https://www.typescriptlang.org/docs/handbook/project-references.html#build-mode-for-typescript) to build the project and all referenced projects before emitting `.d.ts` files. +- If `false`, the plugin will use [`tsc`](https://www.typescriptlang.org/docs/handbook/compiler-options.html) to emit `.d.ts` files without building referenced projects. + +**Default:** `false` + +#### `incremental` + +Controls how project references and incremental builds are handled: + +- If `incremental` is `true`, all built files (including [`.tsbuildinfo`](https://www.typescriptlang.org/tsconfig/#tsBuildInfoFile)) will be written to disk, similar to running `tsc -b` in your project. +- If `incremental` is `false`, built files are kept in memory, minimizing disk usage. + +Enabling this option can speed up builds by caching previous results, which is helpful for large projects with multiple references. + +**Default:** `true` if your `tsconfig` has [`incremental`](https://www.typescriptlang.org/tsconfig/#incremental) or [`tsBuildInfoFile`](https://www.typescriptlang.org/tsconfig/#tsBuildInfoFile) enabled. + +#### `vue` + +If `true`, the plugin will generate `.d.ts` files using `vue-tsc`. + +#### `parallel` + +If `true`, the plugin will launch a separate process for `tsc` or `vue-tsc`, enabling parallel processing of multiple projects. + +#### `eager` + +If `true`, the plugin will prepare all files listed in `tsconfig.json` for `tsc` or `vue-tsc`. + +This is especially useful when you have a single `tsconfig.json` for multiple projects in a monorepo. + +#### `newContext` + +If `true`, the plugin will create a new isolated context for each build, +ensuring that previously generated `.d.ts` code and caches are not reused. + +By default, the plugin may reuse internal caches or incremental build artifacts +to speed up repeated builds. Enabling this option forces a clean context, +guaranteeing that all type definitions are generated from scratch. + +`invalidateContextFile` API can be used to clear invalidated files from the context. + +```ts +import { globalContext, invalidateContextFile } from 'rolldown-plugin-dts/tsc' +invalidateContextFile(globalContext, 'src/foo.ts') +``` + +#### `emitJs` + +If `true`, the plugin will emit `.d.ts` files for `.js` files as well. +This is useful when you want to generate type definitions for JavaScript files with JSDoc comments. + +Enabled by default when `allowJs` in compilerOptions is `true`. + +### Oxc + +#### `oxc` + +If `true`, the plugin will generate `.d.ts` files using [Oxc](https://oxc.rs/docs/guide/usage/transformer.html), which is significantly faster than the TypeScript compiler. + +This option is automatically enabled when `isolatedDeclarations` in `compilerOptions` is set to `true`. + +### TypeScript Go + +> [!WARNING] +> This feature is experimental and not yet recommended for production environments. + +#### `tsgo` + +**[Experimental]** Enables DTS generation using [`tsgo`](https://github.com/microsoft/typescript-go). + +To use this option, ensure that `@typescript/native-preview` is installed as a dependency. + +`tsconfigRaw` and `compilerOptions` options will be ignored when this option is enabled. + +## Code Splitting Support + +When using Rolldown's code splitting features `codeSplitting`, you should pay special attention to handling `.d.ts` files. The chunk names for `.d.ts` files must end with `.d`. + +```ts +export default { + codeSplitting: { + groups: [ + // handle .d.ts files + { test: /foo.*\.d\.[cm]?ts$/, name: 'shared.d' }, + // handle source files + { test: /foo/, name: 'shared' }, + ], + }, +} +``` + +## Differences from `rollup-plugin-dts` + +### Isolated Declarations + +The plugin leverages Oxc's `isolatedDeclarations` to generate `.d.ts` files when `isolatedDeclarations` is enabled, +offering significantly faster performance compared to the `typescript` compiler. + +### Single Build for ESM + +`rolldown-plugin-dts` generates separate chunks for `.d.ts` files, enabling both source code (`.js`) +and type definition files (`.d.ts`) to be produced in a single build process. + +However, this functionality is limited to ESM output format. Consequently, +**two** distinct build processes are required for CommonJS source code (`.cjs`) +and its corresponding type definition files (`.d.cts`). +In such cases, the `emitDtsOnly` option can be particularly helpful. + +The plugin expects ESM-style `.d.ts` input. CommonJS-style declaration syntax +such as `export =` or `import x = require("x")` will produce a warning and is +not guaranteed to bundle correctly. If this syntax comes from a dependency in +`node_modules`, mark that dependency as external in your Rolldown config. + +## Credits + +The project is inspired by [rollup-plugin-dts](https://github.com/Swatinem/rollup-plugin-dts) +but has been independently implemented. +We extend our gratitude to the original creators for their contributions. +Furthermore, the test suite is authorized by them and distributed under the MIT license. + +## Sponsors + +

+ + + +

+ +## License + +[MIT](./LICENSE) License © 2025-PRESENT [Kevin Deng](https://github.com/sxzz) + + + +[npm-version-src]: https://img.shields.io/npm/v/rolldown-plugin-dts.svg +[npm-version-href]: https://npmjs.com/package/rolldown-plugin-dts +[npm-downloads-src]: https://img.shields.io/npm/dm/rolldown-plugin-dts +[npm-downloads-href]: https://www.npmcharts.com/compare/rolldown-plugin-dts?interval=30 +[unit-test-src]: https://github.com/sxzz/rolldown-plugin-dts/actions/workflows/unit-test.yml/badge.svg +[unit-test-href]: https://github.com/sxzz/rolldown-plugin-dts/actions/workflows/unit-test.yml diff --git a/node_modules/rolldown-plugin-dts/package.json b/node_modules/rolldown-plugin-dts/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c1a893e30569142c4971ef9b409ff8b55977b185 --- /dev/null +++ b/node_modules/rolldown-plugin-dts/package.json @@ -0,0 +1,111 @@ +{ + "name": "rolldown-plugin-dts", + "type": "module", + "version": "0.25.2", + "description": "A Rolldown plugin to generate and bundle dts files.", + "author": "Kevin Deng ", + "license": "MIT", + "funding": "https://github.com/sponsors/sxzz", + "homepage": "https://github.com/sxzz/rolldown-plugin-dts#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/sxzz/rolldown-plugin-dts.git" + }, + "bugs": { + "url": "https://github.com/sxzz/rolldown-plugin-dts/issues" + }, + "keywords": [ + "rolldown", + "plugin", + "dts", + "typescript", + "vue", + "jsdoc" + ], + "exports": { + ".": "./dist/index.mjs", + "./internal": "./dist/internal.mjs", + "./tsc": "./dist/tsc.mjs", + "./tsc-context": "./dist/tsc-context.mjs", + "./tsc-worker": "./dist/tsc-worker.mjs", + "./package.json": "./package.json" + }, + "types": "./dist/index.d.mts", + "files": [ + "dist" + ], + "publishConfig": { + "access": "public" + }, + "engines": { + "node": "^22.18.0 || >=24.0.0" + }, + "peerDependencies": { + "@ts-macro/tsc": "^0.3.6", + "@typescript/native-preview": ">=7.0.0-dev.20260325.1", + "rolldown": "^1.0.0", + "typescript": "^5.0.0 || ^6.0.0", + "vue-tsc": "~3.2.0" + }, + "peerDependenciesMeta": { + "@ts-macro/tsc": { + "optional": true + }, + "@typescript/native-preview": { + "optional": true + }, + "typescript": { + "optional": true + }, + "vue-tsc": { + "optional": true + } + }, + "dependencies": { + "@babel/generator": "8.0.0-rc.6", + "@babel/helper-validator-identifier": "8.0.0-rc.6", + "@babel/parser": "8.0.0-rc.6", + "ast-kit": "^3.0.0-beta.1", + "birpc": "^4.0.0", + "dts-resolver": "^3.0.0", + "get-tsconfig": "5.0.0-beta.5", + "obug": "^2.1.1" + }, + "devDependencies": { + "@babel/types": "^8.0.0-rc.6", + "@jridgewell/source-map": "^0.3.11", + "@sxzz/eslint-config": "^8.1.0", + "@sxzz/prettier-config": "^2.3.1", + "@sxzz/test-utils": "^0.5.18", + "@types/node": "^25.9.1", + "@typescript/native-preview": "7.0.0-dev.20260527.2", + "@volar/typescript": "^2.4.28", + "@vue/language-core": "^3.3.2", + "arktype": "^2.2.0", + "bumpp": "^11.1.0", + "diff": "^9.0.0", + "eslint": "^10.4.0", + "prettier": "^3.8.3", + "rolldown": "^1.0.3", + "rolldown-plugin-require-cjs": "^0.4.0", + "rollup-plugin-dts": "^6.4.1", + "tsdown": "^0.22.1", + "tsnapi": "^0.3.3", + "typescript": "^6.0.3", + "vitest": "^4.1.7", + "vue": "^3.5.35", + "vue-tsc": "^3.3.2", + "zod": "^4.4.3" + }, + "prettier": "@sxzz/prettier-config", + "scripts": { + "lint": "eslint --cache .", + "lint:fix": "pnpm run lint --fix", + "build": "tsdown", + "dev": "tsdown --watch", + "test": "vitest", + "typecheck": "tsgo --noEmit", + "format": "prettier --cache --write .", + "release": "bumpp" + } +} \ No newline at end of file diff --git a/node_modules/rolldown/LICENSE b/node_modules/rolldown/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..afc0cdbabfb99ed4030bf9be2b852977f1ed72a0 --- /dev/null +++ b/node_modules/rolldown/LICENSE @@ -0,0 +1,25 @@ +MIT License + +Copyright (c) 2024-present VoidZero Inc. & Contributors + +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. + +end of terms and conditions + +The licenses of externally maintained libraries from which parts of the Software is derived are listed [here](https://github.com/rolldown/rolldown/blob/main/THIRD-PARTY-LICENSE). diff --git a/node_modules/rolldown/README.md b/node_modules/rolldown/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e1c9c293bbf6fc4eda0f00ca826960deb58dec5c --- /dev/null +++ b/node_modules/rolldown/README.md @@ -0,0 +1,11 @@ +# Rolldown + +> Fast Rust-based bundler for JavaScript with Rollup-compatible API + +- ⚡️ Lightning Fast Performance +- 🔌 Rollup-Compatible APIs +- ⏩ esbuild Feature Parity + +Rolldown is primarily designed to serve as the underlying bundler in [Vite](https://vite.dev/), with the goal to replace esbuild and Rollup with one unified build tool. Although designed for Vite, Rolldown is also fully capable of being used as a standalone, general-purpose bundler. It can serve as a drop-in replacement for Rollup in most cases, and can also be used as an esbuild alternative when better chunking control is needed. + +[Read the Docs to Learn More](https://rolldown.rs). diff --git a/node_modules/rolldown/bin/cli.mjs b/node_modules/rolldown/bin/cli.mjs new file mode 100644 index 0000000000000000000000000000000000000000..814234a5ca3ad686aa259095d82e9212195b9664 --- /dev/null +++ b/node_modules/rolldown/bin/cli.mjs @@ -0,0 +1,2 @@ +#!/usr/bin/env node +import '../dist/cli.mjs'; diff --git a/node_modules/rolldown/package.json b/node_modules/rolldown/package.json new file mode 100644 index 0000000000000000000000000000000000000000..91e352c746dfb8f4faddffd88835a842b173ea1c --- /dev/null +++ b/node_modules/rolldown/package.json @@ -0,0 +1,153 @@ +{ + "name": "rolldown", + "version": "1.0.3", + "description": "Fast JavaScript/TypeScript bundler in Rust with Rollup-compatible API.", + "keywords": [ + "bundler", + "esbuild", + "parcel", + "rolldown", + "rollup", + "webpack" + ], + "homepage": "https://rolldown.rs/", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/rolldown/rolldown.git", + "directory": "packages/rolldown" + }, + "bin": { + "rolldown": "./bin/cli.mjs" + }, + "files": [ + "bin", + "cli", + "dist", + "!dist/*.node" + ], + "type": "module", + "main": "./dist/index.mjs", + "module": "./dist/index.mjs", + "types": "./dist/index.d.mts", + "imports": { + "#parallel-plugin-worker": "./dist/parallel-plugin-worker.mjs" + }, + "exports": { + ".": "./dist/index.mjs", + "./config": "./dist/config.mjs", + "./experimental": "./dist/experimental-index.mjs", + "./experimental/runtime-types": { + "types": "./dist/experimental-runtime-types.d.ts" + }, + "./filter": "./dist/filter-index.mjs", + "./getLogFilter": "./dist/get-log-filter.mjs", + "./parallelPlugin": "./dist/parallel-plugin.mjs", + "./parseAst": "./dist/parse-ast-index.mjs", + "./package.json": "./package.json", + "./plugins": "./dist/plugins-index.mjs", + "./utils": "./dist/utils-index.mjs" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "dependencies": { + "@oxc-project/types": "=0.133.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "devDependencies": { + "@napi-rs/cli": "^3.6.1", + "@napi-rs/wasm-runtime": "^1.1.4", + "@oxc-node/cli": "^0.1.0", + "@rollup/plugin-json": "^6.1.0", + "buble": "^0.20.0", + "cac": "^7.0.0", + "consola": "^3.4.2", + "execa": "^9.2.0", + "glob": "^13.0.0", + "oxc-parser": "=0.133.0", + "pathe": "^2.0.3", + "remeda": "^2.34.1", + "rolldown-plugin-dts": "^0.25.1", + "rollup": "^4.60.4", + "signal-exit": "4.1.0", + "source-map": "0.7.6", + "typescript": "^6.0.0", + "valibot": "1.4.0", + "rolldown": "1.0.3" + }, + "napi": { + "binaryName": "rolldown-binding", + "dtsHeader": "type MaybePromise = T | Promise\ntype Nullable = T | null | undefined\ntype VoidNullable = T | null | undefined | void\nexport type BindingStringOrRegex = string | RegExp\nexport type BindingResult = { errors: BindingError[], isBindingErrors: boolean } | T\n\n", + "packageName": "@rolldown/binding", + "targets": [ + "x86_64-apple-darwin", + "x86_64-pc-windows-msvc", + "x86_64-unknown-linux-gnu", + "x86_64-unknown-linux-musl", + "x86_64-unknown-freebsd", + "armv7-unknown-linux-gnueabihf", + "aarch64-unknown-linux-gnu", + "aarch64-apple-darwin", + "aarch64-unknown-linux-musl", + "aarch64-unknown-linux-ohos", + "aarch64-pc-windows-msvc", + "aarch64-linux-android", + "wasm32-wasip1-threads", + "s390x-unknown-linux-gnu", + "powerpc64le-unknown-linux-gnu" + ], + "wasm": { + "initialMemory": 16384, + "browser": { + "fs": true, + "asyncInit": true, + "errorEvent": true + } + } + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-darwin-x64": "1.0.3", + "@rolldown/binding-win32-x64-msvc": "1.0.3", + "@rolldown/binding-linux-x64-gnu": "1.0.3", + "@rolldown/binding-linux-x64-musl": "1.0.3", + "@rolldown/binding-freebsd-x64": "1.0.3", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.3", + "@rolldown/binding-linux-arm64-gnu": "1.0.3", + "@rolldown/binding-darwin-arm64": "1.0.3", + "@rolldown/binding-linux-arm64-musl": "1.0.3", + "@rolldown/binding-openharmony-arm64": "1.0.3", + "@rolldown/binding-win32-arm64-msvc": "1.0.3", + "@rolldown/binding-android-arm64": "1.0.3", + "@rolldown/binding-wasm32-wasi": "1.0.3", + "@rolldown/binding-linux-s390x-gnu": "1.0.3", + "@rolldown/binding-linux-ppc64-gnu": "1.0.3" + }, + "scripts": { + "# Scrips for binding #": "_", + "artifacts": "napi artifacts --cwd ./src --package-json-path ../package.json -o=../artifacts --npm-dir ../npm", + "build-binding": "oxnode ./build-binding.ts", + "build-binding:release": "pnpm build-binding --release", + "build-binding:profile": "pnpm build-binding --profile profile", + "build-binding:wasi": "pnpm build-binding --target wasm32-wasip1-threads", + "build-binding:wasi:release": "pnpm build-binding --profile release-wasi --target wasm32-wasip1-threads", + "# Scrips for node #": "_", + "build-node": "node --enable-source-maps --import @oxc-node/core/register -C dev ./build.ts", + "build-types-check": "tsc -p ./tsconfig.check.json", + "build-js-glue": "pnpm run --sequential '/^build-(node|types-check)$/'", + "build-native:debug": "pnpm run --sequential '/^build-(binding|js-glue)$/'", + "build-native:release": "pnpm run --sequential '/^build-(binding:release|js-glue)$/'", + "build-native:profile": "pnpm run build-binding:profile && pnpm run build-js-glue", + "build-native:memory-profile": "pnpm run build-binding:profile --features default_global_allocator && pnpm run build-js-glue", + "build-wasi:debug": "TARGET='rolldown-wasi' pnpm run --sequential '/^build-(binding|binding:wasi|node)$/'", + "build-wasi:release": "TARGET='rolldown-wasi' pnpm run --sequential '/^build-(binding|binding:wasi:release|node)$/'", + "build-browser-pkg:debug": "TARGET='browser' pnpm run --sequential '/^build-(binding:wasi|node)$/'", + "build-browser-pkg:release": "TARGET='browser' pnpm run --sequential '/^build-(binding:wasi:release|node)$/'", + "# Scrips for docs #": "_", + "publint": "publint ." + } +} \ No newline at end of file diff --git a/node_modules/rollup/LICENSE.md b/node_modules/rollup/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..7b806824370697048284c1726fc4d1b567bfea68 --- /dev/null +++ b/node_modules/rollup/LICENSE.md @@ -0,0 +1,679 @@ +# Rollup core license +Rollup is released under the MIT license: + +The MIT License (MIT) + +Copyright (c) 2017 [these people](https://github.com/rollup/rollup/graphs/contributors) + +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. + +# Licenses of bundled dependencies +The published Rollup artifact additionally contains code with the following licenses: +MIT, ISC, 0BSD + +# Bundled dependencies: +## @jridgewell/sourcemap-codec +License: MIT +By: Justin Ridgewell +Repository: git+https://github.com/jridgewell/sourcemaps.git + +> Copyright 2024 Justin Ridgewell +> +> 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. + +--------------------------------------- + +## @rollup/pluginutils +License: MIT +By: Rich Harris +Repository: rollup/plugins + +> The MIT License (MIT) +> +> Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors) +> +> 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. + +--------------------------------------- + +## anymatch +License: ISC +By: Elan Shanker +Repository: https://github.com/micromatch/anymatch + +> The ISC License +> +> Copyright (c) 2019 Elan Shanker, Paul Miller (https://paulmillr.com) +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## binary-extensions +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/binary-extensions + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://sindresorhus.com) +> Copyright (c) Paul Miller (https://paulmillr.com) +> +> 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. + +--------------------------------------- + +## braces +License: MIT +By: Jon Schlinkert, Brian Woodward, Elan Shanker, Eugene Sharygin, hemanth.hm +Repository: micromatch/braces + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## builtin-modules +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/builtin-modules + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://sindresorhus.com) +> +> 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. + +--------------------------------------- + +## chokidar +License: MIT +By: Paul Miller, Elan Shanker +Repository: git+https://github.com/paulmillr/chokidar.git + +> The MIT License (MIT) +> +> Copyright (c) 2012-2019 Paul Miller (https://paulmillr.com), Elan Shanker +> +> 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. + +--------------------------------------- + +## date-time +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/date-time + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://sindresorhus.com) +> +> 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. + +--------------------------------------- + +## fill-range +License: MIT +By: Jon Schlinkert, Edo Rivai, Paul Miller, Rouven Weßling +Repository: jonschlinkert/fill-range + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## flru +License: MIT +By: Luke Edwards +Repository: lukeed/flru + +> MIT License +> +> Copyright (c) Luke Edwards (lukeed.com) +> +> 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. + +--------------------------------------- + +## glob-parent +License: ISC +By: Gulp Team, Elan Shanker, Blaine Bublitz +Repository: gulpjs/glob-parent + +> The ISC License +> +> Copyright (c) 2015, 2019 Elan Shanker +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +> IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## is-binary-path +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/is-binary-path + +> MIT License +> +> Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), Paul Miller (https://paulmillr.com) +> +> 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. + +--------------------------------------- + +## is-extglob +License: MIT +By: Jon Schlinkert +Repository: jonschlinkert/is-extglob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2016, Jon Schlinkert +> +> 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. + +--------------------------------------- + +## is-glob +License: MIT +By: Jon Schlinkert, Brian Woodward, Daniel Perez +Repository: micromatch/is-glob + +> The MIT License (MIT) +> +> Copyright (c) 2014-2017, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## is-number +License: MIT +By: Jon Schlinkert, Olsten Larck, Rouven Weßling +Repository: jonschlinkert/is-number + +> The MIT License (MIT) +> +> Copyright (c) 2014-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## is-reference +License: MIT +By: Rich Harris +Repository: git+https://github.com/Rich-Harris/is-reference.git + +--------------------------------------- + +## locate-character +License: MIT +By: Rich Harris +Repository: git+https://gitlab.com/Rich-Harris/locate-character.git + +--------------------------------------- + +## magic-string +License: MIT +By: Rich Harris +Repository: git+https://github.com/Rich-Harris/magic-string.git + +> Copyright 2018 Rich Harris +> +> 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. + +--------------------------------------- + +## normalize-path +License: MIT +By: Jon Schlinkert, Blaine Bublitz +Repository: jonschlinkert/normalize-path + +> The MIT License (MIT) +> +> Copyright (c) 2014-2018, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## parse-ms +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/parse-ms + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://sindresorhus.com) +> +> 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. + +--------------------------------------- + +## picocolors +License: ISC +By: Alexey Raspopov +Repository: alexeyraspopov/picocolors + +> ISC License +> +> Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted, provided that the above +> copyright notice and this permission notice appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +> MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +> ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +> WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +> ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +> OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## picomatch +License: MIT +By: Jon Schlinkert +Repository: micromatch/picomatch + +> The MIT License (MIT) +> +> Copyright (c) 2017-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## pretty-bytes +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/pretty-bytes + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://sindresorhus.com) +> +> 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. + +--------------------------------------- + +## pretty-ms +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/pretty-ms + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://sindresorhus.com) +> +> 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. + +--------------------------------------- + +## readdirp +License: MIT +By: Thorsten Lorenz, Paul Miller +Repository: git://github.com/paulmillr/readdirp.git + +> MIT License +> +> Copyright (c) 2012-2019 Thorsten Lorenz, Paul Miller (https://paulmillr.com) +> +> 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. + +--------------------------------------- + +## signal-exit +License: ISC +By: Ben Coe +Repository: https://github.com/tapjs/signal-exit.git + +> The ISC License +> +> Copyright (c) 2015-2023 Benjamin Coe, Isaac Z. Schlueter, and Contributors +> +> Permission to use, copy, modify, and/or distribute this software +> for any purpose with or without fee is hereby granted, provided +> that the above copyright notice and this permission notice +> appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +> OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +> LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +> OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +> WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +> ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## time-zone +License: MIT +By: Sindre Sorhus +Repository: sindresorhus/time-zone + +> MIT License +> +> Copyright (c) Sindre Sorhus (https://sindresorhus.com) +> +> 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. + +--------------------------------------- + +## to-regex-range +License: MIT +By: Jon Schlinkert, Rouven Weßling +Repository: micromatch/to-regex-range + +> The MIT License (MIT) +> +> Copyright (c) 2015-present, Jon Schlinkert. +> +> 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. + +--------------------------------------- + +## tslib +License: 0BSD +By: Microsoft Corp. +Repository: https://github.com/Microsoft/tslib.git + +> Copyright (c) Microsoft Corporation. +> +> Permission to use, copy, modify, and/or distribute this software for any +> purpose with or without fee is hereby granted. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +> REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +> AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +> INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +> LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +> OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +> PERFORMANCE OF THIS SOFTWARE. + +--------------------------------------- + +## yargs-parser +License: ISC +By: Ben Coe +Repository: https://github.com/yargs/yargs-parser.git + +> Copyright (c) 2016, Contributors +> +> Permission to use, copy, modify, and/or distribute this software +> for any purpose with or without fee is hereby granted, provided +> that the above copyright notice and this permission notice +> appear in all copies. +> +> THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +> WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +> OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +> LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +> OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +> WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +> ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/rollup/README.md b/node_modules/rollup/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9d9047a9551b28f2d40151171421c6df7504c833 --- /dev/null +++ b/node_modules/rollup/README.md @@ -0,0 +1,134 @@ +

+ +

+ +

+ + npm version + + + node compatibility + + + install size + + + code coverage + + + backers + + + sponsors + + + license + + + Join the chat at https://is.gd/rollup_chat + +

+ +

Rollup

+ +## Overview + +Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the standardized ES module format for code, instead of previous idiosyncratic solutions such as CommonJS and AMD. ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. Rollup can optimize ES modules for faster native loading in modern browsers, or output a legacy module format allowing ES module workflows today. + +## Quick Start Guide + +Install with `npm install --global rollup`. Rollup can be used either through a [command line interface](https://rollupjs.org/command-line-interface/) with an optional configuration file or else through its [JavaScript API](https://rollupjs.org/javascript-api/). Run `rollup --help` to see the available options and parameters. The starter project templates, [rollup-starter-lib](https://github.com/rollup/rollup-starter-lib) and [rollup-starter-app](https://github.com/rollup/rollup-starter-app), demonstrate common configuration options, and more detailed instructions are available throughout the [user guide](https://rollupjs.org/introduction/). + +### Commands + +These commands assume the entry point to your application is named main.js, and that you'd like all imports compiled into a single file named bundle.js. + +For browsers: + +```bash +# compile to a ' +}); +``` + +The above will produce the following string, HTML-escaped output which is safe to put into an HTML document as it will not cause the inline script element to terminate: + +```js +'{"haxorXSS":"\\u003C\\u002Fscript\\u003E"}' +``` + +> You can pass an optional `unsafe` argument to `serialize()` for straight serialization. + +### Options + +The `serialize()` function accepts an `options` object as its second argument. All options are being defaulted to `undefined`: + +#### `options.space` + +This option is the same as the `space` argument that can be passed to [`JSON.stringify`][JSON.stringify]. It can be used to add whitespace and indentation to the serialized output to make it more readable. + +```js +serialize(obj, {space: 2}); +``` + +#### `options.isJSON` + +This option is a signal to `serialize()` that the object being serialized does not contain any function or regexps values. This enables a hot-path that allows serialization to be over 3x faster. If you're serializing a lot of data, and know its pure JSON, then you can enable this option for a speed-up. + +**Note:** That when using this option, the output will still be escaped to protect against XSS. + +```js +serialize(obj, {isJSON: true}); +``` + +#### `options.unsafe` + +This option is to signal `serialize()` that we want to do a straight conversion, without the XSS protection. This options needs to be explicitly set to `true`. HTML characters and JavaScript line terminators will not be escaped. You will have to roll your own. + +```js +serialize(obj, {unsafe: true}); +``` + +#### `options.ignoreFunction` + +This option is to signal `serialize()` that we do not want serialize JavaScript function. +Just treat function like `JSON.stringify` do, but other features will work as expected. + +```js +serialize(obj, {ignoreFunction: true}); +``` + +## Deserializing + +For some use cases you might also need to deserialize the string. This is explicitly not part of this module. However, you can easily write it yourself: + +```js +function deserialize(serializedJavascript){ + return eval('(' + serializedJavascript + ')'); +} +``` + +**Note:** Don't forget the parentheses around the serialized javascript, as the opening bracket `{` will be considered to be the start of a body. + +## License + +This software is free to use under the Yahoo! Inc. BSD license. +See the [LICENSE file][LICENSE] for license text and copyright information. + + +[npm]: https://www.npmjs.org/package/serialize-javascript +[npm-badge]: https://img.shields.io/npm/v/serialize-javascript.svg?style=flat-square +[express-state]: https://github.com/yahoo/express-state +[JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify +[LICENSE]: https://github.com/yahoo/serialize-javascript/blob/main/LICENSE +[worker threads]: https://nodejs.org/api/worker_threads.html +[closed-over variables]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures diff --git a/node_modules/serialize-javascript/index.js b/node_modules/serialize-javascript/index.js new file mode 100644 index 0000000000000000000000000000000000000000..238911031c905af2b1bb8337ee38b58b9d7bb586 --- /dev/null +++ b/node_modules/serialize-javascript/index.js @@ -0,0 +1,297 @@ +/* +Copyright (c) 2014, Yahoo! Inc. All rights reserved. +Copyrights licensed under the New BSD License. +See the accompanying LICENSE file for terms. +*/ + +'use strict'; + +// Generate an internal UID to make the regexp pattern harder to guess. +var UID_LENGTH = 16; +var UID = generateUID(); +var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B|L)-' + UID + '-(\\d+)__@"', 'g'); + +var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g; +var IS_PURE_FUNCTION = /function.*?\(/; +var IS_ARROW_FUNCTION = /.*?=>.*?/; +var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g; +// Regex to match and variations (case-insensitive) for XSS protection +// Matches +var SCRIPT_CLOSE_REGEXP = /<\/script[^>]*>/gi; + +var RESERVED_SYMBOLS = ['*', 'async']; + +// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their +// Unicode char counterparts which are safe to use in JavaScript strings. +var ESCAPED_CHARS = { + '<' : '\\u003C', + '>' : '\\u003E', + '/' : '\\u002F', + '\u2028': '\\u2028', + '\u2029': '\\u2029' +}; + +function escapeUnsafeChars(unsafeChar) { + return ESCAPED_CHARS[unsafeChar]; +} + +// Escape function body for XSS protection while preserving arrow function syntax +function escapeFunctionBody(str) { + // Escape sequences and variations (case-insensitive) - the main XSS risk + // Matches + // This must be done first before other replacements + str = str.replace(SCRIPT_CLOSE_REGEXP, function(match) { + // Escape all <, /, and > characters in the closing script tag + return match.replace(//g, '\\u003E'); + }); + // Escape line terminators (these are always unsafe) + str = str.replace(/\u2028/g, '\\u2028'); + str = str.replace(/\u2029/g, '\\u2029'); + return str; +} + +function generateUID() { + var bytes = crypto.getRandomValues(new Uint8Array(UID_LENGTH)); + var result = ''; + for(var i=0; i) while escaping + if (options && options.unsafe !== true) { + serializedFn = escapeFunctionBody(serializedFn); + } + + // pure functions, example: {key: function() {}} + if(IS_PURE_FUNCTION.test(serializedFn)) { + return serializedFn; + } + + // arrow functions, example: arg1 => arg1+5 + if(IS_ARROW_FUNCTION.test(serializedFn)) { + return serializedFn; + } + + var argsStartsAt = serializedFn.indexOf('('); + var def = serializedFn.substr(0, argsStartsAt) + .trim() + .split(' ') + .filter(function(val) { return val.length > 0 }); + + var nonReservedSymbols = def.filter(function(val) { + return RESERVED_SYMBOLS.indexOf(val) === -1 + }); + + // enhanced literal objects, example: {key() {}} + if(nonReservedSymbols.length > 0) { + return (def.indexOf('async') > -1 ? 'async ' : '') + 'function' + + (def.join('').indexOf('*') > -1 ? '*' : '') + + serializedFn.substr(argsStartsAt); + } + + // arrow functions + return serializedFn; + } + + // Check if the parameter is function + if (options.ignoreFunction && typeof obj === "function") { + obj = undefined; + } + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (obj === undefined) { + return String(obj); + } + + var str; + + // Creates a JSON string representation of the value. + // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args. + if (options.isJSON && !options.space) { + str = JSON.stringify(obj); + } else { + str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space); + } + + // Protects against `JSON.stringify()` returning `undefined`, by serializing + // to the literal string: "undefined". + if (typeof str !== 'string') { + return String(str); + } + + // Replace unsafe HTML and invalid JavaScript line terminator chars with + // their safe Unicode char counterpart. This _must_ happen before the + // regexps and functions are serialized and added back to the string. + if (options.unsafe !== true) { + str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars); + } + + if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && arrays.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0 && urls.length === 0) { + return str; + } + + // Replaces all occurrences of function, regexp, date, map and set placeholders in the + // JSON string with their string representations. If the original value can + // not be found, then `undefined` is used. + return str.replace(PLACE_HOLDER_REGEXP, function (match, backSlash, type, valueIndex) { + // The placeholder may not be preceded by a backslash. This is to prevent + // replacing things like `"a\"@__R--0__@"` and thus outputting + // invalid JS. + if (backSlash) { + return match; + } + + if (type === 'D') { + // Validate ISO string format to prevent code injection via spoofed toISOString() + var isoStr = String(dates[valueIndex].toISOString()); + if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/.test(isoStr)) { + throw new TypeError('Invalid Date ISO string'); + } + return "new Date(\"" + isoStr + "\")"; + } + + if (type === 'R') { + // Sanitize flags to prevent code injection (only allow valid RegExp flag characters) + var flags = String(regexps[valueIndex].flags).replace(/[^gimsuydv]/g, ''); + return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + flags + "\")"; + } + + if (type === 'M') { + return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")"; + } + + if (type === 'S') { + return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")"; + } + + if (type === 'A') { + return "Array.prototype.slice.call(" + serialize(Object.assign({ length: arrays[valueIndex].length }, arrays[valueIndex]), options) + ")"; + } + + if (type === 'U') { + return 'undefined' + } + + if (type === 'I') { + return infinities[valueIndex]; + } + + if (type === 'B') { + return "BigInt(\"" + bigInts[valueIndex] + "\")"; + } + + if (type === 'L') { + return "new URL(" + serialize(urls[valueIndex].toString(), options) + ")"; + } + + var fn = functions[valueIndex]; + + return serializeFunc(fn, options); + }); +} diff --git a/node_modules/serialize-javascript/package.json b/node_modules/serialize-javascript/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d51c610089552e7d2d8978951596a22601ad018a --- /dev/null +++ b/node_modules/serialize-javascript/package.json @@ -0,0 +1,33 @@ +{ + "name": "serialize-javascript", + "version": "7.0.5", + "description": "Serialize JavaScript to a superset of JSON that includes regular expressions and functions.", + "main": "index.js", + "scripts": { + "benchmark": "node -v && node test/benchmark/serialize.js", + "test": "node --test test/unit/*.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/yahoo/serialize-javascript.git" + }, + "keywords": [ + "serialize", + "serialization", + "javascript", + "js", + "json" + ], + "author": "Eric Ferraiuolo ", + "license": "BSD-3-Clause", + "bugs": { + "url": "https://github.com/yahoo/serialize-javascript/issues" + }, + "homepage": "https://github.com/yahoo/serialize-javascript", + "devDependencies": { + "benchmark": "^2.1.4" + }, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/node_modules/serve-static/HISTORY.md b/node_modules/serve-static/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..99196696860eafda13a5913b504d5190a48fbe6b --- /dev/null +++ b/node_modules/serve-static/HISTORY.md @@ -0,0 +1,493 @@ +1.16.3 / 2024-12-15 +=================== + +* deps: send@~0.19.1 + - deps: encodeurl@~2.0.0 + +1.16.2 / 2024-09-11 +=================== + +* deps: encodeurl@~2.0.0 + +1.16.1 / 2024-09-11 +=================== + +* deps: send@0.19.0 + +1.16.0 / 2024-09-10 +=================== + +* Remove link renderization in html while redirecting + + +1.15.0 / 2022-03-24 +=================== + + * deps: send@0.18.0 + - Fix emitted 416 error missing headers property + - Limit the headers removed for 304 response + - deps: depd@2.0.0 + - deps: destroy@1.2.0 + - deps: http-errors@2.0.0 + - deps: on-finished@2.4.1 + - deps: statuses@2.0.1 + +1.14.2 / 2021-12-15 +=================== + + * deps: send@0.17.2 + - deps: http-errors@1.8.1 + - deps: ms@2.1.3 + - pref: ignore empty http tokens + +1.14.1 / 2019-05-10 +=================== + + * Set stricter CSP header in redirect response + * deps: send@0.17.1 + - deps: range-parser@~1.2.1 + +1.14.0 / 2019-05-07 +=================== + + * deps: parseurl@~1.3.3 + * deps: send@0.17.0 + - deps: http-errors@~1.7.2 + - deps: mime@1.6.0 + - deps: ms@2.1.1 + - deps: statuses@~1.5.0 + - perf: remove redundant `path.normalize` call + +1.13.2 / 2018-02-07 +=================== + + * Fix incorrect end tag in redirects + * deps: encodeurl@~1.0.2 + - Fix encoding `%` as last character + * deps: send@0.16.2 + - deps: depd@~1.1.2 + - deps: encodeurl@~1.0.2 + - deps: statuses@~1.4.0 + +1.13.1 / 2017-09-29 +=================== + + * Fix regression when `root` is incorrectly set to a file + * deps: send@0.16.1 + +1.13.0 / 2017-09-27 +=================== + + * deps: send@0.16.0 + - Add 70 new types for file extensions + - Add `immutable` option + - Fix missing `` in default error & redirects + - Set charset as "UTF-8" for .js and .json + - Use instance methods on steam to check for listeners + - deps: mime@1.4.1 + - perf: improve path validation speed + +1.12.6 / 2017-09-22 +=================== + + * deps: send@0.15.6 + - deps: debug@2.6.9 + - perf: improve `If-Match` token parsing + * perf: improve slash collapsing + +1.12.5 / 2017-09-21 +=================== + + * deps: parseurl@~1.3.2 + - perf: reduce overhead for full URLs + - perf: unroll the "fast-path" `RegExp` + * deps: send@0.15.5 + - Fix handling of modified headers with invalid dates + - deps: etag@~1.8.1 + - deps: fresh@0.5.2 + +1.12.4 / 2017-08-05 +=================== + + * deps: send@0.15.4 + - deps: debug@2.6.8 + - deps: depd@~1.1.1 + - deps: http-errors@~1.6.2 + +1.12.3 / 2017-05-16 +=================== + + * deps: send@0.15.3 + - deps: debug@2.6.7 + +1.12.2 / 2017-04-26 +=================== + + * deps: send@0.15.2 + - deps: debug@2.6.4 + +1.12.1 / 2017-03-04 +=================== + + * deps: send@0.15.1 + - Fix issue when `Date.parse` does not return `NaN` on invalid date + - Fix strict violation in broken environments + +1.12.0 / 2017-02-25 +=================== + + * Send complete HTML document in redirect response + * Set default CSP header in redirect response + * deps: send@0.15.0 + - Fix false detection of `no-cache` request directive + - Fix incorrect result when `If-None-Match` has both `*` and ETags + - Fix weak `ETag` matching to match spec + - Remove usage of `res._headers` private field + - Support `If-Match` and `If-Unmodified-Since` headers + - Use `res.getHeaderNames()` when available + - Use `res.headersSent` when available + - deps: debug@2.6.1 + - deps: etag@~1.8.0 + - deps: fresh@0.5.0 + - deps: http-errors@~1.6.1 + +1.11.2 / 2017-01-23 +=================== + + * deps: send@0.14.2 + - deps: http-errors@~1.5.1 + - deps: ms@0.7.2 + - deps: statuses@~1.3.1 + +1.11.1 / 2016-06-10 +=================== + + * Fix redirect error when `req.url` contains raw non-URL characters + * deps: send@0.14.1 + +1.11.0 / 2016-06-07 +=================== + + * Use status code 301 for redirects + * deps: send@0.14.0 + - Add `acceptRanges` option + - Add `cacheControl` option + - Attempt to combine multiple ranges into single range + - Correctly inherit from `Stream` class + - Fix `Content-Range` header in 416 responses when using `start`/`end` options + - Fix `Content-Range` header missing from default 416 responses + - Ignore non-byte `Range` headers + - deps: http-errors@~1.5.0 + - deps: range-parser@~1.2.0 + - deps: statuses@~1.3.0 + - perf: remove argument reassignment + +1.10.3 / 2016-05-30 +=================== + + * deps: send@0.13.2 + - Fix invalid `Content-Type` header when `send.mime.default_type` unset + +1.10.2 / 2016-01-19 +=================== + + * deps: parseurl@~1.3.1 + - perf: enable strict mode + +1.10.1 / 2016-01-16 +=================== + + * deps: escape-html@~1.0.3 + - perf: enable strict mode + - perf: optimize string replacement + - perf: use faster string coercion + * deps: send@0.13.1 + - deps: depd@~1.1.0 + - deps: destroy@~1.0.4 + - deps: escape-html@~1.0.3 + - deps: range-parser@~1.0.3 + +1.10.0 / 2015-06-17 +=================== + + * Add `fallthrough` option + - Allows declaring this middleware is the final destination + - Provides better integration with Express patterns + * Fix reading options from options prototype + * Improve the default redirect response headers + * deps: escape-html@1.0.2 + * deps: send@0.13.0 + - Allow Node.js HTTP server to set `Date` response header + - Fix incorrectly removing `Content-Location` on 304 response + - Improve the default redirect response headers + - Send appropriate headers on default error response + - Use `http-errors` for standard emitted errors + - Use `statuses` instead of `http` module for status messages + - deps: escape-html@1.0.2 + - deps: etag@~1.7.0 + - deps: fresh@0.3.0 + - deps: on-finished@~2.3.0 + - perf: enable strict mode + - perf: remove unnecessary array allocations + * perf: enable strict mode + * perf: remove argument reassignment + +1.9.3 / 2015-05-14 +================== + + * deps: send@0.12.3 + - deps: debug@~2.2.0 + - deps: depd@~1.0.1 + - deps: etag@~1.6.0 + - deps: ms@0.7.1 + - deps: on-finished@~2.2.1 + +1.9.2 / 2015-03-14 +================== + + * deps: send@0.12.2 + - Throw errors early for invalid `extensions` or `index` options + - deps: debug@~2.1.3 + +1.9.1 / 2015-02-17 +================== + + * deps: send@0.12.1 + - Fix regression sending zero-length files + +1.9.0 / 2015-02-16 +================== + + * deps: send@0.12.0 + - Always read the stat size from the file + - Fix mutating passed-in `options` + - deps: mime@1.3.4 + +1.8.1 / 2015-01-20 +================== + + * Fix redirect loop in Node.js 0.11.14 + * deps: send@0.11.1 + - Fix root path disclosure + +1.8.0 / 2015-01-05 +================== + + * deps: send@0.11.0 + - deps: debug@~2.1.1 + - deps: etag@~1.5.1 + - deps: ms@0.7.0 + - deps: on-finished@~2.2.0 + +1.7.2 / 2015-01-02 +================== + + * Fix potential open redirect when mounted at root + +1.7.1 / 2014-10-22 +================== + + * deps: send@0.10.1 + - deps: on-finished@~2.1.1 + +1.7.0 / 2014-10-15 +================== + + * deps: send@0.10.0 + - deps: debug@~2.1.0 + - deps: depd@~1.0.0 + - deps: etag@~1.5.0 + +1.6.5 / 2015-02-04 +================== + + * Fix potential open redirect when mounted at root + - Back-ported from v1.7.2 + +1.6.4 / 2014-10-08 +================== + + * Fix redirect loop when index file serving disabled + +1.6.3 / 2014-09-24 +================== + + * deps: send@0.9.3 + - deps: etag@~1.4.0 + +1.6.2 / 2014-09-15 +================== + + * deps: send@0.9.2 + - deps: depd@0.4.5 + - deps: etag@~1.3.1 + - deps: range-parser@~1.0.2 + +1.6.1 / 2014-09-07 +================== + + * deps: send@0.9.1 + - deps: fresh@0.2.4 + +1.6.0 / 2014-09-07 +================== + + * deps: send@0.9.0 + - Add `lastModified` option + - Use `etag` to generate `ETag` header + - deps: debug@~2.0.0 + +1.5.4 / 2014-09-04 +================== + + * deps: send@0.8.5 + - Fix a path traversal issue when using `root` + - Fix malicious path detection for empty string path + +1.5.3 / 2014-08-17 +================== + + * deps: send@0.8.3 + +1.5.2 / 2014-08-14 +================== + + * deps: send@0.8.2 + - Work around `fd` leak in Node.js 0.10 for `fs.ReadStream` + +1.5.1 / 2014-08-09 +================== + + * Fix parsing of weird `req.originalUrl` values + * deps: parseurl@~1.3.0 + * deps: utils-merge@1.0.0 + +1.5.0 / 2014-08-05 +================== + + * deps: send@0.8.1 + - Add `extensions` option + +1.4.4 / 2014-08-04 +================== + + * deps: send@0.7.4 + - Fix serving index files without root dir + +1.4.3 / 2014-07-29 +================== + + * deps: send@0.7.3 + - Fix incorrect 403 on Windows and Node.js 0.11 + +1.4.2 / 2014-07-27 +================== + + * deps: send@0.7.2 + - deps: depd@0.4.4 + +1.4.1 / 2014-07-26 +================== + + * deps: send@0.7.1 + - deps: depd@0.4.3 + +1.4.0 / 2014-07-21 +================== + + * deps: parseurl@~1.2.0 + - Cache URLs based on original value + - Remove no-longer-needed URL mis-parse work-around + - Simplify the "fast-path" `RegExp` + * deps: send@0.7.0 + - Add `dotfiles` option + - deps: debug@1.0.4 + - deps: depd@0.4.2 + +1.3.2 / 2014-07-11 +================== + + * deps: send@0.6.0 + - Cap `maxAge` value to 1 year + - deps: debug@1.0.3 + +1.3.1 / 2014-07-09 +================== + + * deps: parseurl@~1.1.3 + - faster parsing of href-only URLs + +1.3.0 / 2014-06-28 +================== + + * Add `setHeaders` option + * Include HTML link in redirect response + * deps: send@0.5.0 + - Accept string for `maxAge` (converted by `ms`) + +1.2.3 / 2014-06-11 +================== + + * deps: send@0.4.3 + - Do not throw un-catchable error on file open race condition + - Use `escape-html` for HTML escaping + - deps: debug@1.0.2 + - deps: finished@1.2.2 + - deps: fresh@0.2.2 + +1.2.2 / 2014-06-09 +================== + + * deps: send@0.4.2 + - fix "event emitter leak" warnings + - deps: debug@1.0.1 + - deps: finished@1.2.1 + +1.2.1 / 2014-06-02 +================== + + * use `escape-html` for escaping + * deps: send@0.4.1 + - Send `max-age` in `Cache-Control` in correct format + +1.2.0 / 2014-05-29 +================== + + * deps: send@0.4.0 + - Calculate ETag with md5 for reduced collisions + - Fix wrong behavior when index file matches directory + - Ignore stream errors after request ends + - Skip directories in index file search + - deps: debug@0.8.1 + +1.1.0 / 2014-04-24 +================== + + * Accept options directly to `send` module + * deps: send@0.3.0 + +1.0.4 / 2014-04-07 +================== + + * Resolve relative paths at middleware setup + * Use parseurl to parse the URL from request + +1.0.3 / 2014-03-20 +================== + + * Do not rely on connect-like environments + +1.0.2 / 2014-03-06 +================== + + * deps: send@0.2.0 + +1.0.1 / 2014-03-05 +================== + + * Add mime export for back-compat + +1.0.0 / 2014-03-05 +================== + + * Genesis from `connect` diff --git a/node_modules/serve-static/LICENSE b/node_modules/serve-static/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..cbe62e8e7f20b6aa70e4d138b1503837ae4e5f95 --- /dev/null +++ b/node_modules/serve-static/LICENSE @@ -0,0 +1,25 @@ +(The MIT License) + +Copyright (c) 2010 Sencha Inc. +Copyright (c) 2011 LearnBoost +Copyright (c) 2011 TJ Holowaychuk +Copyright (c) 2014-2016 Douglas Christopher Wilson + +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. diff --git a/node_modules/serve-static/README.md b/node_modules/serve-static/README.md new file mode 100644 index 0000000000000000000000000000000000000000..262d944ab7510ecb39b47055189a92793c94aa26 --- /dev/null +++ b/node_modules/serve-static/README.md @@ -0,0 +1,257 @@ +# serve-static + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Linux Build][github-actions-ci-image]][github-actions-ci-url] +[![Windows Build][appveyor-image]][appveyor-url] +[![Test Coverage][coveralls-image]][coveralls-url] + +## Install + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install serve-static +``` + +## API + +```js +var serveStatic = require('serve-static') +``` + +### serveStatic(root, options) + +Create a new middleware function to serve files from within a given root +directory. The file to serve will be determined by combining `req.url` +with the provided root directory. When a file is not found, instead of +sending a 404 response, this module will instead call `next()` to move on +to the next middleware, allowing for stacking and fall-backs. + +#### Options + +##### acceptRanges + +Enable or disable accepting ranged requests, defaults to true. +Disabling this will not send `Accept-Ranges` and ignore the contents +of the `Range` request header. + +##### cacheControl + +Enable or disable setting `Cache-Control` response header, defaults to +true. Disabling this will ignore the `immutable` and `maxAge` options. + +##### dotfiles + + Set how "dotfiles" are treated when encountered. A dotfile is a file +or directory that begins with a dot ("."). Note this check is done on +the path itself without checking if the path actually exists on the +disk. If `root` is specified, only the dotfiles above the root are +checked (i.e. the root itself can be within a dotfile when set +to "deny"). + + - `'allow'` No special treatment for dotfiles. + - `'deny'` Deny a request for a dotfile and 403/`next()`. + - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`. + +The default value is similar to `'ignore'`, with the exception that this +default will not ignore the files within a directory that begins with a dot. + +##### etag + +Enable or disable etag generation, defaults to true. + +##### extensions + +Set file extension fallbacks. When set, if a file is not found, the given +extensions will be added to the file name and search for. The first that +exists will be served. Example: `['html', 'htm']`. + +The default value is `false`. + +##### fallthrough + +Set the middleware to have client errors fall-through as just unhandled +requests, otherwise forward a client error. The difference is that client +errors like a bad request or a request to a non-existent file will cause +this middleware to simply `next()` to your next middleware when this value +is `true`. When this value is `false`, these errors (even 404s), will invoke +`next(err)`. + +Typically `true` is desired such that multiple physical directories can be +mapped to the same web address or for routes to fill in non-existent files. + +The value `false` can be used if this middleware is mounted at a path that +is designed to be strictly a single file system directory, which allows for +short-circuiting 404s for less overhead. This middleware will also reply to +all methods. + +The default value is `true`. + +##### immutable + +Enable or disable the `immutable` directive in the `Cache-Control` response +header, defaults to `false`. If set to `true`, the `maxAge` option should +also be specified to enable caching. The `immutable` directive will prevent +supported clients from making conditional requests during the life of the +`maxAge` option to check if the file has changed. + +##### index + +By default this module will send "index.html" files in response to a request +on a directory. To disable this set `false` or to supply a new index pass a +string or an array in preferred order. + +##### lastModified + +Enable or disable `Last-Modified` header, defaults to true. Uses the file +system's last modified value. + +##### maxAge + +Provide a max-age in milliseconds for http caching, defaults to 0. This +can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme) +module. + +##### redirect + +Redirect to trailing "/" when the pathname is a dir. Defaults to `true`. + +##### setHeaders + +Function to set custom headers on response. Alterations to the headers need to +occur synchronously. The function is called as `fn(res, path, stat)`, where +the arguments are: + + - `res` the response object + - `path` the file path that is being sent + - `stat` the stat object of the file that is being sent + +## Examples + +### Serve files with vanilla node.js http server + +```js +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] }) + +// Create server +var server = http.createServer(function onRequest (req, res) { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serve all files as downloads + +```js +var contentDisposition = require('content-disposition') +var finalhandler = require('finalhandler') +var http = require('http') +var serveStatic = require('serve-static') + +// Serve up public/ftp folder +var serve = serveStatic('public/ftp', { + index: false, + setHeaders: setHeaders +}) + +// Set header to force download +function setHeaders (res, path) { + res.setHeader('Content-Disposition', contentDisposition(path)) +} + +// Create server +var server = http.createServer(function onRequest (req, res) { + serve(req, res, finalhandler(req, res)) +}) + +// Listen +server.listen(3000) +``` + +### Serving using express + +#### Simple + +This is a simple example of using Express. + +```js +var express = require('express') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] })) +app.listen(3000) +``` + +#### Multiple roots + +This example shows a simple way to search through multiple directories. +Files are searched for in `public-optimized/` first, then `public/` second +as a fallback. + +```js +var express = require('express') +var path = require('path') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(path.join(__dirname, 'public-optimized'))) +app.use(serveStatic(path.join(__dirname, 'public'))) +app.listen(3000) +``` + +#### Different settings for paths + +This example shows how to set a different max age depending on the served +file type. In this example, HTML files are not cached, while everything else +is for 1 day. + +```js +var express = require('express') +var path = require('path') +var serveStatic = require('serve-static') + +var app = express() + +app.use(serveStatic(path.join(__dirname, 'public'), { + maxAge: '1d', + setHeaders: setCustomCacheControl +})) + +app.listen(3000) + +function setCustomCacheControl (res, path) { + if (serveStatic.mime.lookup(path) === 'text/html') { + // Custom Cache-Control for HTML files + res.setHeader('Cache-Control', 'public, max-age=0') + } +} +``` + +## License + +[MIT](LICENSE) + +[appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/serve-static/master?label=windows +[appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-static +[coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/serve-static/master +[coveralls-url]: https://coveralls.io/r/expressjs/serve-static?branch=master +[github-actions-ci-image]: https://badgen.net/github/checks/expressjs/serve-static/master?label=linux +[github-actions-ci-url]: https://github.com/expressjs/serve-static/actions/workflows/ci.yml +[node-image]: https://badgen.net/npm/node/serve-static +[node-url]: https://nodejs.org/en/download/ +[npm-downloads-image]: https://badgen.net/npm/dm/serve-static +[npm-url]: https://npmjs.org/package/serve-static +[npm-version-image]: https://badgen.net/npm/v/serve-static diff --git a/node_modules/serve-static/index.js b/node_modules/serve-static/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3f3e64e9eaad83c4638b1a458ecfa6c49a6bebc1 --- /dev/null +++ b/node_modules/serve-static/index.js @@ -0,0 +1,209 @@ +/*! + * serve-static + * Copyright(c) 2010 Sencha Inc. + * Copyright(c) 2011 TJ Holowaychuk + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var encodeUrl = require('encodeurl') +var escapeHtml = require('escape-html') +var parseUrl = require('parseurl') +var resolve = require('path').resolve +var send = require('send') +var url = require('url') + +/** + * Module exports. + * @public + */ + +module.exports = serveStatic +module.exports.mime = send.mime + +/** + * @param {string} root + * @param {object} [options] + * @return {function} + * @public + */ + +function serveStatic (root, options) { + if (!root) { + throw new TypeError('root path required') + } + + if (typeof root !== 'string') { + throw new TypeError('root path must be a string') + } + + // copy options object + var opts = Object.create(options || null) + + // fall-though + var fallthrough = opts.fallthrough !== false + + // default redirect + var redirect = opts.redirect !== false + + // headers listener + var setHeaders = opts.setHeaders + + if (setHeaders && typeof setHeaders !== 'function') { + throw new TypeError('option setHeaders must be function') + } + + // setup options for send + opts.maxage = opts.maxage || opts.maxAge || 0 + opts.root = resolve(root) + + // construct directory listener + var onDirectory = redirect + ? createRedirectDirectoryListener() + : createNotFoundDirectoryListener() + + return function serveStatic (req, res, next) { + if (req.method !== 'GET' && req.method !== 'HEAD') { + if (fallthrough) { + return next() + } + + // method not allowed + res.statusCode = 405 + res.setHeader('Allow', 'GET, HEAD') + res.setHeader('Content-Length', '0') + res.end() + return + } + + var forwardError = !fallthrough + var originalUrl = parseUrl.original(req) + var path = parseUrl(req).pathname + + // make sure redirect occurs at mount + if (path === '/' && originalUrl.pathname.substr(-1) !== '/') { + path = '' + } + + // create send stream + var stream = send(req, path, opts) + + // add directory handler + stream.on('directory', onDirectory) + + // add headers listener + if (setHeaders) { + stream.on('headers', setHeaders) + } + + // add file listener for fallthrough + if (fallthrough) { + stream.on('file', function onFile () { + // once file is determined, always forward error + forwardError = true + }) + } + + // forward errors + stream.on('error', function error (err) { + if (forwardError || !(err.statusCode < 500)) { + next(err) + return + } + + next() + }) + + // pipe + stream.pipe(res) + } +} + +/** + * Collapse all leading slashes into a single slash + * @private + */ +function collapseLeadingSlashes (str) { + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) !== 0x2f /* / */) { + break + } + } + + return i > 1 + ? '/' + str.substr(i) + : str +} + +/** + * Create a minimal HTML document. + * + * @param {string} title + * @param {string} body + * @private + */ + +function createHtmlDocument (title, body) { + return '\n' + + '\n' + + '\n' + + '\n' + + '' + title + '\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} + +/** + * Create a directory listener that just 404s. + * @private + */ + +function createNotFoundDirectoryListener () { + return function notFound () { + this.error(404) + } +} + +/** + * Create a directory listener that performs a redirect. + * @private + */ + +function createRedirectDirectoryListener () { + return function redirect (res) { + if (this.hasTrailingSlash()) { + this.error(404) + return + } + + // get original URL + var originalUrl = parseUrl.original(this.req) + + // append trailing slash + originalUrl.path = null + originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + '/') + + // reformat the URL + var loc = encodeUrl(url.format(originalUrl)) + var doc = createHtmlDocument('Redirecting', 'Redirecting to ' + escapeHtml(loc)) + + // send redirect response + res.statusCode = 301 + res.setHeader('Content-Type', 'text/html; charset=UTF-8') + res.setHeader('Content-Length', Buffer.byteLength(doc)) + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') + res.setHeader('Location', loc) + res.end(doc) + } +} diff --git a/node_modules/serve-static/package.json b/node_modules/serve-static/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b268e48edb50f61dfe6af8abf1c8a8a4dc478e92 --- /dev/null +++ b/node_modules/serve-static/package.json @@ -0,0 +1,42 @@ +{ + "name": "serve-static", + "description": "Serve static files", + "version": "1.16.3", + "author": "Douglas Christopher Wilson ", + "license": "MIT", + "repository": "expressjs/serve-static", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "~0.19.1" + }, + "devDependencies": { + "eslint": "7.32.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.25.4", + "eslint-plugin-markdown": "2.2.1", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "5.2.0", + "eslint-plugin-standard": "4.1.0", + "mocha": "9.2.2", + "nyc": "15.1.0", + "safe-buffer": "5.2.1", + "supertest": "6.2.2" + }, + "files": [ + "LICENSE", + "HISTORY.md", + "index.js" + ], + "engines": { + "node": ">= 0.8.0" + }, + "scripts": { + "lint": "eslint .", + "test": "mocha --reporter spec --bail --check-leaks test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/set-blocking/CHANGELOG.md b/node_modules/set-blocking/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..03bf591923d78279cb887b3ea6a576e5cdc531bc --- /dev/null +++ b/node_modules/set-blocking/CHANGELOG.md @@ -0,0 +1,26 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +# [2.0.0](https://github.com/yargs/set-blocking/compare/v1.0.0...v2.0.0) (2016-05-17) + + +### Features + +* add an isTTY check ([#3](https://github.com/yargs/set-blocking/issues/3)) ([66ce277](https://github.com/yargs/set-blocking/commit/66ce277)) + + +### BREAKING CHANGES + +* stdio/stderr will not be set to blocking if isTTY === false + + + + +# 1.0.0 (2016-05-14) + + +### Features + +* implemented shim for stream._handle.setBlocking ([6bde0c0](https://github.com/yargs/set-blocking/commit/6bde0c0)) diff --git a/node_modules/set-blocking/LICENSE.txt b/node_modules/set-blocking/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..836440bef7cf14841c05b0f8635e580c91327fc4 --- /dev/null +++ b/node_modules/set-blocking/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/set-blocking/README.md b/node_modules/set-blocking/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e93b4202b59d65f5a5b67937fd18a3c45c479594 --- /dev/null +++ b/node_modules/set-blocking/README.md @@ -0,0 +1,31 @@ +# set-blocking + +[![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) +[![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) +[![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) + +set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. + +```js +const setBlocking = require('set-blocking') +setBlocking(true) +console.log(someLargeStringToOutput) +``` + +## Historical Context/Word of Warning + +This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on +newer versions of Node.js (`0.12+`), truncating terminal output. + +You should be mindful of the side-effects caused by using `set-blocking`: + +* if your module sets blocking to `true`, it will effect other modules + consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call + `setBlocking(true)` once we already know we are about to call `process.exit(code)`. +* this patch will not apply to subprocesses spawned with `isTTY = true`, this is + the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). + +## License + +ISC diff --git a/node_modules/set-blocking/index.js b/node_modules/set-blocking/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6f78774bb63ee6d0558e6726446a73b3ac7c7144 --- /dev/null +++ b/node_modules/set-blocking/index.js @@ -0,0 +1,7 @@ +module.exports = function (blocking) { + [process.stdout, process.stderr].forEach(function (stream) { + if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') { + stream._handle.setBlocking(blocking) + } + }) +} diff --git a/node_modules/set-blocking/package.json b/node_modules/set-blocking/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c082db72c6259d2cf17edc9de3fac401213c457f --- /dev/null +++ b/node_modules/set-blocking/package.json @@ -0,0 +1,42 @@ +{ + "name": "set-blocking", + "version": "2.0.0", + "description": "set blocking stdio and stderr ensuring that terminal output does not truncate", + "main": "index.js", + "scripts": { + "pretest": "standard", + "test": "nyc mocha ./test/*.js", + "coverage": "nyc report --reporter=text-lcov | coveralls", + "version": "standard-version" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/yargs/set-blocking.git" + }, + "keywords": [ + "flush", + "terminal", + "blocking", + "shim", + "stdio", + "stderr" + ], + "author": "Ben Coe ", + "license": "ISC", + "bugs": { + "url": "https://github.com/yargs/set-blocking/issues" + }, + "homepage": "https://github.com/yargs/set-blocking#readme", + "devDependencies": { + "chai": "^3.5.0", + "coveralls": "^2.11.9", + "mocha": "^2.4.5", + "nyc": "^6.4.4", + "standard": "^7.0.1", + "standard-version": "^2.2.1" + }, + "files": [ + "index.js", + "LICENSE.txt" + ] +} \ No newline at end of file diff --git a/node_modules/set-cookie-parser/LICENSE b/node_modules/set-cookie-parser/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..46f7017bb76f1f2844d7e95ecd725d682d5e9d05 --- /dev/null +++ b/node_modules/set-cookie-parser/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Nathan Friedly (http://nfriedly.com/) + +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. diff --git a/node_modules/set-cookie-parser/README.md b/node_modules/set-cookie-parser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d27729934b09848e45e8d3e8e670f833f7238ce1 --- /dev/null +++ b/node_modules/set-cookie-parser/README.md @@ -0,0 +1,169 @@ +# set-cookie-parser + +[![Node.js CI](https://github.com/nfriedly/set-cookie-parser/actions/workflows/node.js.yml/badge.svg)](https://github.com/nfriedly/set-cookie-parser/actions/workflows/node.js.yml) +[![NPM version][npm-image]][npm-url] +[![npm downloads](https://img.shields.io/npm/dm/set-cookie-parser)][npm-url] + +--- + +Parses set-cookie headers into JavaScript objects + +Accepts a single `set-cookie` header value, an array of `set-cookie` header values, a Node.js response object, or a `fetch()` `Response` object that may have 0 or more `set-cookie` headers. + +Returns either an array of cookie objects or a map of name => cookie object with options set `{map: true}`. Each cookie object will have, at a minimum `name` and `value` properties, and may have additional properties depending on the set-cookie header: + +* `name` - cookie name (string) +* `value` - cookie value (string) +* `path` - URL path to limit the scope to (string or undefined) +* `domain` - domain to expand the scope to (string or undefined, may begin with "." to indicate the named domain or any subdomain of it) +* `expires` - absolute expiration date for the cookie (Date object or undefined) +* `maxAge` - relative expiration time of the cookie in seconds from when the client receives it (integer or undefined) + * Note: when using with [express's res.cookie() method](http://expressjs.com/en/4x/api.html#res.cookie), multiply `maxAge` by 1000 to convert to milliseconds. +* `secure` - indicates cookie should only be sent over HTTPs (true or undefined) +* `httpOnly` - indicates cookie should *not* be accessible to client-side JavaScript (true or undefined) +* `sameSite` - indicates if cookie should be included in cross-site requests ([more info](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value)) (string or undefined) + * Note: valid values are `"Strict"`, `"Lax"`, and `"None"`, but set-cookie-parser copies the value verbatim and does *not* perform any validation. +* `partitioned` - indicates cookie should be scoped to the combination of 3rd party domain + top page domain ([more info](https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies)) (true or undefined) + +(The output format is loosely based on the input format of https://www.npmjs.com/package/cookie) + +## Install + +```sh +$ npm install --save set-cookie-parser +``` + + +## Usage + +### Get array of cookie objects + +```js +import * as http from 'node:http'; +import { parseSetCookie } from 'set-cookie-parser'; +// or const { parseSetCookie } = require('set-cookie-parser'); + +http.get('http://example.com', function(res) { + const cookies = parseSetCookie(res, { + decodeValues: true // default: true + }); + + cookies.forEach(console.log); +} +``` + +Example output: + +```js +[ + { + name: 'bam', + value: 'baz' + }, + { + name: 'foo', + value: 'bar', + path: '/', + expires: new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)'), + maxAge: 1000, + domain: '.example.com', + secure: true, + httpOnly: true, + sameSite: 'lax' + } +] +``` + +### Get map of cookie objects + +```js +import * as http from 'node:http'; +import { parseSetCookie } from 'set-cookie-parser'; +// or const { parseSetCookie } = require('set-cookie-parser'); + +http.get('http://example.com', function(res) { + const cookies = parseSetCookie(res, { + decodeValues: true, // default: true + map: true // default: false + }); + + const desiredCookie = cookies['session']; + console.log(desiredCookie); +}); +``` +Example output: +```js +{ + bam: { + name: 'bam', + value: 'baz' + }, + foo: { + name: 'foo', + value: 'bar', + path: '/', + expires: new Date('Tue Jul 01 2025 06:01:11 GMT-0400 (EDT)'), + maxAge: 1000, + domain: '.example.com', + secure: true, + httpOnly: true, + sameSite: 'lax' + } +} +``` + +### Creating a new, modified set-cookie header + +This library can be used in conjunction with the [cookie](https://www.npmjs.com/package/cookie) library to modify and replace set-cookie headers: + +```js +import * as libCookie from 'cookie'; +import { parseSetCookie } from 'set-cookie-parser'; +// or const { parseSetCookie } = require('set-cookie-parser'); + +function modifySetCookie(res){ + // parse the set-cookie headers with this library + const cookies = parseSetCookie(res); + + // modify the cookies here + // ... + + // create new set-cookie headers using the cookie library + res.headers['set-cookie'] = cookies.map(function(cookie) { + return libCookie.serialize(cookie.name, cookie.value, cookie); + }); +} +``` + +See a real-world example of this in [unblocker](https://github.com/nfriedly/node-unblocker/blob/08a89ec27274b46dcd80d0a324a59406f2bdad3d/lib/cookies.js#L67-L85) + +## API + +### parseSetCookie(input, [options]) + +Parses cookies from a string, array of strings, or a http response object. +Always returns an array, regardless of input format. (Unless the `map` option is set, in which case it always returns an object.) + +Also accepts an optional options object. Defaults: + +```js +{ + decodeValues: true, // Calls decodeURIComponent on each value - default: true + map: false, // Return an object instead of an array - default: false + silent: false, // Suppress the warning that is logged when called on a request instead of a response - default: false + split: 'auto', // Separate combined cookie headers. Valid options are true/false/'auto'. 'auto' splits strings but not arrays. +} +``` + +## References + +* [RFC 6265: HTTP State Management Mechanism](https://tools.ietf.org/html/rfc6265) +* [draft-ietf-httpbis-rfc6265bis-10](https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html) + +## License + +MIT © [Nathan Friedly](http://www.nfriedly.com/) + + +[npm-image]: https://badge.fury.io/js/set-cookie-parser.svg +[npm-url]: https://npmjs.org/package/set-cookie-parser diff --git a/node_modules/set-cookie-parser/lib/set-cookie.d.ts b/node_modules/set-cookie-parser/lib/set-cookie.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1342043038af1ade71b0a68c499d54334c9a7809 --- /dev/null +++ b/node_modules/set-cookie-parser/lib/set-cookie.d.ts @@ -0,0 +1,119 @@ +export interface Cookie { + /** Cookie name */ + name: string; + /** Cookie value */ + value: string; + /** Cookie path */ + path?: string; + /** Absolute expiration date for the cookie */ + expires?: Date; + /** + * Relative max age of the cookie in seconds from when the client receives it. + * Note: when using with express's res.cookie() method, multiply maxAge by 1000 to convert to milliseconds. + */ + maxAge?: number; + /** + * Domain for the cookie, + * may begin with "." to indicate the named domain or any subdomain of it + */ + domain?: string; + /** Indicates that this cookie should only be sent over HTTPS */ + secure?: boolean; + /** Indicates that this cookie should not be accessible to client-side JavaScript */ + httpOnly?: boolean; + /** Indicates a cookie ought not to be sent along with cross-site requests */ + sameSite?: string; + /** Indicates the cookie should be stored using partitioned storage */ + partitioned?: boolean; +} + +export interface CookieMap { + [name: string]: Cookie; +} + +export interface Options { + /** + * Calls decodeURIComponent on each value. + * @default true + */ + decodeValues?: boolean; + /** + * Return an object instead of an array. + * @default false + */ + map?: boolean; + /** + * Suppress the warning that is logged when called on a request instead of a response. + * @default false + */ + silent?: boolean; + /** + * Controls whether combined cookie strings are split. + * - `true`: always split + * - `false`: never split + * - `"auto"`: split strings but not arrays + * @default "auto" + */ + split?: boolean | "auto"; +} + +/** Object with a `headers` property (e.g. Node.js IncomingMessage or fetch Response) */ +type ResponseLike = { + headers: + | { getSetCookie(): string[] } + | { "set-cookie"?: string | readonly string[] } + | Record; +}; + +type SetCookieInput = string | readonly string[] | ResponseLike; + +/** + * Parses set-cookie headers into objects. + */ +export function parseSetCookie( + input: SetCookieInput, + options: Options & { map: true } +): CookieMap; +export function parseSetCookie( + input: SetCookieInput, + options?: Options & { map?: false } +): Cookie[]; +export function parseSetCookie( + input: SetCookieInput, + options?: Options +): Cookie[] | CookieMap; + +/** + * Parses a single set-cookie header value string. + * @deprecated Use `parseSetCookie` instead. + */ +export function parseString( + setCookieValue: string, + options?: Options +): Cookie | null; + +/** + * Splits a combined set-cookie header string into individual set-cookie header strings. + * @deprecated Use `parseSetCookie` with the `split` option instead. + */ +export function splitCookiesString( + input: string | readonly string[] | undefined +): string[]; + +/** + * @deprecated Renamed to `parseSetCookie`. Kept for backward compatibility. + */ +export { + parseSetCookie as parse, +}; + +/** + * Default export — the `parseSetCookie` function with additional properties for backward compatibility. + */ +declare const _default: typeof parseSetCookie & { + parseSetCookie: typeof parseSetCookie; + parse: typeof parseSetCookie; + parseString: typeof parseString; + splitCookiesString: typeof splitCookiesString; +}; +export default _default; diff --git a/node_modules/set-cookie-parser/lib/set-cookie.js b/node_modules/set-cookie-parser/lib/set-cookie.js new file mode 100644 index 0000000000000000000000000000000000000000..2c7b9b076cc3a109aabc221267bde3ba9062f77d --- /dev/null +++ b/node_modules/set-cookie-parser/lib/set-cookie.js @@ -0,0 +1,265 @@ +var defaultParseOptions = { + decodeValues: true, + map: false, + silent: false, + split: "auto", // auto = split strings but not arrays +}; + +function isForbiddenKey(key) { + return typeof key !== "string" || key in {}; +} + +function createNullObj() { + return Object.create(null); +} + +function isNonEmptyString(str) { + return typeof str === "string" && !!str.trim(); +} + +function parseString(setCookieValue, options) { + var parts = setCookieValue.split(";").filter(isNonEmptyString); + + var nameValuePairStr = parts.shift(); + var parsed = parseNameValuePair(nameValuePairStr); + var name = parsed.name; + var value = parsed.value; + + options = options + ? Object.assign({}, defaultParseOptions, options) + : defaultParseOptions; + + if (isForbiddenKey(name)) { + return null; + } + + try { + value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value + } catch (e) { + console.error( + "set-cookie-parser: failed to decode cookie value. Set options.decodeValues=false to disable decoding.", + e + ); + } + + var cookie = createNullObj(); + cookie.name = name; + cookie.value = value; + + parts.forEach(function (part) { + var sides = part.split("="); + var key = sides.shift().trimLeft().toLowerCase(); + if (isForbiddenKey(key)) { + return; + } + var value = sides.join("="); + if (key === "expires") { + cookie.expires = new Date(value); + } else if (key === "max-age") { + var n = parseInt(value, 10); + if (!Number.isNaN(n)) cookie.maxAge = n; + } else if (key === "secure") { + cookie.secure = true; + } else if (key === "httponly") { + cookie.httpOnly = true; + } else if (key === "samesite") { + cookie.sameSite = value; + } else if (key === "partitioned") { + cookie.partitioned = true; + } else if (key) { + cookie[key] = value; + } + }); + + return cookie; +} + +function parseNameValuePair(nameValuePairStr) { + // Parses name-value-pair according to rfc6265bis draft + + var name = ""; + var value = ""; + var nameValueArr = nameValuePairStr.split("="); + if (nameValueArr.length > 1) { + name = nameValueArr.shift(); + value = nameValueArr.join("="); // everything after the first =, joined by a "=" if there was more than one part + } else { + value = nameValuePairStr; + } + + return { name: name, value: value }; +} + +function parseSetCookie(input, options) { + options = options + ? Object.assign({}, defaultParseOptions, options) + : defaultParseOptions; + + if (!input) { + if (!options.map) { + return []; + } else { + return createNullObj(); + } + } + + if (input.headers) { + if (typeof input.headers.getSetCookie === "function") { + // for fetch responses - they combine headers of the same type in the headers array, + // but getSetCookie returns an uncombined array + input = input.headers.getSetCookie(); + } else if (input.headers["set-cookie"]) { + // fast-path for node.js (which automatically normalizes header names to lower-case) + input = input.headers["set-cookie"]; + } else { + // slow-path for other environments - see #25 + var sch = + input.headers[ + Object.keys(input.headers).find(function (key) { + return key.toLowerCase() === "set-cookie"; + }) + ]; + // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36 + if (!sch && input.headers.cookie && !options.silent) { + console.warn( + "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning." + ); + } + input = sch; + } + } + + var split = options.split; + var isArray = Array.isArray(input); + + if (split === "auto") { + split = !isArray; + } + + if (!isArray) { + input = [input]; + } + + input = input.filter(isNonEmptyString); + + if (split) { + input = input.map(splitCookiesString).flat(); + } + + if (!options.map) { + return input + .map(function (str) { + return parseString(str, options); + }) + .filter(Boolean); + } else { + var cookies = createNullObj(); + return input.reduce(function (cookies, str) { + var cookie = parseString(str, options); + if (cookie && !isForbiddenKey(cookie.name)) { + cookies[cookie.name] = cookie; + } + return cookies; + }, cookies); + } +} + +/* + Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas + that are within a single set-cookie field-value, such as in the Expires portion. + + This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2 + Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128 + React Native's fetch does this for *every* header, including set-cookie. + + Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25 + Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation +*/ +function splitCookiesString(cookiesString) { + if (Array.isArray(cookiesString)) { + return cookiesString; + } + if (typeof cookiesString !== "string") { + return []; + } + + var cookiesStrings = []; + var pos = 0; + var start; + var ch; + var lastComma; + var nextStart; + var cookiesSeparatorFound; + + function skipWhitespace() { + while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) { + pos += 1; + } + return pos < cookiesString.length; + } + + function notSpecialChar() { + ch = cookiesString.charAt(pos); + + return ch !== "=" && ch !== ";" && ch !== ","; + } + + while (pos < cookiesString.length) { + start = pos; + cookiesSeparatorFound = false; + + while (skipWhitespace()) { + ch = cookiesString.charAt(pos); + if (ch === ",") { + // ',' is a cookie separator if we have later first '=', not ';' or ',' + lastComma = pos; + pos += 1; + + skipWhitespace(); + nextStart = pos; + + while (pos < cookiesString.length && notSpecialChar()) { + pos += 1; + } + + // currently special character + if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") { + // we found cookies separator + cookiesSeparatorFound = true; + // pos is inside the next cookie, so back up and return it. + pos = nextStart; + cookiesStrings.push(cookiesString.substring(start, lastComma)); + start = pos; + } else { + // in param ',' or param separator ';', + // we continue from that comma + pos = lastComma + 1; + } + } else { + pos += 1; + } + } + + if (!cookiesSeparatorFound || pos >= cookiesString.length) { + cookiesStrings.push(cookiesString.substring(start, cookiesString.length)); + } + } + + return cookiesStrings; +} + +// named export for CJS +parseSetCookie.parseSetCookie = parseSetCookie; +// for backwards compatibility +parseSetCookie.parse = parseSetCookie; +parseSetCookie.parseString = parseString; +parseSetCookie.splitCookiesString = splitCookiesString; + +// EXPORTS +// (this section is replaced by build-cjs.js) + +// named export for ESM +export { parseSetCookie }; +// for backwards compatibility +export default parseSetCookie; +export { parseSetCookie as parse, parseString, splitCookiesString }; diff --git a/node_modules/set-cookie-parser/package.json b/node_modules/set-cookie-parser/package.json new file mode 100644 index 0000000000000000000000000000000000000000..096cb4f779a463fd8b9f6c466591a39214cb532a --- /dev/null +++ b/node_modules/set-cookie-parser/package.json @@ -0,0 +1,61 @@ +{ + "name": "set-cookie-parser", + "version": "3.1.0", + "description": "Parses set-cookie headers into objects", + "homepage": "https://github.com/nfriedly/set-cookie-parser", + "repository": "nfriedly/set-cookie-parser", + "author": { + "name": "Nathan Friedly", + "url": "http://nfriedly.com/" + }, + "files": [ + "lib", + "dist" + ], + "main": "./dist/set-cookie.cjs", + "module": "./lib/set-cookie.js", + "types": "./lib/set-cookie.d.ts", + "type": "module", + "exports": { + ".": { + "types": "./lib/set-cookie.d.ts", + "module-sync": "./lib/set-cookie.js", + "import": "./lib/set-cookie.js", + "require": "./dist/set-cookie.cjs" + } + }, + "sideEffects": false, + "keywords": [ + "set-cookie", + "set", + "cookie", + "cookies", + "header", + "parse", + "parser" + ], + "devDependencies": { + "eslint": "^8.57.0", + "eslint-config-prettier": "^9.1.0", + "eslint-plugin-prettier": "^5.1.3", + "husky": "^9.1.7", + "mocha": "^11.7.5", + "prettier": "^3.2.5", + "pretty-quick": "^4.0.0", + "sinon": "^21.0.3", + "tsd": "^0.33.0" + }, + "scripts": { + "lint": "eslint . --ignore-pattern '!.eslintrc.js'", + "test": "npm run build && npm run lint && mocha && npm run typecheck", + "typecheck": "tsd", + "autofix": "npm run lint -- --fix", + "format": "npm run lint -- --fix", + "build": "node ./build-cjs.js", + "prepare": "husky" + }, + "license": "MIT", + "prettier": { + "trailingComma": "es5" + } +} diff --git a/node_modules/set-function-length/.eslintrc b/node_modules/set-function-length/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..7cff50717edb2b4867273c28e147ec570bfa8f89 --- /dev/null +++ b/node_modules/set-function-length/.eslintrc @@ -0,0 +1,27 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "GetIntrinsic" + ], + }], + "no-extra-parens": "off", + }, + + "overrides": [ + { + "files": ["test/**/*.js"], + "rules": { + "id-length": "off", + "max-lines-per-function": "off", + "multiline-comment-style": "off", + "no-empty-function": "off", + }, + }, + ], +} diff --git a/node_modules/set-function-length/.github/FUNDING.yml b/node_modules/set-function-length/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..92feb6f9bc4063b604bf3a2790852792a03902fb --- /dev/null +++ b/node_modules/set-function-length/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/set-function-name +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/set-function-length/.nycrc b/node_modules/set-function-length/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/node_modules/set-function-length/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/set-function-length/CHANGELOG.md b/node_modules/set-function-length/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..bac439d8783a8963dd44fd5ad74384a46ef14dc1 --- /dev/null +++ b/node_modules/set-function-length/CHANGELOG.md @@ -0,0 +1,70 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.2](https://github.com/ljharb/set-function-length/compare/v1.2.1...v1.2.2) - 2024-03-09 + +### Commits + +- [types] use shared config [`027032f`](https://github.com/ljharb/set-function-length/commit/027032fe9cc439644a07248ea6a8d813fcc767cb) +- [actions] remove redundant finisher; use reusable workflow [`1fd4fb1`](https://github.com/ljharb/set-function-length/commit/1fd4fb1c58bd5170f0dcff7e320077c0aa2ffdeb) +- [types] use a handwritten d.ts file instead of emit [`01b9761`](https://github.com/ljharb/set-function-length/commit/01b9761742c95e1118e8c2d153ce2ae43d9731aa) +- [Deps] update `define-data-property`, `get-intrinsic`, `has-property-descriptors` [`bee8eaf`](https://github.com/ljharb/set-function-length/commit/bee8eaf7749f325357ade85cffeaeef679e513d4) +- [Dev Deps] update `call-bind`, `tape` [`5dae579`](https://github.com/ljharb/set-function-length/commit/5dae579fdc3aab91b14ebb58f9c19ee3f509d434) +- [Tests] use `@arethetypeswrong/cli` [`7e22425`](https://github.com/ljharb/set-function-length/commit/7e22425d15957fd3d6da0b6bca4afc0c8d255d2d) + +## [v1.2.1](https://github.com/ljharb/set-function-length/compare/v1.2.0...v1.2.1) - 2024-02-06 + +### Commits + +- [Dev Deps] update `call-bind`, `tape`, `typescript` [`d9a4601`](https://github.com/ljharb/set-function-length/commit/d9a460199c4c1fa37da9ebe055e2c884128f0738) +- [Deps] update `define-data-property`, `get-intrinsic` [`38d39ae`](https://github.com/ljharb/set-function-length/commit/38d39aed13a757ed36211d5b0437b88485090c6b) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`b4bfe5a`](https://github.com/ljharb/set-function-length/commit/b4bfe5ae0953b906d55b85f867eca5e7f673ebf4) + +## [v1.2.0](https://github.com/ljharb/set-function-length/compare/v1.1.1...v1.2.0) - 2024-01-14 + +### Commits + +- [New] add types [`f6d9088`](https://github.com/ljharb/set-function-length/commit/f6d9088b9283a3112b21c6776e8bef6d1f30558a) +- [Fix] ensure `env` properties are always booleans [`0c42f84`](https://github.com/ljharb/set-function-length/commit/0c42f84979086389b3229e1b4272697fd352275a) +- [Dev Deps] update `aud`, `call-bind`, `npmignore`, `tape` [`2b75f75`](https://github.com/ljharb/set-function-length/commit/2b75f75468093a4bb8ce8ca989b2edd2e80d95d1) +- [Deps] update `get-intrinsic`, `has-property-descriptors` [`19bf0fc`](https://github.com/ljharb/set-function-length/commit/19bf0fc4ffaa5ad425acbfa150516be9f3b6263a) +- [meta] add `sideEffects` flag [`8bb9b78`](https://github.com/ljharb/set-function-length/commit/8bb9b78c11c621123f725c9470222f43466c01d0) + +## [v1.1.1](https://github.com/ljharb/set-function-length/compare/v1.1.0...v1.1.1) - 2023-10-19 + +### Fixed + +- [Fix] move `define-data-property` to runtime deps [`#2`](https://github.com/ljharb/set-function-length/issues/2) + +### Commits + +- [Dev Deps] update `object-inspect`; add missing `call-bind` [`5aecf79`](https://github.com/ljharb/set-function-length/commit/5aecf79e7d6400957a5d9bd9ac20d4528908ca18) + +## [v1.1.0](https://github.com/ljharb/set-function-length/compare/v1.0.1...v1.1.0) - 2023-10-13 + +### Commits + +- [New] add `env` entry point [`475c87a`](https://github.com/ljharb/set-function-length/commit/475c87aa2f59b700aaed589d980624ec596acdcb) +- [Tests] add coverage with `nyc` [`14f0bf8`](https://github.com/ljharb/set-function-length/commit/14f0bf8c145ae60bf14a026420a06bb7be132c36) +- [eslint] fix linting failure [`fb516f9`](https://github.com/ljharb/set-function-length/commit/fb516f93c664057138c53559ef63c8622a093335) +- [Deps] update `define-data-property` [`d727e7c`](https://github.com/ljharb/set-function-length/commit/d727e7c6c9a40d7bf26797694e500ea68741feea) + +## [v1.0.1](https://github.com/ljharb/set-function-length/compare/v1.0.0...v1.0.1) - 2023-10-12 + +### Commits + +- [Refactor] use `get-intrinsic`, since it‘s in the dep graph anyways [`278a954`](https://github.com/ljharb/set-function-length/commit/278a954a06cd849051c569ff7aee56df6798933e) +- [meta] add `exports` [`72acfe5`](https://github.com/ljharb/set-function-length/commit/72acfe5a0310071fb205a72caba5ecbab24336a0) + +## v1.0.0 - 2023-10-12 + +### Commits + +- Initial implementation, tests, readme [`fce14e1`](https://github.com/ljharb/set-function-length/commit/fce14e17586460e4f294405173be72b6ffdf7e5f) +- Initial commit [`ca7ba85`](https://github.com/ljharb/set-function-length/commit/ca7ba857c7c283f9d26e21f14e71cd388f2cb722) +- npm init [`6a7e493`](https://github.com/ljharb/set-function-length/commit/6a7e493927736cebcaf5c1a84e69b8e6b7b744d8) +- Only apps should have lockfiles [`d2bf6c4`](https://github.com/ljharb/set-function-length/commit/d2bf6c43de8a51b02a0aa53e8d62cb50c4a2b0da) diff --git a/node_modules/set-function-length/LICENSE b/node_modules/set-function-length/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0314929078de8a733a0af9c8ba5bc00aca094cc9 --- /dev/null +++ b/node_modules/set-function-length/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and contributors + +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. diff --git a/node_modules/set-function-length/README.md b/node_modules/set-function-length/README.md new file mode 100644 index 0000000000000000000000000000000000000000..15e3ac4b1ef6ada3bc5929bf990119bc079a9be3 --- /dev/null +++ b/node_modules/set-function-length/README.md @@ -0,0 +1,56 @@ +# set-function-length [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Set a function’s length. + +Arguments: + - `fn`: the function + - `length`: the new length. Must be an integer between 0 and 2**32. + - `loose`: Optional. If true, and the length fails to be set, do not throw. Default false. + +Returns `fn`. + +## Usage + +```javascript +var setFunctionLength = require('set-function-length'); +var assert = require('assert'); + +function zero() {} +function one(_) {} +function two(_, __) {} + +assert.equal(zero.length, 0); +assert.equal(one.length, 1); +assert.equal(two.length, 2); + +assert.equal(setFunctionLength(zero, 10), zero); +assert.equal(setFunctionLength(one, 11), one); +assert.equal(setFunctionLength(two, 12), two); + +assert.equal(zero.length, 10); +assert.equal(one.length, 11); +assert.equal(two.length, 12); +``` + +[package-url]: https://npmjs.org/package/set-function-length +[npm-version-svg]: https://versionbadg.es/ljharb/set-function-length.svg +[deps-svg]: https://david-dm.org/ljharb/set-function-length.svg +[deps-url]: https://david-dm.org/ljharb/set-function-length +[dev-deps-svg]: https://david-dm.org/ljharb/set-function-length/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/set-function-length#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/set-function-length.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/set-function-length.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/set-function-length.svg +[downloads-url]: https://npm-stat.com/charts.html?package=set-function-length +[codecov-image]: https://codecov.io/gh/ljharb/set-function-length/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/set-function-length/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/set-function-length +[actions-url]: https://github.com/ljharb/set-function-length/actions diff --git a/node_modules/set-function-length/env.d.ts b/node_modules/set-function-length/env.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..970ea535b697b0caeebf85847060a90883a852df --- /dev/null +++ b/node_modules/set-function-length/env.d.ts @@ -0,0 +1,9 @@ +declare const env: { + __proto__: null, + boundFnsHaveConfigurableLengths: boolean; + boundFnsHaveWritableLengths: boolean; + functionsHaveConfigurableLengths: boolean; + functionsHaveWritableLengths: boolean; +}; + +export = env; \ No newline at end of file diff --git a/node_modules/set-function-length/env.js b/node_modules/set-function-length/env.js new file mode 100644 index 0000000000000000000000000000000000000000..d9b0a2997b5998902ac7963f847964987c3cd6b5 --- /dev/null +++ b/node_modules/set-function-length/env.js @@ -0,0 +1,25 @@ +'use strict'; + +var gOPD = require('gopd'); +var bind = require('function-bind'); + +var unbound = gOPD && gOPD(function () {}, 'length'); +// @ts-expect-error ts(2555) TS is overly strict with .call +var bound = gOPD && gOPD(bind.call(function () {}), 'length'); + +var functionsHaveConfigurableLengths = !!(unbound && unbound.configurable); + +var functionsHaveWritableLengths = !!(unbound && unbound.writable); + +var boundFnsHaveConfigurableLengths = !!(bound && bound.configurable); + +var boundFnsHaveWritableLengths = !!(bound && bound.writable); + +/** @type {import('./env')} */ +module.exports = { + __proto__: null, + boundFnsHaveConfigurableLengths: boundFnsHaveConfigurableLengths, + boundFnsHaveWritableLengths: boundFnsHaveWritableLengths, + functionsHaveConfigurableLengths: functionsHaveConfigurableLengths, + functionsHaveWritableLengths: functionsHaveWritableLengths +}; diff --git a/node_modules/set-function-length/index.d.ts b/node_modules/set-function-length/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0451ecd391adfac03186df30945ad1c537b3654c --- /dev/null +++ b/node_modules/set-function-length/index.d.ts @@ -0,0 +1,7 @@ +declare namespace setFunctionLength { + type Func = (...args: unknown[]) => unknown; +} + +declare function setFunctionLength(fn: T, length: number, loose?: boolean): T; + +export = setFunctionLength; \ No newline at end of file diff --git a/node_modules/set-function-length/index.js b/node_modules/set-function-length/index.js new file mode 100644 index 0000000000000000000000000000000000000000..14ce74dae4ca6a2e7a03826b82c81b09e442573b --- /dev/null +++ b/node_modules/set-function-length/index.js @@ -0,0 +1,42 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var define = require('define-data-property'); +var hasDescriptors = require('has-property-descriptors')(); +var gOPD = require('gopd'); + +var $TypeError = require('es-errors/type'); +var $floor = GetIntrinsic('%Math.floor%'); + +/** @type {import('.')} */ +module.exports = function setFunctionLength(fn, length) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + if (typeof length !== 'number' || length < 0 || length > 0xFFFFFFFF || $floor(length) !== length) { + throw new $TypeError('`length` must be a positive 32-bit integer'); + } + + var loose = arguments.length > 2 && !!arguments[2]; + + var functionLengthIsConfigurable = true; + var functionLengthIsWritable = true; + if ('length' in fn && gOPD) { + var desc = gOPD(fn, 'length'); + if (desc && !desc.configurable) { + functionLengthIsConfigurable = false; + } + if (desc && !desc.writable) { + functionLengthIsWritable = false; + } + } + + if (functionLengthIsConfigurable || functionLengthIsWritable || !loose) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'length', length, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'length', length); + } + } + return fn; +}; diff --git a/node_modules/set-function-length/package.json b/node_modules/set-function-length/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f6b88819a6b7375386b3423e6438ebf535354101 --- /dev/null +++ b/node_modules/set-function-length/package.json @@ -0,0 +1,102 @@ +{ + "name": "set-function-length", + "version": "1.2.2", + "description": "Set a function's length property", + "main": "index.js", + "exports": { + ".": "./index.js", + "./env": "./env.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "directories": { + "test": "test" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/set-function-length.git" + }, + "keywords": [ + "javascript", + "ecmascript", + "set", + "function", + "length", + "function.length" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/set-function-length/issues" + }, + "homepage": "https://github.com/ljharb/set-function-length#readme", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.15.1", + "@ljharb/eslint-config": "^21.1.0", + "@ljharb/tsconfig": "^0.1.1", + "@types/call-bind": "^1.0.5", + "@types/define-properties": "^1.1.5", + "@types/es-value-fixtures": "^1.4.4", + "@types/for-each": "^0.3.3", + "@types/function-bind": "^1.1.10", + "@types/gopd": "^1.0.3", + "@types/has-property-descriptors": "^1.0.3", + "@types/object-inspect": "^1.8.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "call-bind": "^1.0.7", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/node_modules/set-function-length/tsconfig.json b/node_modules/set-function-length/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d9a6668c3ae6be748c78fbd5694053706b3d6942 --- /dev/null +++ b/node_modules/set-function-length/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/set-function-name/.eslintrc b/node_modules/set-function-name/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..ceed91844e5d0e7d38d51b055707cd3f134ef0e7 --- /dev/null +++ b/node_modules/set-function-name/.eslintrc @@ -0,0 +1,21 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "no-extra-parens": "off", + }, + + "overrides": [ + { + "files": ["test/**/*.js"], + "rules": { + "id-length": "off", + "multiline-comment-style": "off", + "no-empty-function": "off", + }, + }, + ], +} diff --git a/node_modules/set-function-name/.github/FUNDING.yml b/node_modules/set-function-name/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..92feb6f9bc4063b604bf3a2790852792a03902fb --- /dev/null +++ b/node_modules/set-function-name/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/set-function-name +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/set-function-name/CHANGELOG.md b/node_modules/set-function-name/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..d3719c3b05a1e70e82332ecc1e23b11a3372b3a3 --- /dev/null +++ b/node_modules/set-function-name/CHANGELOG.md @@ -0,0 +1,48 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.0.2](https://github.com/jfsiii/set-function-name/compare/v2.0.1...v2.0.2) - 2024-02-19 + +### Commits + +- [meta] add types [`ae747cd`](https://github.com/jfsiii/set-function-name/commit/ae747cdcf4a986e6974a375be8ec04dd7565f0bd) +- [Dev Deps] update `aud`, `npmignore`, `object-inspect`, `tape` [`01aafcb`](https://github.com/jfsiii/set-function-name/commit/01aafcb82e4df653fcbd666ce4f256c06f70d94e) +- [Deps] update `define-data-property`, `has-property-descriptors` [`0ef6338`](https://github.com/jfsiii/set-function-name/commit/0ef6338fac84f63c2445855778bfd9271ae048cb) +- [Refactor] use `es-errors` [`0b23e87`](https://github.com/jfsiii/set-function-name/commit/0b23e878a16c959bd8b1aa7152d65818dd90578c) + +## [v2.0.1](https://github.com/jfsiii/set-function-name/compare/v2.0.0...v2.0.1) - 2023-09-13 + +### Commits + +- [Fix] move `functions-have-names` to runtime deps [`db2eda8`](https://github.com/jfsiii/set-function-name/commit/db2eda8da4c8aecfad01739000bbd63d04a8e8cf) + +## [v2.0.0](https://github.com/jfsiii/set-function-name/compare/v1.0.0...v2.0.0) - 2023-09-12 + +### Commits + +- [eslint] add `npm run lint` [`23e1fcd`](https://github.com/jfsiii/set-function-name/commit/23e1fcd85b64b864cb8f7e894da78d540e72923a) +- [actions] add reused GHA [`525127e`](https://github.com/jfsiii/set-function-name/commit/525127e08bdb35b0d44f565492456c7d1d5923fc) +- [meta] add `.gitignore` [`aa3abdf`](https://github.com/jfsiii/set-function-name/commit/aa3abdfa6af18adf70281352905dd69ef8b2c66f) +- [Tests] switch tests to use tape; add posttest [`8ad6d30`](https://github.com/jfsiii/set-function-name/commit/8ad6d30c61f78d2f9beec156ba7f1c4c3741c593) +- [readme] add readme [`732c46c`](https://github.com/jfsiii/set-function-name/commit/732c46c05e0fa6843dbc85b3af1e9c9bf22e7bf9) +- [New] add optional `loose` argument [`f5e4771`](https://github.com/jfsiii/set-function-name/commit/f5e4771266c95567d87f6dc2cff94c986bc7e074) +- [meta] relicense package to MIT; fix repo URLs [`13948f8`](https://github.com/jfsiii/set-function-name/commit/13948f8bb4ec8a25b67332d8de232ad0c0dc4e6d) +- [meta] add `auto-changelog` [`7ab201c`](https://github.com/jfsiii/set-function-name/commit/7ab201c0d83d464664cc4588acad0d0f75926679) +- [Breaking] throw if a non-function is provided [`cf6fc8f`](https://github.com/jfsiii/set-function-name/commit/cf6fc8f3396d58aa8c32a83375cbf57d933d7e79) +- [Breaking] drop UMD, just use CJS [`47abfe8`](https://github.com/jfsiii/set-function-name/commit/47abfe89abfaa72f71e0a77a52a5ff2b7377e11a) +- [Refactor] use `define-data-property` and `has-property-descriptors` [`9921c2b`](https://github.com/jfsiii/set-function-name/commit/9921c2b64c571255084aefaa02660314609e8ea0) +- [meta] use `npmignore` to autogenerate an npmignore file [`c5dbe4f`](https://github.com/jfsiii/set-function-name/commit/c5dbe4f4c44298596338432e2ac9946a10c98edd) +- Only apps should have lockfiles [`98bbfa1`](https://github.com/jfsiii/set-function-name/commit/98bbfa145387f318152a6b792bd69aca3c544813) +- [meta] add `safe-publish-latest` [`8916cd8`](https://github.com/jfsiii/set-function-name/commit/8916cd8f5549dceee31f06d35a76e2f9d4933a8b) +- [meta] add `engines` [`2427c8e`](https://github.com/jfsiii/set-function-name/commit/2427c8e2499f378c9ff3d92c7d544c771ca810df) + +## v1.0.0 - 2017-09-14 + +### Commits + +- Initial commit. Including tests. [`f26a1f2`](https://github.com/jfsiii/set-function-name/commit/f26a1f2c69a70dad5049b1daa08eae5f6acd9a1e) +- add .npmignore to ignore test directory [`9cac96f`](https://github.com/jfsiii/set-function-name/commit/9cac96fd9e98f25883be6e727ac32356522a5d69) diff --git a/node_modules/set-function-name/LICENSE b/node_modules/set-function-name/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0314929078de8a733a0af9c8ba5bc00aca094cc9 --- /dev/null +++ b/node_modules/set-function-name/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and contributors + +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. diff --git a/node_modules/set-function-name/README.md b/node_modules/set-function-name/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b1612dd353e1d251451c71ae6a232a139fc7a3fd --- /dev/null +++ b/node_modules/set-function-name/README.md @@ -0,0 +1,61 @@ +# set-function-name [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Set a function’s name. + +Arguments: + - `fn`: the function + - `name`: the new name + - `loose`: Optional. If true, and the name fails to be set, do not throw. Default false. + +Returns `fn`. + +## Usage + +```javascript +var setFunctionName = require('set-function-name'); +var assert = require('assert'); + +const obj = { + concise() {}, + arrow: () => {}, + named: function named() {}, + anon: function () {}, +}; +assert.equal(obj.concise.name, 'concise'); +assert.equal(obj.arrow.name, 'arrow'); +assert.equal(obj.named.name, 'named'); +assert.equal(obj.anon.name, 'anon'); + +assert.equal(setFunctionName(obj.concise, 'brief'), obj.concise); +assert.equal(setFunctionName(obj.arrow, 'pointy'), obj.arrow); +assert.equal(setFunctionName(obj.named, ''), obj.named); +assert.equal(setFunctionName(obj.anon, 'anonymous'), obj.anon); + +assert.equal(obj.concise.name, 'brief'); +assert.equal(obj.arrow.name, 'pointy'); +assert.equal(obj.named.name, ''); +assert.equal(obj.anon.name, 'anonymous'); +``` + +[package-url]: https://npmjs.org/package/set-function-name +[npm-version-svg]: https://versionbadg.es/ljharb/set-function-name.svg +[deps-svg]: https://david-dm.org/ljharb/set-function-name.svg +[deps-url]: https://david-dm.org/ljharb/set-function-name +[dev-deps-svg]: https://david-dm.org/ljharb/set-function-name/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/set-function-name#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/set-function-name.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/set-function-name.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/set-function-name.svg +[downloads-url]: https://npm-stat.com/charts.html?package=set-function-name +[codecov-image]: https://codecov.io/gh/ljharb/set-function-name/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/set-function-name/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/set-function-name +[actions-url]: https://github.com/ljharb/set-function-name/actions diff --git a/node_modules/set-function-name/index.d.ts b/node_modules/set-function-name/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3f6114a23af84be9944f18cdd40b8625eb0492e --- /dev/null +++ b/node_modules/set-function-name/index.d.ts @@ -0,0 +1,5 @@ +type Func = (...args: unknown[]) => unknown; + +declare function setFunctionName(fn: T, name: string, loose?: boolean): T; + +export = setFunctionName; \ No newline at end of file diff --git a/node_modules/set-function-name/index.js b/node_modules/set-function-name/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8c1823875bc4a7c0c2f4579c6be3a4d6a8ba8613 --- /dev/null +++ b/node_modules/set-function-name/index.js @@ -0,0 +1,23 @@ +'use strict'; + +var define = require('define-data-property'); +var hasDescriptors = require('has-property-descriptors')(); +var functionsHaveConfigurableNames = require('functions-have-names').functionsHaveConfigurableNames(); + +var $TypeError = require('es-errors/type'); + +/** @type {import('.')} */ +module.exports = function setFunctionName(fn, name) { + if (typeof fn !== 'function') { + throw new $TypeError('`fn` is not a function'); + } + var loose = arguments.length > 2 && !!arguments[2]; + if (!loose || functionsHaveConfigurableNames) { + if (hasDescriptors) { + define(/** @type {Parameters[0]} */ (fn), 'name', name, true, true); + } else { + define(/** @type {Parameters[0]} */ (fn), 'name', name); + } + } + return fn; +}; diff --git a/node_modules/set-function-name/package.json b/node_modules/set-function-name/package.json new file mode 100644 index 0000000000000000000000000000000000000000..df47de0af22dff3cbbefbf3c515a5ea90a83b747 --- /dev/null +++ b/node_modules/set-function-name/package.json @@ -0,0 +1,99 @@ +{ + "name": "set-function-name", + "version": "2.0.2", + "description": "Set a function's name property", + "main": "index.js", + "types": "./index.d.ts", + "directories": { + "test": "test" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p .", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "aud --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/set-function-name.git" + }, + "keywords": [ + "set", + "assign", + "function", + "name", + "function.name" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/set-function-name/issues" + }, + "homepage": "https://github.com/ljharb/set-function-name#readme", + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/call-bind": "^1.0.5", + "@types/define-properties": "^1.1.5", + "@types/es-value-fixtures": "^1.4.4", + "@types/for-each": "^0.3.3", + "@types/function.prototype.name": "^1.1.3", + "@types/functions-have-names": "^1.2.2", + "@types/has-property-descriptors": "^1.0.3", + "@types/make-arrow-function": "^1.2.2", + "@types/make-async-function": "^1.0.2", + "@types/make-async-generator-function": "^1.0.3", + "@types/make-generator-function": "^2.0.3", + "@types/object-inspect": "^1.8.4", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "es-value-fixtures": "^1.4.2", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "function.prototype.name": "^1.1.6", + "in-publish": "^2.0.1", + "make-arrow-function": "^1.2.0", + "make-async-function": "^1.0.0", + "make-async-generator-function": "^1.0.0", + "make-generator-function": "^2.0.0", + "npmignore": "^0.3.1", + "object-inspect": "^1.13.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5", + "typescript": "next" + }, + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test", + "!*.d.ts", + "!*.d.ts.map" + ] + } +} diff --git a/node_modules/set-function-name/tsconfig.json b/node_modules/set-function-name/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..6d5dc00f23f3ea969710c9871621042b2bbb1cce --- /dev/null +++ b/node_modules/set-function-name/tsconfig.json @@ -0,0 +1,59 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "es2022", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ + "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ + "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ + "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ + "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ + "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ + "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ + "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ + "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ + // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ + + /* Completeness */ + // "skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage" + ] +} diff --git a/node_modules/set-proto/.eslintrc b/node_modules/set-proto/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..1d21a8aefa405581c2fe7e1a1e28bde05a45f1cc --- /dev/null +++ b/node_modules/set-proto/.eslintrc @@ -0,0 +1,10 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "sort-keys": "off", + }, +} diff --git a/node_modules/set-proto/.github/FUNDING.yml b/node_modules/set-proto/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..71e5d8b13cb03c76859578826daaae0c3c1a91a9 --- /dev/null +++ b/node_modules/set-proto/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/set-proto +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/set-proto/.nycrc b/node_modules/set-proto/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/set-proto/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/set-proto/CHANGELOG.md b/node_modules/set-proto/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..7ffdd41920b2783a9d7c845ea601da9eb6c00ee1 --- /dev/null +++ b/node_modules/set-proto/CHANGELOG.md @@ -0,0 +1,15 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## v1.0.0 - 2024-12-30 + +### Commits + +- Initial implementation, tests, readme, types [`7036fc9`](https://github.com/ljharb/set-proto/commit/7036fc9128568b1ff0b75d1955f7f364a4394079) +- Initial commit [`dd9bedd`](https://github.com/ljharb/set-proto/commit/dd9bedd41db6ff3efa00c84fcac8ae34558bf6ee) +- npm init [`63915de`](https://github.com/ljharb/set-proto/commit/63915dee39422698275fabe9876eb141e04390dd) +- Only apps should have lockfiles [`deffdae`](https://github.com/ljharb/set-proto/commit/deffdae5b989a9305247a4db314222ecc0a99280) diff --git a/node_modules/set-proto/LICENSE b/node_modules/set-proto/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f82f38963b0d282b529f64def2bcd40be3a9a947 --- /dev/null +++ b/node_modules/set-proto/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +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. diff --git a/node_modules/set-proto/Object.setPrototypeOf.d.ts b/node_modules/set-proto/Object.setPrototypeOf.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cbef07051494d0f9ea9ea503d0daee3bca27bd68 --- /dev/null +++ b/node_modules/set-proto/Object.setPrototypeOf.d.ts @@ -0,0 +1,8 @@ +declare function setProto( + object: O, + proto: P, +): O; + +declare const x: typeof setProto | null; + +export = x; \ No newline at end of file diff --git a/node_modules/set-proto/Object.setPrototypeOf.js b/node_modules/set-proto/Object.setPrototypeOf.js new file mode 100644 index 0000000000000000000000000000000000000000..dc213eb0914b459a5daa621b3d20f261cbb1e79f --- /dev/null +++ b/node_modules/set-proto/Object.setPrototypeOf.js @@ -0,0 +1,6 @@ +'use strict'; + +var $Object = require('es-object-atoms'); + +/** @type {import('./Object.setPrototypeOf')} */ +module.exports = $Object.setPrototypeOf || null; diff --git a/node_modules/set-proto/README.md b/node_modules/set-proto/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7e304179a6f77619441a9e22c17c8603724da59b --- /dev/null +++ b/node_modules/set-proto/README.md @@ -0,0 +1,52 @@ +# set-proto [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Robustly set the [[Prototype]] of an object. Uses the best available method. + +## Getting started + +```sh +npm install --save set-proto +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const setProto = require('set-proto'); + +const a = { a: 1, b: 2, [Symbol.toStringTag]: 'foo' }; +const b = { c: 3 }; + +assert.ok(!('c' in a)); + +setProto(a, b); + +assert.ok('c' in a); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/set-proto +[npm-version-svg]: https://versionbadg.es/ljharb/set-proto.svg +[deps-svg]: https://david-dm.org/ljharb/set-proto.svg +[deps-url]: https://david-dm.org/ljharb/set-proto +[dev-deps-svg]: https://david-dm.org/ljharb/set-proto/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/set-proto#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/set-proto.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/set-proto.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/set-proto.svg +[downloads-url]: https://npm-stat.com/charts.html?package=set-proto +[codecov-image]: https://codecov.io/gh/ljharb/set-proto/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/set-proto/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/set-proto +[actions-url]: https://github.com/ljharb/set-proto/actions diff --git a/node_modules/set-proto/Reflect.setPrototypeOf.d.ts b/node_modules/set-proto/Reflect.setPrototypeOf.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb156a4df8fac87c3a83e706b5c743352141abe2 --- /dev/null +++ b/node_modules/set-proto/Reflect.setPrototypeOf.d.ts @@ -0,0 +1,3 @@ +declare const x: typeof Reflect.setPrototypeOf | null; + +export = x; \ No newline at end of file diff --git a/node_modules/set-proto/Reflect.setPrototypeOf.js b/node_modules/set-proto/Reflect.setPrototypeOf.js new file mode 100644 index 0000000000000000000000000000000000000000..ccb7fd0599f2067901290d1cb155565d4d3c21ec --- /dev/null +++ b/node_modules/set-proto/Reflect.setPrototypeOf.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./Reflect.setPrototypeOf')} */ +module.exports = (typeof Reflect !== 'undefined' && Reflect.setPrototypeOf) || null; diff --git a/node_modules/set-proto/index.d.ts b/node_modules/set-proto/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0cadad92323bde95bb0c645c2322b30ca3d692d2 --- /dev/null +++ b/node_modules/set-proto/index.d.ts @@ -0,0 +1,8 @@ +declare function setProto( + object: O, + proto: P, +): O; + +declare const x: typeof setProto | null; + +export = x; diff --git a/node_modules/set-proto/index.js b/node_modules/set-proto/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d5df1bf2d5358318fe475f4877c18f0506b6aad9 --- /dev/null +++ b/node_modules/set-proto/index.js @@ -0,0 +1,25 @@ +'use strict'; + +var reflectSetProto = require('./Reflect.setPrototypeOf'); +var originalSetProto = require('./Object.setPrototypeOf'); + +var setDunderProto = require('dunder-proto/set'); + +var $TypeError = require('es-errors/type'); + +/** @type {import('.')} */ +module.exports = reflectSetProto + ? function setProto(O, proto) { + // @ts-expect-error TS can't narrow inside a closure, for some reason + if (reflectSetProto(O, proto)) { + return O; + } + throw new $TypeError('Reflect.setPrototypeOf: failed to set [[Prototype]]'); + } + : originalSetProto || ( + setDunderProto ? function setProto(O, proto) { + // @ts-expect-error TS can't narrow inside a closure, for some reason + setDunderProto(O, proto); + return O; + } : null + ); diff --git a/node_modules/set-proto/package.json b/node_modules/set-proto/package.json new file mode 100644 index 0000000000000000000000000000000000000000..47ec706164e4337aff1adbf70772ffa1ef16cecc --- /dev/null +++ b/node_modules/set-proto/package.json @@ -0,0 +1,82 @@ +{ + "name": "set-proto", + "version": "1.0.0", + "description": "Robustly set the [[Prototype]] of an object", + "main": "index.js", + "exports": { + ".": "./index.js", + "./Reflect.setPrototypeOf": "./Reflect.setPrototypeOf.js", + "./Object.setPrototypeOf": "./Object.setPrototypeOf.js", + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "npx npm@\">=10.2\" audit --production", + "tests-only": "nyc tape 'test/**/*.js'", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/set-proto.git" + }, + "keywords": [ + "set", + "proto", + "prototype", + "setPrototypeOf", + "[[Prototype]]" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/set-proto/issues" + }, + "homepage": "https://github.com/ljharb/set-proto#readme", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.2", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.3", + "@types/tape": "^5.8.0", + "auto-changelog": "^2.5.0", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "testling": { + "files": "test/index.js" + } +} diff --git a/node_modules/set-proto/test/index.js b/node_modules/set-proto/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ee1f10942c62755ae76aea405270e42f443d5b1a --- /dev/null +++ b/node_modules/set-proto/test/index.js @@ -0,0 +1,40 @@ +'use strict'; + +var test = require('tape'); + +var setProto = require('../'); + +var isPrototypeOf = Object.prototype.isPrototypeOf; + +test('setProto', function (t) { + t.equal(typeof setProto, 'function', 'is a function'); + + t.test('can set', { skip: !setProto }, function (st) { + var obj = { a: 1 }; + var proto = { b: 2 }; + + st.ok(isPrototypeOf.call(Object.prototype, obj), 'Object.prototype is isPrototypeOf obj'); + st.notOk(isPrototypeOf.call(proto, obj), 'proto is not isPrototypeOf obj'); + st.ok('a' in obj, 'a is in obj'); + st.notOk('b' in obj, 'b is not in obj'); + + // eslint-disable-next-line no-extra-parens + st.equal(/** @type {NonNullable} */ (setProto)(obj, proto), obj, 'returns the object'); + + st.ok(isPrototypeOf.call(Object.prototype, obj), 'Object.prototype is isPrototypeOf obj'); + st.ok(isPrototypeOf.call(proto, obj), 'proto is isPrototypeOf obj'); + st.ok('a' in obj, 'a is in obj'); + st.ok('b' in obj, 'b is in obj'); + + st.equal(Object.getPrototypeOf(obj), proto, 'sets the prototype'); + st.end(); + }); + + t.test('can not set', { skip: !!setProto }, function (st) { + st.equal(setProto, null); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/set-proto/tsconfig.json b/node_modules/set-proto/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..60fb90e45970d491a68e6db8c72fcc531d13a44e --- /dev/null +++ b/node_modules/set-proto/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + //"target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/setprototypeof/LICENSE b/node_modules/setprototypeof/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..61afa2f18532ecd749469c7d9bdd15940a852f5f --- /dev/null +++ b/node_modules/setprototypeof/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Wes Todd + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/setprototypeof/README.md b/node_modules/setprototypeof/README.md new file mode 100644 index 0000000000000000000000000000000000000000..791eeff0c094d51fc53009527cd13884666987ef --- /dev/null +++ b/node_modules/setprototypeof/README.md @@ -0,0 +1,31 @@ +# Polyfill for `Object.setPrototypeOf` + +[![NPM Version](https://img.shields.io/npm/v/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![NPM Downloads](https://img.shields.io/npm/dm/setprototypeof.svg)](https://npmjs.org/package/setprototypeof) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/standard/standard) + +A simple cross platform implementation to set the prototype of an instianted object. Supports all modern browsers and at least back to IE8. + +## Usage: + +``` +$ npm install --save setprototypeof +``` + +```javascript +var setPrototypeOf = require('setprototypeof') + +var obj = {} +setPrototypeOf(obj, { + foo: function () { + return 'bar' + } +}) +obj.foo() // bar +``` + +TypeScript is also supported: + +```typescript +import setPrototypeOf from 'setprototypeof' +``` diff --git a/node_modules/setprototypeof/index.d.ts b/node_modules/setprototypeof/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f108ecd0a8ca1ec609529d3a0b76106c48e418a0 --- /dev/null +++ b/node_modules/setprototypeof/index.d.ts @@ -0,0 +1,2 @@ +declare function setPrototypeOf(o: any, proto: object | null): any; +export = setPrototypeOf; diff --git a/node_modules/setprototypeof/index.js b/node_modules/setprototypeof/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c5270551e93921ccd9eda9ce2b33e54490e57f05 --- /dev/null +++ b/node_modules/setprototypeof/index.js @@ -0,0 +1,17 @@ +'use strict' +/* eslint no-proto: 0 */ +module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties) + +function setProtoOf (obj, proto) { + obj.__proto__ = proto + return obj +} + +function mixinProperties (obj, proto) { + for (var prop in proto) { + if (!Object.prototype.hasOwnProperty.call(obj, prop)) { + obj[prop] = proto[prop] + } + } + return obj +} diff --git a/node_modules/setprototypeof/package.json b/node_modules/setprototypeof/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f20915bea42e4016313176f9e8c1a154f457db3d --- /dev/null +++ b/node_modules/setprototypeof/package.json @@ -0,0 +1,38 @@ +{ + "name": "setprototypeof", + "version": "1.2.0", + "description": "A small polyfill for Object.setprototypeof", + "main": "index.js", + "typings": "index.d.ts", + "scripts": { + "test": "standard && mocha", + "testallversions": "npm run node010 && npm run node4 && npm run node6 && npm run node9 && npm run node11", + "testversion": "docker run -it --rm -v $(PWD):/usr/src/app -w /usr/src/app node:${NODE_VER} npm install mocha@${MOCHA_VER:-latest} && npm t", + "node010": "NODE_VER=0.10 MOCHA_VER=3 npm run testversion", + "node4": "NODE_VER=4 npm run testversion", + "node6": "NODE_VER=6 npm run testversion", + "node9": "NODE_VER=9 npm run testversion", + "node11": "NODE_VER=11 npm run testversion", + "prepublishOnly": "npm t", + "postpublish": "git push origin && git push origin --tags" + }, + "repository": { + "type": "git", + "url": "https://github.com/wesleytodd/setprototypeof.git" + }, + "keywords": [ + "polyfill", + "object", + "setprototypeof" + ], + "author": "Wes Todd", + "license": "ISC", + "bugs": { + "url": "https://github.com/wesleytodd/setprototypeof/issues" + }, + "homepage": "https://github.com/wesleytodd/setprototypeof", + "devDependencies": { + "mocha": "^6.1.4", + "standard": "^13.0.2" + } +} diff --git a/node_modules/setprototypeof/test/index.js b/node_modules/setprototypeof/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..afeb4ddb2921824491502d0f68a0a3a44cf28aa1 --- /dev/null +++ b/node_modules/setprototypeof/test/index.js @@ -0,0 +1,24 @@ +'use strict' +/* eslint-env mocha */ +/* eslint no-proto: 0 */ +var assert = require('assert') +var setPrototypeOf = require('..') + +describe('setProtoOf(obj, proto)', function () { + it('should merge objects', function () { + var obj = { a: 1, b: 2 } + var proto = { b: 3, c: 4 } + var mergeObj = setPrototypeOf(obj, proto) + + if (Object.getPrototypeOf) { + assert.strictEqual(Object.getPrototypeOf(obj), proto) + } else if ({ __proto__: [] } instanceof Array) { + assert.strictEqual(obj.__proto__, proto) + } else { + assert.strictEqual(obj.a, 1) + assert.strictEqual(obj.b, 2) + assert.strictEqual(obj.c, 4) + } + assert.strictEqual(mergeObj, obj) + }) +}) diff --git a/node_modules/sharp/LICENSE b/node_modules/sharp/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..37ec93a14fdcd0d6e525d97c0cfa6b314eaa98d8 --- /dev/null +++ b/node_modules/sharp/LICENSE @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/sharp/README.md b/node_modules/sharp/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1c52c0cdbd13957bb38a96691714a8661fbe76c0 --- /dev/null +++ b/node_modules/sharp/README.md @@ -0,0 +1,118 @@ +# sharp + +sharp logo + +The typical use case for this high speed Node-API module +is to convert large images in common formats to +smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions. + +It can be used with all JavaScript runtimes +that provide support for Node-API v9, including +Node.js (^18.17.0 or >= 20.3.0), Deno and Bun. + +Resizing an image is typically 4x-5x faster than using the +quickest ImageMagick and GraphicsMagick settings +due to its use of [libvips](https://github.com/libvips/libvips). + +Colour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly. +Lanczos resampling ensures quality is not sacrificed for speed. + +As well as image resizing, operations such as +rotation, extraction, compositing and gamma correction are available. + +Most modern macOS, Windows and Linux systems +do not require any additional install or runtime dependencies. + +## Documentation + +Visit [sharp.pixelplumbing.com](https://sharp.pixelplumbing.com/) for complete +[installation instructions](https://sharp.pixelplumbing.com/install), +[API documentation](https://sharp.pixelplumbing.com/api-constructor), +[benchmark tests](https://sharp.pixelplumbing.com/performance) and +[changelog](https://sharp.pixelplumbing.com/changelog). + +## Examples + +```sh +npm install sharp +``` + +```javascript +const sharp = require('sharp'); +``` + +### Callback + +```javascript +sharp(inputBuffer) + .resize(320, 240) + .toFile('output.webp', (err, info) => { ... }); +``` + +### Promise + +```javascript +sharp('input.jpg') + .rotate() + .resize(200) + .jpeg({ mozjpeg: true }) + .toBuffer() + .then( data => { ... }) + .catch( err => { ... }); +``` + +### Async/await + +```javascript +const semiTransparentRedPng = await sharp({ + create: { + width: 48, + height: 48, + channels: 4, + background: { r: 255, g: 0, b: 0, alpha: 0.5 } + } +}) + .png() + .toBuffer(); +``` + +### Stream + +```javascript +const roundedCorners = Buffer.from( + '' +); + +const roundedCornerResizer = + sharp() + .resize(200, 200) + .composite([{ + input: roundedCorners, + blend: 'dest-in' + }]) + .png(); + +readableStream + .pipe(roundedCornerResizer) + .pipe(writableStream); +``` + +## Contributing + +A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md) +covers reporting bugs, requesting features and submitting code changes. + +## Licensing + +Copyright 2013 Lovell Fuller and others. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/node_modules/sharp/install/check.js b/node_modules/sharp/install/check.js new file mode 100644 index 0000000000000000000000000000000000000000..0e00133ab6e74178c8f39914e4ff8c4000e3ef47 --- /dev/null +++ b/node_modules/sharp/install/check.js @@ -0,0 +1,41 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +try { + const { useGlobalLibvips, globalLibvipsVersion, log, spawnRebuild } = require('../lib/libvips'); + + const buildFromSource = (msg) => { + log(msg); + log('Attempting to build from source via node-gyp'); + try { + const addonApi = require('node-addon-api'); + log(`Found node-addon-api ${addonApi.version || ''}`); + } catch (err) { + log('Please add node-addon-api to your dependencies'); + return; + } + try { + const gyp = require('node-gyp'); + log(`Found node-gyp ${gyp().version}`); + } catch (err) { + log('Please add node-gyp to your dependencies'); + return; + } + log('See https://sharp.pixelplumbing.com/install#building-from-source'); + const status = spawnRebuild(); + if (status !== 0) { + process.exit(status); + } + }; + + if (useGlobalLibvips(log)) { + buildFromSource(`Detected globally-installed libvips v${globalLibvipsVersion()}`); + } else if (process.env.npm_config_build_from_source) { + buildFromSource('Detected --build-from-source flag'); + } +} catch (err) { + const summary = err.message.split(/\n/).slice(0, 1); + console.log(`sharp: skipping install check: ${summary}`); +} diff --git a/node_modules/sharp/lib/channel.js b/node_modules/sharp/lib/channel.js new file mode 100644 index 0000000000000000000000000000000000000000..977ea386ea3cbe3726c2672cb1ee68f013a480ad --- /dev/null +++ b/node_modules/sharp/lib/channel.js @@ -0,0 +1,174 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const is = require('./is'); + +/** + * Boolean operations for bandbool. + * @private + */ +const bool = { + and: 'and', + or: 'or', + eor: 'eor' +}; + +/** + * Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel. + * + * See also {@link /api-operation#flatten|flatten}. + * + * @example + * sharp('rgba.png') + * .removeAlpha() + * .toFile('rgb.png', function(err, info) { + * // rgb.png is a 3 channel image without an alpha channel + * }); + * + * @returns {Sharp} + */ +function removeAlpha () { + this.options.removeAlpha = true; + return this; +} + +/** + * Ensure the output image has an alpha transparency channel. + * If missing, the added alpha channel will have the specified + * transparency level, defaulting to fully-opaque (1). + * This is a no-op if the image already has an alpha channel. + * + * @since 0.21.2 + * + * @example + * // rgba.png will be a 4 channel image with a fully-opaque alpha channel + * await sharp('rgb.jpg') + * .ensureAlpha() + * .toFile('rgba.png') + * + * @example + * // rgba is a 4 channel image with a fully-transparent alpha channel + * const rgba = await sharp(rgb) + * .ensureAlpha(0) + * .toBuffer(); + * + * @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque) + * @returns {Sharp} + * @throws {Error} Invalid alpha transparency level + */ +function ensureAlpha (alpha) { + if (is.defined(alpha)) { + if (is.number(alpha) && is.inRange(alpha, 0, 1)) { + this.options.ensureAlpha = alpha; + } else { + throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha); + } + } else { + this.options.ensureAlpha = 1; + } + return this; +} + +/** + * Extract a single channel from a multi-channel image. + * + * @example + * // green.jpg is a greyscale image containing the green channel of the input + * await sharp(input) + * .extractChannel('green') + * .toFile('green.jpg'); + * + * @example + * // red1 is the red value of the first pixel, red2 the second pixel etc. + * const [red1, red2, ...] = await sharp(input) + * .extractChannel(0) + * .raw() + * .toBuffer(); + * + * @param {number|string} channel - zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`. + * @returns {Sharp} + * @throws {Error} Invalid channel + */ +function extractChannel (channel) { + const channelMap = { red: 0, green: 1, blue: 2, alpha: 3 }; + if (Object.keys(channelMap).includes(channel)) { + channel = channelMap[channel]; + } + if (is.integer(channel) && is.inRange(channel, 0, 4)) { + this.options.extractChannel = channel; + } else { + throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel); + } + return this; +} + +/** + * Join one or more channels to the image. + * The meaning of the added channels depends on the output colourspace, set with `toColourspace()`. + * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. + * Channel ordering follows vips convention: + * - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha. + * - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha. + * + * Buffers may be any of the image formats supported by sharp. + * For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor. + * + * @param {Array|string|Buffer} images - one or more images (file paths, Buffers). + * @param {Object} options - image options, see `sharp()` constructor. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function joinChannel (images, options) { + if (Array.isArray(images)) { + images.forEach(function (image) { + this.options.joinChannelIn.push(this._createInputDescriptor(image, options)); + }, this); + } else { + this.options.joinChannelIn.push(this._createInputDescriptor(images, options)); + } + return this; +} + +/** + * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image. + * + * @example + * sharp('3-channel-rgb-input.png') + * .bandbool(sharp.bool.and) + * .toFile('1-channel-output.png', function (err, info) { + * // The output will be a single channel image where each pixel `P = R & G & B`. + * // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]` + * // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`. + * }); + * + * @param {string} boolOp - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function bandbool (boolOp) { + if (is.string(boolOp) && is.inArray(boolOp, ['and', 'or', 'eor'])) { + this.options.bandBoolOp = boolOp; + } else { + throw is.invalidParameterError('boolOp', 'one of: and, or, eor', boolOp); + } + return this; +} + +/** + * Decorate the Sharp prototype with channel-related functions. + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + // Public instance functions + removeAlpha, + ensureAlpha, + extractChannel, + joinChannel, + bandbool + }); + // Class attributes + Sharp.bool = bool; +}; diff --git a/node_modules/sharp/lib/colour.js b/node_modules/sharp/lib/colour.js new file mode 100644 index 0000000000000000000000000000000000000000..9962fb57124e7663fdcc852b1db9d95737753d97 --- /dev/null +++ b/node_modules/sharp/lib/colour.js @@ -0,0 +1,180 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const color = require('color'); +const is = require('./is'); + +/** + * Colourspaces. + * @private + */ +const colourspace = { + multiband: 'multiband', + 'b-w': 'b-w', + bw: 'b-w', + cmyk: 'cmyk', + srgb: 'srgb' +}; + +/** + * Tint the image using the provided colour. + * An alpha channel may be present and will be unchanged by the operation. + * + * @example + * const output = await sharp(input) + * .tint({ r: 255, g: 240, b: 16 }) + * .toBuffer(); + * + * @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module. + * @returns {Sharp} + * @throws {Error} Invalid parameter + */ +function tint (tint) { + this._setBackgroundColourOption('tint', tint); + return this; +} + +/** + * Convert to 8-bit greyscale; 256 shades of grey. + * This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results. + * By default the output image will be web-friendly sRGB and contain three (identical) color channels. + * This may be overridden by other sharp operations such as `toColourspace('b-w')`, + * which will produce an output image containing one color channel. + * An alpha channel may be present, and will be unchanged by the operation. + * + * @example + * const output = await sharp(input).greyscale().toBuffer(); + * + * @param {Boolean} [greyscale=true] + * @returns {Sharp} + */ +function greyscale (greyscale) { + this.options.greyscale = is.bool(greyscale) ? greyscale : true; + return this; +} + +/** + * Alternative spelling of `greyscale`. + * @param {Boolean} [grayscale=true] + * @returns {Sharp} + */ +function grayscale (grayscale) { + return this.greyscale(grayscale); +} + +/** + * Set the pipeline colourspace. + * + * The input image will be converted to the provided colourspace at the start of the pipeline. + * All operations will use this colourspace before converting to the output colourspace, + * as defined by {@link #tocolourspace|toColourspace}. + * + * @since 0.29.0 + * + * @example + * // Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB. + * await sharp(input) + * .pipelineColourspace('rgb16') + * .toColourspace('srgb') + * .toFile('16bpc-pipeline-to-8bpc-output.png') + * + * @param {string} [colourspace] - pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774) + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function pipelineColourspace (colourspace) { + if (!is.string(colourspace)) { + throw is.invalidParameterError('colourspace', 'string', colourspace); + } + this.options.colourspacePipeline = colourspace; + return this; +} + +/** + * Alternative spelling of `pipelineColourspace`. + * @param {string} [colorspace] - pipeline colorspace. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function pipelineColorspace (colorspace) { + return this.pipelineColourspace(colorspace); +} + +/** + * Set the output colourspace. + * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. + * + * @example + * // Output 16 bits per pixel RGB + * await sharp(input) + * .toColourspace('rgb16') + * .toFile('16-bpp.png') + * + * @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794) + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function toColourspace (colourspace) { + if (!is.string(colourspace)) { + throw is.invalidParameterError('colourspace', 'string', colourspace); + } + this.options.colourspace = colourspace; + return this; +} + +/** + * Alternative spelling of `toColourspace`. + * @param {string} [colorspace] - output colorspace. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function toColorspace (colorspace) { + return this.toColourspace(colorspace); +} + +/** + * Update a colour attribute of the this.options Object. + * @private + * @param {string} key + * @param {string|Object} value + * @throws {Error} Invalid value + */ +function _setBackgroundColourOption (key, value) { + if (is.defined(value)) { + if (is.object(value) || is.string(value)) { + const colour = color(value); + this.options[key] = [ + colour.red(), + colour.green(), + colour.blue(), + Math.round(colour.alpha() * 255) + ]; + } else { + throw is.invalidParameterError('background', 'object or string', value); + } + } +} + +/** + * Decorate the Sharp prototype with colour-related functions. + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + // Public + tint, + greyscale, + grayscale, + pipelineColourspace, + pipelineColorspace, + toColourspace, + toColorspace, + // Private + _setBackgroundColourOption + }); + // Class attributes + Sharp.colourspace = colourspace; + Sharp.colorspace = colourspace; +}; diff --git a/node_modules/sharp/lib/composite.js b/node_modules/sharp/lib/composite.js new file mode 100644 index 0000000000000000000000000000000000000000..28e837880477f78c7318a2beebdbfa186a8c4b7e --- /dev/null +++ b/node_modules/sharp/lib/composite.js @@ -0,0 +1,210 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const is = require('./is'); + +/** + * Blend modes. + * @member + * @private + */ +const blend = { + clear: 'clear', + source: 'source', + over: 'over', + in: 'in', + out: 'out', + atop: 'atop', + dest: 'dest', + 'dest-over': 'dest-over', + 'dest-in': 'dest-in', + 'dest-out': 'dest-out', + 'dest-atop': 'dest-atop', + xor: 'xor', + add: 'add', + saturate: 'saturate', + multiply: 'multiply', + screen: 'screen', + overlay: 'overlay', + darken: 'darken', + lighten: 'lighten', + 'colour-dodge': 'colour-dodge', + 'color-dodge': 'colour-dodge', + 'colour-burn': 'colour-burn', + 'color-burn': 'colour-burn', + 'hard-light': 'hard-light', + 'soft-light': 'soft-light', + difference: 'difference', + exclusion: 'exclusion' +}; + +/** + * Composite image(s) over the processed (resized, extracted etc.) image. + * + * The images to composite must be the same size or smaller than the processed image. + * If both `top` and `left` options are provided, they take precedence over `gravity`. + * + * Any resize, rotate or extract operations in the same processing pipeline + * will always be applied to the input image before composition. + * + * The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`, + * `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`, + * `xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`, + * `colour-dodge`, `color-dodge`, `colour-burn`,`color-burn`, + * `hard-light`, `soft-light`, `difference`, `exclusion`. + * + * More information about blend modes can be found at + * https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode + * and https://www.cairographics.org/operators/ + * + * @since 0.22.0 + * + * @example + * await sharp(background) + * .composite([ + * { input: layer1, gravity: 'northwest' }, + * { input: layer2, gravity: 'southeast' }, + * ]) + * .toFile('combined.png'); + * + * @example + * const output = await sharp('input.gif', { animated: true }) + * .composite([ + * { input: 'overlay.png', tile: true, blend: 'saturate' } + * ]) + * .toBuffer(); + * + * @example + * sharp('input.png') + * .rotate(180) + * .resize(300) + * .flatten( { background: '#ff6600' } ) + * .composite([{ input: 'overlay.png', gravity: 'southeast' }]) + * .sharpen() + * .withMetadata() + * .webp( { quality: 90 } ) + * .toBuffer() + * .then(function(outputBuffer) { + * // outputBuffer contains upside down, 300px wide, alpha channel flattened + * // onto orange background, composited with overlay.png with SE gravity, + * // sharpened, with metadata, 90% quality WebP image data. Phew! + * }); + * + * @param {Object[]} images - Ordered list of images to composite + * @param {Buffer|String} [images[].input] - Buffer containing image data, String containing the path to an image file, or Create object (see below) + * @param {Object} [images[].input.create] - describes a blank overlay to be created. + * @param {Number} [images[].input.create.width] + * @param {Number} [images[].input.create.height] + * @param {Number} [images[].input.create.channels] - 3-4 + * @param {String|Object} [images[].input.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @param {Object} [images[].input.text] - describes a new text image to be created. + * @param {string} [images[].input.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. + * @param {string} [images[].input.text.font] - font name to render with. + * @param {string} [images[].input.text.fontfile] - absolute filesystem path to a font file that can be used by `font`. + * @param {number} [images[].input.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. + * @param {number} [images[].input.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. + * @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). + * @param {boolean} [images[].input.text.justify=false] - set this to true to apply justification to the text. + * @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified. + * @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `Red!`. + * @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified. + * @param {String} [images[].blend='over'] - how to blend this image with the image below. + * @param {String} [images[].gravity='centre'] - gravity at which to place the overlay. + * @param {Number} [images[].top] - the pixel offset from the top edge. + * @param {Number} [images[].left] - the pixel offset from the left edge. + * @param {Boolean} [images[].tile=false] - set to true to repeat the overlay image across the entire image with the given `gravity`. + * @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option. + * @param {Number} [images[].density=72] - number representing the DPI for vector overlay image. + * @param {Object} [images[].raw] - describes overlay when using raw pixel data. + * @param {Number} [images[].raw.width] + * @param {Number} [images[].raw.height] + * @param {Number} [images[].raw.channels] + * @param {boolean} [images[].animated=false] - Set to `true` to read all frames/pages of an animated image. + * @param {string} [images[].failOn='warning'] - @see {@link /api-constructor#parameters|constructor parameters} + * @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor#parameters|constructor parameters} + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function composite (images) { + if (!Array.isArray(images)) { + throw is.invalidParameterError('images to composite', 'array', images); + } + this.options.composite = images.map(image => { + if (!is.object(image)) { + throw is.invalidParameterError('image to composite', 'object', image); + } + const inputOptions = this._inputOptionsFromObject(image); + const composite = { + input: this._createInputDescriptor(image.input, inputOptions, { allowStream: false }), + blend: 'over', + tile: false, + left: 0, + top: 0, + hasOffset: false, + gravity: 0, + premultiplied: false + }; + if (is.defined(image.blend)) { + if (is.string(blend[image.blend])) { + composite.blend = blend[image.blend]; + } else { + throw is.invalidParameterError('blend', 'valid blend name', image.blend); + } + } + if (is.defined(image.tile)) { + if (is.bool(image.tile)) { + composite.tile = image.tile; + } else { + throw is.invalidParameterError('tile', 'boolean', image.tile); + } + } + if (is.defined(image.left)) { + if (is.integer(image.left)) { + composite.left = image.left; + } else { + throw is.invalidParameterError('left', 'integer', image.left); + } + } + if (is.defined(image.top)) { + if (is.integer(image.top)) { + composite.top = image.top; + } else { + throw is.invalidParameterError('top', 'integer', image.top); + } + } + if (is.defined(image.top) !== is.defined(image.left)) { + throw new Error('Expected both left and top to be set'); + } else { + composite.hasOffset = is.integer(image.top) && is.integer(image.left); + } + if (is.defined(image.gravity)) { + if (is.integer(image.gravity) && is.inRange(image.gravity, 0, 8)) { + composite.gravity = image.gravity; + } else if (is.string(image.gravity) && is.integer(this.constructor.gravity[image.gravity])) { + composite.gravity = this.constructor.gravity[image.gravity]; + } else { + throw is.invalidParameterError('gravity', 'valid gravity', image.gravity); + } + } + if (is.defined(image.premultiplied)) { + if (is.bool(image.premultiplied)) { + composite.premultiplied = image.premultiplied; + } else { + throw is.invalidParameterError('premultiplied', 'boolean', image.premultiplied); + } + } + return composite; + }); + return this; +} + +/** + * Decorate the Sharp prototype with composite-related functions. + * @private + */ +module.exports = function (Sharp) { + Sharp.prototype.composite = composite; + Sharp.blend = blend; +}; diff --git a/node_modules/sharp/lib/constructor.js b/node_modules/sharp/lib/constructor.js new file mode 100644 index 0000000000000000000000000000000000000000..41f780204424b6f8647fe85531050a1a7b9d4824 --- /dev/null +++ b/node_modules/sharp/lib/constructor.js @@ -0,0 +1,452 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const util = require('node:util'); +const stream = require('node:stream'); +const is = require('./is'); + +require('./sharp'); + +// Use NODE_DEBUG=sharp to enable libvips warnings +const debuglog = util.debuglog('sharp'); + +/** + * Constructor factory to create an instance of `sharp`, to which further methods are chained. + * + * JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object. + * When using Stream based output, derived attributes are available from the `info` event. + * + * Non-critical problems encountered during processing are emitted as `warning` events. + * + * Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class. + * + * When loading more than one page/frame of an animated image, + * these are combined as a vertically-stacked "toilet roll" image + * where the overall height is the `pageHeight` multiplied by the number of `pages`. + * + * @constructs Sharp + * + * @emits Sharp#info + * @emits Sharp#warning + * + * @example + * sharp('input.jpg') + * .resize(300, 200) + * .toFile('output.jpg', function(err) { + * // output.jpg is a 300 pixels wide and 200 pixels high image + * // containing a scaled and cropped version of input.jpg + * }); + * + * @example + * // Read image data from remote URL, + * // resize to 300 pixels wide, + * // emit an 'info' event with calculated dimensions + * // and finally write image data to writableStream + * const { body } = fetch('https://...'); + * const readableStream = Readable.fromWeb(body); + * const transformer = sharp() + * .resize(300) + * .on('info', ({ height }) => { + * console.log(`Image height is ${height}`); + * }); + * readableStream.pipe(transformer).pipe(writableStream); + * + * @example + * // Create a blank 300x200 PNG image of semi-translucent red pixels + * sharp({ + * create: { + * width: 300, + * height: 200, + * channels: 4, + * background: { r: 255, g: 0, b: 0, alpha: 0.5 } + * } + * }) + * .png() + * .toBuffer() + * .then( ... ); + * + * @example + * // Convert an animated GIF to an animated WebP + * await sharp('in.gif', { animated: true }).toFile('out.webp'); + * + * @example + * // Read a raw array of pixels and save it to a png + * const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray + * const image = sharp(input, { + * // because the input does not contain its dimensions or how many channels it has + * // we need to specify it in the constructor options + * raw: { + * width: 2, + * height: 1, + * channels: 3 + * } + * }); + * await image.toFile('my-two-pixels.png'); + * + * @example + * // Generate RGB Gaussian noise + * await sharp({ + * create: { + * width: 300, + * height: 200, + * channels: 3, + * noise: { + * type: 'gaussian', + * mean: 128, + * sigma: 30 + * } + * } + * }).toFile('noise.png'); + * + * @example + * // Generate an image from text + * await sharp({ + * text: { + * text: 'Hello, world!', + * width: 400, // max width + * height: 300 // max height + * } + * }).toFile('text_bw.png'); + * + * @example + * // Generate an rgba image from text using pango markup and font + * await sharp({ + * text: { + * text: 'Red!blue', + * font: 'sans', + * rgba: true, + * dpi: 300 + * } + * }).toFile('text_rgba.png'); + * + * @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string)} [input] - if present, can be + * a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or + * a TypedArray containing raw pixel image data, or + * a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. + * JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. + * @param {Object} [options] - if present, is an Object with optional attributes. + * @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort. + * @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels + * (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. + * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). + * @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). + * @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. + * @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000. + * @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored. + * @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. + * @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. + * @param {number} [options.subifd=-1] - subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. + * @param {number} [options.level=0] - level to extract from a multi-level input (OpenSlide), zero based. + * @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. + * @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering. + * @param {number} [options.raw.width] - integral number of pixels wide. + * @param {number} [options.raw.height] - integral number of pixels high. + * @param {number} [options.raw.channels] - integral number of channels, between 1 and 4. + * @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true` + * to avoid sharp premultiplying the image. (optional, default `false`) + * @param {Object} [options.create] - describes a new image to be created. + * @param {number} [options.create.width] - integral number of pixels wide. + * @param {number} [options.create.height] - integral number of pixels high. + * @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA). + * @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @param {Object} [options.create.noise] - describes a noise to be created. + * @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported. + * @param {number} [options.create.noise.mean] - mean of pixels in generated noise. + * @param {number} [options.create.noise.sigma] - standard deviation of pixels in generated noise. + * @param {Object} [options.text] - describes a new text image to be created. + * @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. + * @param {string} [options.text.font] - font name to render with. + * @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`. + * @param {number} [options.text.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. + * @param {number} [options.text.height=0] - Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. + * @param {string} [options.text.align='left'] - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`). + * @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text. + * @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified. + * @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `Red!`. + * @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified. + * @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +const Sharp = function (input, options) { + if (arguments.length === 1 && !is.defined(input)) { + throw new Error('Invalid input'); + } + if (!(this instanceof Sharp)) { + return new Sharp(input, options); + } + stream.Duplex.call(this); + this.options = { + // resize options + topOffsetPre: -1, + leftOffsetPre: -1, + widthPre: -1, + heightPre: -1, + topOffsetPost: -1, + leftOffsetPost: -1, + widthPost: -1, + heightPost: -1, + width: -1, + height: -1, + canvas: 'crop', + position: 0, + resizeBackground: [0, 0, 0, 255], + useExifOrientation: false, + angle: 0, + rotationAngle: 0, + rotationBackground: [0, 0, 0, 255], + rotateBeforePreExtract: false, + flip: false, + flop: false, + extendTop: 0, + extendBottom: 0, + extendLeft: 0, + extendRight: 0, + extendBackground: [0, 0, 0, 255], + extendWith: 'background', + withoutEnlargement: false, + withoutReduction: false, + affineMatrix: [], + affineBackground: [0, 0, 0, 255], + affineIdx: 0, + affineIdy: 0, + affineOdx: 0, + affineOdy: 0, + affineInterpolator: this.constructor.interpolators.bilinear, + kernel: 'lanczos3', + fastShrinkOnLoad: true, + // operations + tint: [-1, 0, 0, 0], + flatten: false, + flattenBackground: [0, 0, 0], + unflatten: false, + negate: false, + negateAlpha: true, + medianSize: 0, + blurSigma: 0, + precision: 'integer', + minAmpl: 0.2, + sharpenSigma: 0, + sharpenM1: 1, + sharpenM2: 2, + sharpenX1: 2, + sharpenY2: 10, + sharpenY3: 20, + threshold: 0, + thresholdGrayscale: true, + trimBackground: [], + trimThreshold: -1, + trimLineArt: false, + gamma: 0, + gammaOut: 0, + greyscale: false, + normalise: false, + normaliseLower: 1, + normaliseUpper: 99, + claheWidth: 0, + claheHeight: 0, + claheMaxSlope: 3, + brightness: 1, + saturation: 1, + hue: 0, + lightness: 0, + booleanBufferIn: null, + booleanFileIn: '', + joinChannelIn: [], + extractChannel: -1, + removeAlpha: false, + ensureAlpha: -1, + colourspace: 'srgb', + colourspacePipeline: 'last', + composite: [], + // output + fileOut: '', + formatOut: 'input', + streamOut: false, + keepMetadata: 0, + withMetadataOrientation: -1, + withMetadataDensity: 0, + withIccProfile: '', + withExif: {}, + withExifMerge: true, + resolveWithObject: false, + // output format + jpegQuality: 80, + jpegProgressive: false, + jpegChromaSubsampling: '4:2:0', + jpegTrellisQuantisation: false, + jpegOvershootDeringing: false, + jpegOptimiseScans: false, + jpegOptimiseCoding: true, + jpegQuantisationTable: 0, + pngProgressive: false, + pngCompressionLevel: 6, + pngAdaptiveFiltering: false, + pngPalette: false, + pngQuality: 100, + pngEffort: 7, + pngBitdepth: 8, + pngDither: 1, + jp2Quality: 80, + jp2TileHeight: 512, + jp2TileWidth: 512, + jp2Lossless: false, + jp2ChromaSubsampling: '4:4:4', + webpQuality: 80, + webpAlphaQuality: 100, + webpLossless: false, + webpNearLossless: false, + webpSmartSubsample: false, + webpPreset: 'default', + webpEffort: 4, + webpMinSize: false, + webpMixed: false, + gifBitdepth: 8, + gifEffort: 7, + gifDither: 1, + gifInterFrameMaxError: 0, + gifInterPaletteMaxError: 3, + gifReuse: true, + gifProgressive: false, + tiffQuality: 80, + tiffCompression: 'jpeg', + tiffPredictor: 'horizontal', + tiffPyramid: false, + tiffMiniswhite: false, + tiffBitdepth: 8, + tiffTile: false, + tiffTileHeight: 256, + tiffTileWidth: 256, + tiffXres: 1.0, + tiffYres: 1.0, + tiffResolutionUnit: 'inch', + heifQuality: 50, + heifLossless: false, + heifCompression: 'av1', + heifEffort: 4, + heifChromaSubsampling: '4:4:4', + heifBitdepth: 8, + jxlDistance: 1, + jxlDecodingTier: 0, + jxlEffort: 7, + jxlLossless: false, + rawDepth: 'uchar', + tileSize: 256, + tileOverlap: 0, + tileContainer: 'fs', + tileLayout: 'dz', + tileFormat: 'last', + tileDepth: 'last', + tileAngle: 0, + tileSkipBlanks: -1, + tileBackground: [255, 255, 255, 255], + tileCentre: false, + tileId: 'https://example.com/iiif', + tileBasename: '', + timeoutSeconds: 0, + linearA: [], + linearB: [], + // Function to notify of libvips warnings + debuglog: warning => { + this.emit('warning', warning); + debuglog(warning); + }, + // Function to notify of queue length changes + queueListener: function (queueLength) { + Sharp.queue.emit('change', queueLength); + } + }; + this.options.input = this._createInputDescriptor(input, options, { allowStream: true }); + return this; +}; +Object.setPrototypeOf(Sharp.prototype, stream.Duplex.prototype); +Object.setPrototypeOf(Sharp, stream.Duplex); + +/** + * Take a "snapshot" of the Sharp instance, returning a new instance. + * Cloned instances inherit the input of their parent instance. + * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream. + * + * @example + * const pipeline = sharp().rotate(); + * pipeline.clone().resize(800, 600).pipe(firstWritableStream); + * pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream); + * readableStream.pipe(pipeline); + * // firstWritableStream receives auto-rotated, resized readableStream + * // secondWritableStream receives auto-rotated, extracted region of readableStream + * + * @example + * // Create a pipeline that will download an image, resize it and format it to different files + * // Using Promises to know when the pipeline is complete + * const fs = require("fs"); + * const got = require("got"); + * const sharpStream = sharp({ failOn: 'none' }); + * + * const promises = []; + * + * promises.push( + * sharpStream + * .clone() + * .jpeg({ quality: 100 }) + * .toFile("originalFile.jpg") + * ); + * + * promises.push( + * sharpStream + * .clone() + * .resize({ width: 500 }) + * .jpeg({ quality: 80 }) + * .toFile("optimized-500.jpg") + * ); + * + * promises.push( + * sharpStream + * .clone() + * .resize({ width: 500 }) + * .webp({ quality: 80 }) + * .toFile("optimized-500.webp") + * ); + * + * // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md + * got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream); + * + * Promise.all(promises) + * .then(res => { console.log("Done!", res); }) + * .catch(err => { + * console.error("Error processing files, let's clean it up", err); + * try { + * fs.unlinkSync("originalFile.jpg"); + * fs.unlinkSync("optimized-500.jpg"); + * fs.unlinkSync("optimized-500.webp"); + * } catch (e) {} + * }); + * + * @returns {Sharp} + */ +function clone () { + // Clone existing options + const clone = this.constructor.call(); + const { debuglog, queueListener, ...options } = this.options; + clone.options = structuredClone(options); + clone.options.debuglog = debuglog; + clone.options.queueListener = queueListener; + // Pass 'finish' event to clone for Stream-based input + if (this._isStreamInput()) { + this.on('finish', () => { + // Clone inherits input data + this._flattenBufferIn(); + clone.options.input.buffer = this.options.input.buffer; + clone.emit('finish'); + }); + } + return clone; +} +Object.assign(Sharp.prototype, { clone }); + +/** + * Export constructor. + * @private + */ +module.exports = Sharp; diff --git a/node_modules/sharp/lib/index.d.ts b/node_modules/sharp/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7fba55f7864dbb03b4241a682350dfa8e4de181e --- /dev/null +++ b/node_modules/sharp/lib/index.d.ts @@ -0,0 +1,1754 @@ +/** + * Copyright 2017 François Nguyen and others. + * + * Billy Kwok + * Bradley Odell + * Espen Hovlandsdal + * Floris de Bijl + * François Nguyen + * Jamie Woodbury + * Wooseop Kim + * + * 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. + */ + +// SPDX-License-Identifier: MIT + +/// + +import { Duplex } from 'stream'; + +//#region Constructor functions + +/** + * Creates a sharp instance from an image + * @param input Buffer containing JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data, or String containing the path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. + * @param options Object with optional attributes. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ +declare function sharp(options?: sharp.SharpOptions): sharp.Sharp; +declare function sharp( + input?: + | Buffer + | ArrayBuffer + | Uint8Array + | Uint8ClampedArray + | Int8Array + | Uint16Array + | Int16Array + | Uint32Array + | Int32Array + | Float32Array + | Float64Array + | string, + options?: sharp.SharpOptions, +): sharp.Sharp; + +declare namespace sharp { + /** Object containing nested boolean values representing the available input and output formats/methods. */ + const format: FormatEnum; + + /** An Object containing the version numbers of sharp, libvips and its dependencies. */ + const versions: { + vips: string; + cairo?: string | undefined; + croco?: string | undefined; + exif?: string | undefined; + expat?: string | undefined; + ffi?: string | undefined; + fontconfig?: string | undefined; + freetype?: string | undefined; + gdkpixbuf?: string | undefined; + gif?: string | undefined; + glib?: string | undefined; + gsf?: string | undefined; + harfbuzz?: string | undefined; + jpeg?: string | undefined; + lcms?: string | undefined; + orc?: string | undefined; + pango?: string | undefined; + pixman?: string | undefined; + png?: string | undefined; + sharp?: string | undefined; + svg?: string | undefined; + tiff?: string | undefined; + webp?: string | undefined; + avif?: string | undefined; + heif?: string | undefined; + xml?: string | undefined; + zlib?: string | undefined; + }; + + /** An Object containing the available interpolators and their proper values */ + const interpolators: Interpolators; + + /** An EventEmitter that emits a change event when a task is either queued, waiting for libuv to provide a worker thread, complete */ + const queue: NodeJS.EventEmitter; + + //#endregion + + //#region Utility functions + + /** + * Gets or, when options are provided, sets the limits of libvips' operation cache. + * Existing entries in the cache will be trimmed after any change in limits. + * This method always returns cache statistics, useful for determining how much working memory is required for a particular task. + * @param options Object with the following attributes, or Boolean where true uses default cache settings and false removes all caching (optional, default true) + * @returns The cache results. + */ + function cache(options?: boolean | CacheOptions): CacheResult; + + /** + * Gets or sets the number of threads libvips' should create to process each image. + * The default value is the number of CPU cores. A value of 0 will reset to this default. + * The maximum number of images that can be processed in parallel is limited by libuv's UV_THREADPOOL_SIZE environment variable. + * @param concurrency The new concurrency value. + * @returns The current concurrency value. + */ + function concurrency(concurrency?: number): number; + + /** + * Provides access to internal task counters. + * @returns Object containing task counters + */ + function counters(): SharpCounters; + + /** + * Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with highway support. + * Improves the performance of resize, blur and sharpen operations by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON. + * @param enable enable or disable use of SIMD vector unit instructions + * @returns true if usage of SIMD vector unit instructions is enabled + */ + function simd(enable?: boolean): boolean; + + /** + * Block libvips operations at runtime. + * + * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable, + * which when set will block all "untrusted" operations. + * + * @since 0.32.4 + * + * @example Block all TIFF input. + * sharp.block({ + * operation: ['VipsForeignLoadTiff'] + * }); + * + * @param {Object} options + * @param {Array} options.operation - List of libvips low-level operation names to block. + */ + function block(options: { operation: string[] }): void; + + /** + * Unblock libvips operations at runtime. + * + * This is useful for defining a list of allowed operations. + * + * @since 0.32.4 + * + * @example Block all input except WebP from the filesystem. + * sharp.block({ + * operation: ['VipsForeignLoad'] + * }); + * sharp.unblock({ + * operation: ['VipsForeignLoadWebpFile'] + * }); + * + * @example Block all input except JPEG and PNG from a Buffer or Stream. + * sharp.block({ + * operation: ['VipsForeignLoad'] + * }); + * sharp.unblock({ + * operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer'] + * }); + * + * @param {Object} options + * @param {Array} options.operation - List of libvips low-level operation names to unblock. + */ + function unblock(options: { operation: string[] }): void; + + //#endregion + + const gravity: GravityEnum; + const strategy: StrategyEnum; + const kernel: KernelEnum; + const fit: FitEnum; + const bool: BoolEnum; + + interface Sharp extends Duplex { + //#region Channel functions + + /** + * Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel. + * @returns A sharp instance that can be used to chain operations + */ + removeAlpha(): Sharp; + + /** + * Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel. + * @param alpha transparency level (0=fully-transparent, 1=fully-opaque) (optional, default 1). + * @returns A sharp instance that can be used to chain operations + */ + ensureAlpha(alpha?: number): Sharp; + + /** + * Extract a single channel from a multi-channel image. + * @param channel zero-indexed channel/band number to extract, or red, green, blue or alpha. + * @throws {Error} Invalid channel + * @returns A sharp instance that can be used to chain operations + */ + extractChannel(channel: 0 | 1 | 2 | 3 | 'red' | 'green' | 'blue' | 'alpha'): Sharp; + + /** + * Join one or more channels to the image. The meaning of the added channels depends on the output colourspace, set with toColourspace(). + * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. Channel ordering follows vips convention: + * - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha. + * - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha. + * + * Buffers may be any of the image formats supported by sharp. + * For raw pixel input, the options object should contain a raw attribute, which follows the format of the attribute of the same name in the sharp() constructor. + * @param images one or more images (file paths, Buffers). + * @param options image options, see sharp() constructor. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + joinChannel(images: string | Buffer | ArrayLike, options?: SharpOptions): Sharp; + + /** + * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image. + * @param boolOp one of "and", "or" or "eor" to perform that bitwise operation, like the C logic operators &, | and ^ respectively. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + bandbool(boolOp: keyof BoolEnum): Sharp; + + //#endregion + + //#region Color functions + + /** + * Tint the image using the provided colour. + * An alpha channel may be present and will be unchanged by the operation. + * @param tint Parsed by the color module. + * @returns A sharp instance that can be used to chain operations + */ + tint(tint: Color): Sharp; + + /** + * Convert to 8-bit greyscale; 256 shades of grey. + * This is a linear operation. + * If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results. + * By default the output image will be web-friendly sRGB and contain three (identical) color channels. + * This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one color channel. + * An alpha channel may be present, and will be unchanged by the operation. + * @param greyscale true to enable and false to disable (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + greyscale(greyscale?: boolean): Sharp; + + /** + * Alternative spelling of greyscale(). + * @param grayscale true to enable and false to disable (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + grayscale(grayscale?: boolean): Sharp; + + /** + * Set the pipeline colourspace. + * The input image will be converted to the provided colourspace at the start of the pipeline. + * All operations will use this colourspace before converting to the output colourspace, as defined by toColourspace. + * This feature is experimental and has not yet been fully-tested with all operations. + * + * @param colourspace pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ... + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + pipelineColourspace(colourspace?: string): Sharp; + + /** + * Alternative spelling of pipelineColourspace + * @param colorspace pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ... + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + pipelineColorspace(colorspace?: string): Sharp; + + /** + * Set the output colourspace. + * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. + * @param colourspace output colourspace e.g. srgb, rgb, cmyk, lab, b-w ... + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + toColourspace(colourspace?: string): Sharp; + + /** + * Alternative spelling of toColourspace(). + * @param colorspace output colorspace e.g. srgb, rgb, cmyk, lab, b-w ... + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + toColorspace(colorspace: string): Sharp; + + //#endregion + + //#region Composite functions + + /** + * Composite image(s) over the processed (resized, extracted etc.) image. + * + * The images to composite must be the same size or smaller than the processed image. + * If both `top` and `left` options are provided, they take precedence over `gravity`. + * @param images - Ordered list of images to composite + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + composite(images: OverlayOptions[]): Sharp; + + //#endregion + + //#region Input functions + + /** + * Take a "snapshot" of the Sharp instance, returning a new instance. + * Cloned instances inherit the input of their parent instance. + * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream. + * @returns A sharp instance that can be used to chain operations + */ + clone(): Sharp; + + /** + * Fast access to (uncached) image metadata without decoding any compressed image data. + * @returns A sharp instance that can be used to chain operations + */ + metadata(callback: (err: Error, metadata: Metadata) => void): Sharp; + + /** + * Fast access to (uncached) image metadata without decoding any compressed image data. + * @returns A promise that resolves with a metadata object + */ + metadata(): Promise; + + /** + * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image. + * @returns A sharp instance that can be used to chain operations + */ + keepMetadata(): Sharp; + + /** + * Access to pixel-derived image statistics for every channel in the image. + * @returns A sharp instance that can be used to chain operations + */ + stats(callback: (err: Error, stats: Stats) => void): Sharp; + + /** + * Access to pixel-derived image statistics for every channel in the image. + * @returns A promise that resolves with a stats object + */ + stats(): Promise; + + //#endregion + + //#region Operation functions + + /** + * Rotate the output image by either an explicit angle or auto-orient based on the EXIF Orientation tag. + * + * If an angle is provided, it is converted to a valid positive degree rotation. For example, -450 will produce a 270deg rotation. + * + * When rotating by an angle other than a multiple of 90, the background colour can be provided with the background option. + * + * If no angle is provided, it is determined from the EXIF data. Mirroring is supported and may infer the use of a flip operation. + * + * The use of rotate implies the removal of the EXIF Orientation tag, if any. + * + * Method order is important when both rotating and extracting regions, for example rotate(x).extract(y) will produce a different result to extract(y).rotate(x). + * @param angle angle of rotation. (optional, default auto) + * @param options if present, is an Object with optional attributes. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + rotate(angle?: number, options?: RotateOptions): Sharp; + + /** + * Flip the image about the vertical Y axis. This always occurs after rotation, if any. + * The use of flip implies the removal of the EXIF Orientation tag, if any. + * @param flip true to enable and false to disable (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + flip(flip?: boolean): Sharp; + + /** + * Flop the image about the horizontal X axis. This always occurs after rotation, if any. + * The use of flop implies the removal of the EXIF Orientation tag, if any. + * @param flop true to enable and false to disable (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + flop(flop?: boolean): Sharp; + + /** + * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. + * You must provide an array of length 4 or a 2x2 affine transformation matrix. + * By default, new pixels are filled with a black background. You can provide a background color with the `background` option. + * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. + * + * In the case of a 2x2 matrix, the transform is: + * X = matrix[0, 0] * (x + idx) + matrix[0, 1] * (y + idy) + odx + * Y = matrix[1, 0] * (x + idx) + matrix[1, 1] * (y + idy) + ody + * + * where: + * + * x and y are the coordinates in input image. + * X and Y are the coordinates in output image. + * (0,0) is the upper left corner. + * + * @param matrix Affine transformation matrix, may either by a array of length four or a 2x2 matrix array + * @param options if present, is an Object with optional attributes. + * + * @returns A sharp instance that can be used to chain operations + */ + affine(matrix: [number, number, number, number] | Matrix2x2, options?: AffineOptions): Sharp; + + /** + * Sharpen the image. + * When used without parameters, performs a fast, mild sharpen of the output image. + * When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. + * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. + * @param options if present, is an Object with optional attributes + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + sharpen(options?: SharpenOptions): Sharp; + + /** + * Sharpen the image. + * When used without parameters, performs a fast, mild sharpen of the output image. + * When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. + * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. + * @param sigma the sigma of the Gaussian mask, where sigma = 1 + radius / 2. + * @param flat the level of sharpening to apply to "flat" areas. (optional, default 1.0) + * @param jagged the level of sharpening to apply to "jagged" areas. (optional, default 2.0) + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + * + * @deprecated Use the object parameter `sharpen({sigma, m1, m2, x1, y2, y3})` instead + */ + sharpen(sigma?: number, flat?: number, jagged?: number): Sharp; + + /** + * Apply median filter. When used without parameters the default window is 3x3. + * @param size square mask size: size x size (optional, default 3) + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + median(size?: number): Sharp; + + /** + * Blur the image. + * When used without parameters, performs a fast, mild blur of the output image. + * When a sigma is provided, performs a slower, more accurate Gaussian blur. + * When a boolean sigma is provided, ether blur mild or disable blur + * @param sigma a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where sigma = 1 + radius / 2. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + blur(sigma?: number | boolean | BlurOptions): Sharp; + + /** + * Merge alpha transparency channel, if any, with background. + * @param flatten true to enable and false to disable (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + flatten(flatten?: boolean | FlattenOptions): Sharp; + + /** + * Ensure the image has an alpha channel with all white pixel values made fully transparent. + * Existing alpha channel values for non-white pixels remain unchanged. + * @returns A sharp instance that can be used to chain operations + */ + unflatten(): Sharp; + + /** + * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of 1/gamma then increasing the encoding (brighten) post-resize at a factor of gamma. + * This can improve the perceived brightness of a resized image in non-linear colour spaces. + * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation when applying a gamma correction. + * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases. + * @param gamma value between 1.0 and 3.0. (optional, default 2.2) + * @param gammaOut value between 1.0 and 3.0. (optional, defaults to same as gamma) + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + gamma(gamma?: number, gammaOut?: number): Sharp; + + /** + * Produce the "negative" of the image. + * @param negate true to enable and false to disable, or an object of options (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + negate(negate?: boolean | NegateOptions): Sharp; + + /** + * Enhance output image contrast by stretching its luminance to cover a full dynamic range. + * + * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes. + * + * Luminance values below the `lower` percentile will be underexposed by clipping to zero. + * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value. + * + * @param normalise options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + normalise(normalise?: NormaliseOptions): Sharp; + + /** + * Alternative spelling of normalise. + * @param normalize options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + normalize(normalize?: NormaliseOptions): Sharp; + + /** + * Perform contrast limiting adaptive histogram equalization (CLAHE) + * + * This will, in general, enhance the clarity of the image by bringing out + * darker details. Please read more about CLAHE here: + * https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE + * + * @param options clahe options + */ + clahe(options: ClaheOptions): Sharp; + + /** + * Convolve the image with the specified kernel. + * @param kernel the specified kernel + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + convolve(kernel: Kernel): Sharp; + + /** + * Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0. + * @param threshold a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default 128) + * @param options threshold options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + threshold(threshold?: number, options?: ThresholdOptions): Sharp; + + /** + * Perform a bitwise boolean operation with operand image. + * This operation creates an output image where each pixel is the result of the selected bitwise boolean operation between the corresponding pixels of the input images. + * @param operand Buffer containing image data or String containing the path to an image file. + * @param operator one of "and", "or" or "eor" to perform that bitwise operation, like the C logic operators &, | and ^ respectively. + * @param options describes operand when using raw pixel data. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + boolean(operand: string | Buffer, operator: keyof BoolEnum, options?: { raw: Raw }): Sharp; + + /** + * Apply the linear formula a * input + b to the image (levels adjustment) + * @param a multiplier (optional, default 1.0) + * @param b offset (optional, default 0.0) + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + linear(a?: number | number[] | null, b?: number | number[]): Sharp; + + /** + * Recomb the image with the specified matrix. + * @param inputMatrix 3x3 Recombination matrix or 4x4 Recombination matrix + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + recomb(inputMatrix: Matrix3x3 | Matrix4x4): Sharp; + + /** + * Transforms the image using brightness, saturation, hue rotation and lightness. + * Brightness and lightness both operate on luminance, with the difference being that brightness is multiplicative whereas lightness is additive. + * @param options describes the modulation + * @returns A sharp instance that can be used to chain operations + */ + modulate(options?: { + brightness?: number | undefined; + saturation?: number | undefined; + hue?: number | undefined; + lightness?: number | undefined; + }): Sharp; + + //#endregion + + //#region Output functions + + /** + * Write output image data to a file. + * If an explicit output format is not selected, it will be inferred from the extension, with JPEG, PNG, WebP, AVIF, TIFF, DZI, and libvips' V format supported. + * Note that raw pixel data is only supported for buffer output. + * @param fileOut The path to write the image data to. + * @param callback Callback function called on completion with two arguments (err, info). info contains the output image format, size (bytes), width, height and channels. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + toFile(fileOut: string, callback: (err: Error, info: OutputInfo) => void): Sharp; + + /** + * Write output image data to a file. + * @param fileOut The path to write the image data to. + * @throws {Error} Invalid parameters + * @returns A promise that fulfills with an object containing information on the resulting file + */ + toFile(fileOut: string): Promise; + + /** + * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported. + * By default, the format will match the input image, except SVG input which becomes PNG output. + * @param callback Callback function called on completion with three arguments (err, buffer, info). + * @returns A sharp instance that can be used to chain operations + */ + toBuffer(callback: (err: Error, buffer: Buffer, info: OutputInfo) => void): Sharp; + + /** + * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported. + * By default, the format will match the input image, except SVG input which becomes PNG output. + * @param options resolve options + * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data. + * @returns A promise that resolves with the Buffer data. + */ + toBuffer(options?: { resolveWithObject: false }): Promise; + + /** + * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported. + * By default, the format will match the input image, except SVG input which becomes PNG output. + * @param options resolve options + * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data. + * @returns A promise that resolves with an object containing the Buffer data and an info object containing the output image format, size (bytes), width, height and channels + */ + toBuffer(options: { resolveWithObject: true }): Promise<{ data: Buffer; info: OutputInfo }>; + + /** + * Keep all EXIF metadata from the input image in the output image. + * EXIF metadata is unsupported for TIFF output. + * @returns A sharp instance that can be used to chain operations + */ + keepExif(): Sharp; + + /** + * Set EXIF metadata in the output image, ignoring any EXIF in the input image. + * @param {Exif} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. + * @returns A sharp instance that can be used to chain operations + * @throws {Error} Invalid parameters + */ + withExif(exif: Exif): Sharp; + + /** + * Update EXIF metadata from the input image in the output image. + * @param {Exif} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. + * @returns A sharp instance that can be used to chain operations + * @throws {Error} Invalid parameters + */ + withExifMerge(exif: Exif): Sharp; + + /** + * Keep ICC profile from the input image in the output image where possible. + * @returns A sharp instance that can be used to chain operations + */ + keepIccProfile(): Sharp; + + /** + * Transform using an ICC profile and attach to the output image. + * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk). + * @returns A sharp instance that can be used to chain operations + * @throws {Error} Invalid parameters + */ + withIccProfile(icc: string, options?: WithIccProfileOptions): Sharp; + + /** + * Include all metadata (EXIF, XMP, IPTC) from the input image in the output image. + * The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space. + * This will also convert to and add a web-friendly sRGB ICC profile. + * @param withMetadata + * @throws {Error} Invalid parameters. + */ + withMetadata(withMetadata?: WriteableMetadata): Sharp; + + /** + * Use these JPEG options for output image. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + jpeg(options?: JpegOptions): Sharp; + + /** + * Use these JP2 (JPEG 2000) options for output image. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + jp2(options?: Jp2Options): Sharp; + + /** + * Use these JPEG-XL (JXL) options for output image. + * This feature is experimental, please do not use in production systems. + * Requires libvips compiled with support for libjxl. + * The prebuilt binaries do not include this. + * Image metadata (EXIF, XMP) is unsupported. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + jxl(options?: JxlOptions): Sharp; + + /** + * Use these PNG options for output image. + * PNG output is always full colour at 8 or 16 bits per pixel. + * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + png(options?: PngOptions): Sharp; + + /** + * Use these WebP options for output image. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + webp(options?: WebpOptions): Sharp; + + /** + * Use these GIF options for output image. + * Requires libvips compiled with support for ImageMagick or GraphicsMagick. The prebuilt binaries do not include this - see installing a custom libvips. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + gif(options?: GifOptions): Sharp; + + /** + * Use these AVIF options for output image. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + avif(options?: AvifOptions): Sharp; + + /** + * Use these HEIF options for output image. + * Support for patent-encumbered HEIC images requires the use of a globally-installed libvips compiled with support for libheif, libde265 and x265. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + heif(options?: HeifOptions): Sharp; + + /** + * Use these TIFF options for output image. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + tiff(options?: TiffOptions): Sharp; + + /** + * Force output to be raw, uncompressed uint8 pixel data. + * @param options Raw output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + raw(options?: RawOptions): Sharp; + + /** + * Force output to a given format. + * @param format a String or an Object with an 'id' attribute + * @param options output options + * @throws {Error} Unsupported format or options + * @returns A sharp instance that can be used to chain operations + */ + toFormat( + format: keyof FormatEnum | AvailableFormatInfo, + options?: + | OutputOptions + | JpegOptions + | PngOptions + | WebpOptions + | AvifOptions + | HeifOptions + | JxlOptions + | GifOptions + | Jp2Options + | TiffOptions, + ): Sharp; + + /** + * Use tile-based deep zoom (image pyramid) output. + * Set the format and options for tile images via the toFormat, jpeg, png or webp functions. + * Use a .zip or .szi file extension with toFile to write to a compressed archive file format. + * + * Warning: multiple sharp instances concurrently producing tile output can expose a possible race condition in some versions of libgsf. + * @param tile tile options + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + tile(tile?: TileOptions): Sharp; + + /** + * Set a timeout for processing, in seconds. Use a value of zero to continue processing indefinitely, the default behaviour. + * The clock starts when libvips opens an input image for processing. Time spent waiting for a libuv thread to become available is not included. + * @param options Object with a `seconds` attribute between 0 and 3600 (number) + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + timeout(options: TimeoutOptions): Sharp; + + //#endregion + + //#region Resize functions + + /** + * Resize image to width, height or width x height. + * + * When both a width and height are provided, the possible methods by which the image should fit these are: + * - cover: Crop to cover both provided dimensions (the default). + * - contain: Embed within both provided dimensions. + * - fill: Ignore the aspect ratio of the input and stretch to both provided dimensions. + * - inside: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified. + * - outside: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified. + * Some of these values are based on the object-fit CSS property. + * + * When using a fit of cover or contain, the default position is centre. Other options are: + * - sharp.position: top, right top, right, right bottom, bottom, left bottom, left, left top. + * - sharp.gravity: north, northeast, east, southeast, south, southwest, west, northwest, center or centre. + * - sharp.strategy: cover only, dynamically crop using either the entropy or attention strategy. Some of these values are based on the object-position CSS property. + * + * The experimental strategy-based approach resizes so one dimension is at its target length then repeatedly ranks edge regions, + * discarding the edge with the lowest score based on the selected strategy. + * - entropy: focus on the region with the highest Shannon entropy. + * - attention: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones. + * + * Possible interpolation kernels are: + * - nearest: Use nearest neighbour interpolation. + * - cubic: Use a Catmull-Rom spline. + * - lanczos2: Use a Lanczos kernel with a=2. + * - lanczos3: Use a Lanczos kernel with a=3 (the default). + * + * @param width pixels wide the resultant image should be. Use null or undefined to auto-scale the width to match the height. + * @param height pixels high the resultant image should be. Use null or undefined to auto-scale the height to match the width. + * @param options resize options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + resize(widthOrOptions?: number | ResizeOptions | null, height?: number | null, options?: ResizeOptions): Sharp; + + /** + * Shorthand for resize(null, null, options); + * + * @param options resize options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + resize(options: ResizeOptions): Sharp; + + /** + * Extend / pad / extrude one or more edges of the image with either + * the provided background colour or pixels derived from the image. + * This operation will always occur after resizing and extraction, if any. + * @param extend single pixel count to add to all edges or an Object with per-edge counts + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + extend(extend: number | ExtendOptions): Sharp; + + /** + * Extract a region of the image. + * - Use extract() before resize() for pre-resize extraction. + * - Use extract() after resize() for post-resize extraction. + * - Use extract() before and after for both. + * + * @param region The region to extract + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + extract(region: Region): Sharp; + + /** + * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel. + * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels. + * The info response Object will contain trimOffsetLeft and trimOffsetTop properties. + * @param options trim options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + trim(options?: TrimOptions): Sharp; + + //#endregion + } + + interface SharpOptions { + /** + * When to abort processing of invalid pixel data, one of (in order of sensitivity): + * 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default 'warning') + */ + failOn?: FailOnOptions | undefined; + /** + * By default halt processing and raise an error when loading invalid images. + * Set this flag to false if you'd rather apply a "best effort" to decode images, + * even if the data is corrupt or invalid. (optional, default true) + * + * @deprecated Use `failOn` instead + */ + failOnError?: boolean | undefined; + /** + * Do not process input images where the number of pixels (width x height) exceeds this limit. + * Assumes image dimensions contained in the input metadata can be trusted. + * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default 268402689) + */ + limitInputPixels?: number | boolean | undefined; + /** Set this to true to remove safety features that help prevent memory exhaustion (SVG, PNG). (optional, default false) */ + unlimited?: boolean | undefined; + /** Set this to false to use random access rather than sequential read. Some operations will do this automatically. */ + sequentialRead?: boolean | undefined; + /** Number representing the DPI for vector images in the range 1 to 100000. (optional, default 72) */ + density?: number | undefined; + /** Should the embedded ICC profile, if any, be ignored. */ + ignoreIcc?: boolean | undefined; + /** Number of pages to extract for multi-page input (GIF, TIFF, PDF), use -1 for all pages */ + pages?: number | undefined; + /** Page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based. (optional, default 0) */ + page?: number | undefined; + /** subIFD (Sub Image File Directory) to extract for OME-TIFF, defaults to main image. (optional, default -1) */ + subifd?: number | undefined; + /** Level to extract from a multi-level input (OpenSlide), zero based. (optional, default 0) */ + level?: number | undefined; + /** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default false) */ + animated?: boolean | undefined; + /** Describes raw pixel input image data. See raw() for pixel ordering. */ + raw?: CreateRaw | undefined; + /** Describes a new image to be created. */ + create?: Create | undefined; + /** Describes a new text image to be created. */ + text?: CreateText | undefined; + } + + interface CacheOptions { + /** Is the maximum memory in MB to use for this cache (optional, default 50) */ + memory?: number | undefined; + /** Is the maximum number of files to hold open (optional, default 20) */ + files?: number | undefined; + /** Is the maximum number of operations to cache (optional, default 100) */ + items?: number | undefined; + } + + interface TimeoutOptions { + /** Number of seconds after which processing will be stopped (default 0, eg disabled) */ + seconds: number; + } + + interface SharpCounters { + /** The number of tasks this module has queued waiting for libuv to provide a worker thread from its pool. */ + queue: number; + /** The number of resize tasks currently being processed. */ + process: number; + } + + interface Raw { + width: number; + height: number; + channels: 1 | 2 | 3 | 4; + } + + interface CreateRaw extends Raw { + /** Specifies that the raw input has already been premultiplied, set to true to avoid sharp premultiplying the image. (optional, default false) */ + premultiplied?: boolean | undefined; + } + + interface Create { + /** Number of pixels wide. */ + width: number; + /** Number of pixels high. */ + height: number; + /** Number of bands e.g. 3 for RGB, 4 for RGBA */ + channels: Channels; + /** Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. */ + background: Color; + /** Describes a noise to be created. */ + noise?: Noise | undefined; + } + + interface CreateText { + /** Text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. */ + text: string; + /** Font name to render with. */ + font?: string; + /** Absolute filesystem path to a font file that can be used by `font`. */ + fontfile?: string; + /** Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`) */ + width?: number; + /** + * Integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution + * defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`) + */ + height?: number; + /** Text alignment ('left', 'centre', 'center', 'right'). (optional, default 'left') */ + align?: TextAlign; + /** Set this to true to apply justification to the text. (optional, default `false`) */ + justify?: boolean; + /** The resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`) */ + dpi?: number; + /** + * Set this to true to enable RGBA output. This is useful for colour emoji rendering, + * or support for pango markup features like `Red!`. (optional, default `false`) + */ + rgba?: boolean; + /** Text line height in points. Will use the font line height if none is specified. (optional, default `0`) */ + spacing?: number; + /** Word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none' */ + wrap?: TextWrap; + } + + interface ExifDir { + [k: string]: string; + } + + interface Exif { + 'IFD0'?: ExifDir; + 'IFD1'?: ExifDir; + 'IFD2'?: ExifDir; + 'IFD3'?: ExifDir; + } + + interface WriteableMetadata { + /** Number of pixels per inch (DPI) */ + density?: number | undefined; + /** Value between 1 and 8, used to update the EXIF Orientation tag. */ + orientation?: number | undefined; + /** + * Filesystem path to output ICC profile, defaults to sRGB. + * @deprecated Use `withIccProfile()` instead. + */ + icc?: string | undefined; + /** + * Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. + * @deprecated Use `withExif()` or `withExifMerge()` instead. + */ + exif?: Exif | undefined; + } + + interface Metadata { + /** Number value of the EXIF Orientation header, if present */ + orientation?: number | undefined; + /** Name of decoder used to decompress image data e.g. jpeg, png, webp, gif, svg */ + format?: keyof FormatEnum | undefined; + /** Total size of image in bytes, for Stream and Buffer input only */ + size?: number | undefined; + /** Number of pixels wide (EXIF orientation is not taken into consideration) */ + width?: number | undefined; + /** Number of pixels high (EXIF orientation is not taken into consideration) */ + height?: number | undefined; + /** Name of colour space interpretation */ + space?: keyof ColourspaceEnum | undefined; + /** Number of bands e.g. 3 for sRGB, 4 for CMYK */ + channels?: Channels | undefined; + /** Name of pixel depth format e.g. uchar, char, ushort, float ... */ + depth?: string | undefined; + /** Number of pixels per inch (DPI), if present */ + density?: number | undefined; + /** String containing JPEG chroma subsampling, 4:2:0 or 4:4:4 for RGB, 4:2:0:4 or 4:4:4:4 for CMYK */ + chromaSubsampling?: string | undefined; + /** Boolean indicating whether the image is interlaced using a progressive scan */ + isProgressive?: boolean | undefined; + /** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */ + pages?: number | undefined; + /** Number of pixels high each page in a multi-page image will be. */ + pageHeight?: number | undefined; + /** Number of times to loop an animated image, zero refers to a continuous loop. */ + loop?: number | undefined; + /** Delay in ms between each page in an animated image, provided as an array of integers. */ + delay?: number[] | undefined; + /** Number of the primary page in a HEIF image */ + pagePrimary?: number | undefined; + /** Boolean indicating the presence of an embedded ICC profile */ + hasProfile?: boolean | undefined; + /** Boolean indicating the presence of an alpha transparency channel */ + hasAlpha?: boolean | undefined; + /** Buffer containing raw EXIF data, if present */ + exif?: Buffer | undefined; + /** Buffer containing raw ICC profile data, if present */ + icc?: Buffer | undefined; + /** Buffer containing raw IPTC data, if present */ + iptc?: Buffer | undefined; + /** Buffer containing raw XMP data, if present */ + xmp?: Buffer | undefined; + /** Buffer containing raw TIFFTAG_PHOTOSHOP data, if present */ + tifftagPhotoshop?: Buffer | undefined; + /** The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) */ + compression?: 'av1' | 'hevc'; + /** Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value */ + background?: { r: number; g: number; b: number } | number; + /** Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide */ + levels?: LevelMetadata[] | undefined; + /** Number of Sub Image File Directories in an OME-TIFF image */ + subifds?: number | undefined; + /** The unit of resolution (density) */ + resolutionUnit?: 'inch' | 'cm' | undefined; + /** String containing format for images loaded via *magick */ + formatMagick?: string | undefined; + /** Array of keyword/text pairs representing PNG text blocks, if present. */ + comments?: CommentsMetadata[] | undefined; + } + + interface LevelMetadata { + width: number; + height: number; + } + + interface CommentsMetadata { + keyword: string; + text: string; + } + + interface Stats { + /** Array of channel statistics for each channel in the image. */ + channels: ChannelStats[]; + /** Value to identify if the image is opaque or transparent, based on the presence and use of alpha channel */ + isOpaque: boolean; + /** Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental) */ + entropy: number; + /** Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental) */ + sharpness: number; + /** Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental) */ + dominant: { r: number; g: number; b: number }; + } + + interface ChannelStats { + /** minimum value in the channel */ + min: number; + /** maximum value in the channel */ + max: number; + /** sum of all values in a channel */ + sum: number; + /** sum of squared values in a channel */ + squaresSum: number; + /** mean of the values in a channel */ + mean: number; + /** standard deviation for the values in a channel */ + stdev: number; + /** x-coordinate of one of the pixel where the minimum lies */ + minX: number; + /** y-coordinate of one of the pixel where the minimum lies */ + minY: number; + /** x-coordinate of one of the pixel where the maximum lies */ + maxX: number; + /** y-coordinate of one of the pixel where the maximum lies */ + maxY: number; + } + + interface OutputOptions { + /** Force format output, otherwise attempt to use input format (optional, default true) */ + force?: boolean | undefined; + } + + interface WithIccProfileOptions { + /** Should the ICC profile be included in the output image metadata? (optional, default true) */ + attach?: boolean | undefined; + } + + interface JpegOptions extends OutputOptions { + /** Quality, integer 1-100 (optional, default 80) */ + quality?: number | undefined; + /** Use progressive (interlace) scan (optional, default false) */ + progressive?: boolean | undefined; + /** Set to '4:4:4' to prevent chroma subsampling when quality <= 90 (optional, default '4:2:0') */ + chromaSubsampling?: string | undefined; + /** Apply trellis quantisation (optional, default false) */ + trellisQuantisation?: boolean | undefined; + /** Apply overshoot deringing (optional, default false) */ + overshootDeringing?: boolean | undefined; + /** Optimise progressive scans, forces progressive (optional, default false) */ + optimiseScans?: boolean | undefined; + /** Alternative spelling of optimiseScans (optional, default false) */ + optimizeScans?: boolean | undefined; + /** Optimise Huffman coding tables (optional, default true) */ + optimiseCoding?: boolean | undefined; + /** Alternative spelling of optimiseCoding (optional, default true) */ + optimizeCoding?: boolean | undefined; + /** Quantization table to use, integer 0-8 (optional, default 0) */ + quantisationTable?: number | undefined; + /** Alternative spelling of quantisationTable (optional, default 0) */ + quantizationTable?: number | undefined; + /** Use mozjpeg defaults (optional, default false) */ + mozjpeg?: boolean | undefined; + } + + interface Jp2Options extends OutputOptions { + /** Quality, integer 1-100 (optional, default 80) */ + quality?: number; + /** Use lossless compression mode (optional, default false) */ + lossless?: boolean; + /** Horizontal tile size (optional, default 512) */ + tileWidth?: number; + /** Vertical tile size (optional, default 512) */ + tileHeight?: number; + /** Set to '4:2:0' to enable chroma subsampling (optional, default '4:4:4') */ + chromaSubsampling?: '4:4:4' | '4:2:0'; + } + + interface JxlOptions extends OutputOptions { + /** Maximum encoding error, between 0 (highest quality) and 15 (lowest quality) (optional, default 1.0) */ + distance?: number; + /** Calculate distance based on JPEG-like quality, between 1 and 100, overrides distance if specified */ + quality?: number; + /** Target decode speed tier, between 0 (highest quality) and 4 (lowest quality) (optional, default 0) */ + decodingTier?: number; + /** Use lossless compression (optional, default false) */ + lossless?: boolean; + /** CPU effort, between 3 (fastest) and 9 (slowest) (optional, default 7) */ + effort?: number | undefined; + } + + interface WebpOptions extends OutputOptions, AnimationOptions { + /** Quality, integer 1-100 (optional, default 80) */ + quality?: number | undefined; + /** Quality of alpha layer, number from 0-100 (optional, default 100) */ + alphaQuality?: number | undefined; + /** Use lossless compression mode (optional, default false) */ + lossless?: boolean | undefined; + /** Use near_lossless compression mode (optional, default false) */ + nearLossless?: boolean | undefined; + /** Use high quality chroma subsampling (optional, default false) */ + smartSubsample?: boolean | undefined; + /** Level of CPU effort to reduce file size, integer 0-6 (optional, default 4) */ + effort?: number | undefined; + /** Prevent use of animation key frames to minimise file size (slow) (optional, default false) */ + minSize?: boolean; + /** Allow mixture of lossy and lossless animation frames (slow) (optional, default false) */ + mixed?: boolean; + /** Preset options: one of default, photo, picture, drawing, icon, text (optional, default 'default') */ + preset?: keyof PresetEnum | undefined; + } + + interface AvifOptions extends OutputOptions { + /** quality, integer 1-100 (optional, default 50) */ + quality?: number | undefined; + /** use lossless compression (optional, default false) */ + lossless?: boolean | undefined; + /** Level of CPU effort to reduce file size, between 0 (fastest) and 9 (slowest) (optional, default 4) */ + effort?: number | undefined; + /** set to '4:2:0' to use chroma subsampling, requires libvips v8.11.0 (optional, default '4:4:4') */ + chromaSubsampling?: string | undefined; + /** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */ + bitdepth?: 8 | 10 | 12 | undefined; + } + + interface HeifOptions extends OutputOptions { + /** quality, integer 1-100 (optional, default 50) */ + quality?: number | undefined; + /** compression format: av1, hevc (optional, default 'av1') */ + compression?: 'av1' | 'hevc' | undefined; + /** use lossless compression (optional, default false) */ + lossless?: boolean | undefined; + /** Level of CPU effort to reduce file size, between 0 (fastest) and 9 (slowest) (optional, default 4) */ + effort?: number | undefined; + /** set to '4:2:0' to use chroma subsampling (optional, default '4:4:4') */ + chromaSubsampling?: string | undefined; + /** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */ + bitdepth?: 8 | 10 | 12 | undefined; + } + + interface GifOptions extends OutputOptions, AnimationOptions { + /** Re-use existing palette, otherwise generate new (slow) */ + reuse?: boolean | undefined; + /** Use progressive (interlace) scan */ + progressive?: boolean | undefined; + /** Maximum number of palette entries, including transparency, between 2 and 256 (optional, default 256) */ + colours?: number | undefined; + /** Alternative spelling of "colours". Maximum number of palette entries, including transparency, between 2 and 256 (optional, default 256) */ + colors?: number | undefined; + /** Level of CPU effort to reduce file size, between 1 (fastest) and 10 (slowest) (optional, default 7) */ + effort?: number | undefined; + /** Level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default 1.0) */ + dither?: number | undefined; + /** Maximum inter-frame error for transparency, between 0 (lossless) and 32 (optional, default 0) */ + interFrameMaxError?: number; + /** Maximum inter-palette error for palette reuse, between 0 and 256 (optional, default 3) */ + interPaletteMaxError?: number; + } + + interface TiffOptions extends OutputOptions { + /** Quality, integer 1-100 (optional, default 80) */ + quality?: number | undefined; + /** Compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k (optional, default 'jpeg') */ + compression?: string | undefined; + /** Compression predictor options: none, horizontal, float (optional, default 'horizontal') */ + predictor?: string | undefined; + /** Write an image pyramid (optional, default false) */ + pyramid?: boolean | undefined; + /** Write a tiled tiff (optional, default false) */ + tile?: boolean | undefined; + /** Horizontal tile size (optional, default 256) */ + tileWidth?: number | undefined; + /** Vertical tile size (optional, default 256) */ + tileHeight?: number | undefined; + /** Horizontal resolution in pixels/mm (optional, default 1.0) */ + xres?: number | undefined; + /** Vertical resolution in pixels/mm (optional, default 1.0) */ + yres?: number | undefined; + /** Reduce bitdepth to 1, 2 or 4 bit (optional, default 8) */ + bitdepth?: 1 | 2 | 4 | 8 | undefined; + /** Write 1-bit images as miniswhite (optional, default false) */ + miniswhite?: boolean | undefined; + /** Resolution unit options: inch, cm (optional, default 'inch') */ + resolutionUnit?: 'inch' | 'cm' | undefined; + } + + interface PngOptions extends OutputOptions { + /** Use progressive (interlace) scan (optional, default false) */ + progressive?: boolean | undefined; + /** zlib compression level, 0-9 (optional, default 6) */ + compressionLevel?: number | undefined; + /** Use adaptive row filtering (optional, default false) */ + adaptiveFiltering?: boolean | undefined; + /** Use the lowest number of colours needed to achieve given quality (optional, default `100`) */ + quality?: number | undefined; + /** Level of CPU effort to reduce file size, between 1 (fastest) and 10 (slowest), sets palette to true (optional, default 7) */ + effort?: number | undefined; + /** Quantise to a palette-based image with alpha transparency support (optional, default false) */ + palette?: boolean | undefined; + /** Maximum number of palette entries (optional, default 256) */ + colours?: number | undefined; + /** Alternative Spelling of "colours". Maximum number of palette entries (optional, default 256) */ + colors?: number | undefined; + /** Level of Floyd-Steinberg error diffusion (optional, default 1.0) */ + dither?: number | undefined; + } + + interface RotateOptions { + /** parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */ + background?: Color | undefined; + } + + type Precision = 'integer' | 'float' | 'approximate'; + + interface BlurOptions { + /** A value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2` */ + sigma: number; + /** A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. */ + minAmplitude?: number; + /** How accurate the operation should be, one of: integer, float, approximate. (optional, default "integer") */ + precision?: Precision | undefined; + } + + interface FlattenOptions { + /** background colour, parsed by the color module, defaults to black. (optional, default {r:0,g:0,b:0}) */ + background?: Color | undefined; + } + + interface NegateOptions { + /** whether or not to negate any alpha channel. (optional, default true) */ + alpha?: boolean | undefined; + } + + interface NormaliseOptions { + /** Percentile below which luminance values will be underexposed. */ + lower?: number | undefined; + /** Percentile above which luminance values will be overexposed. */ + upper?: number | undefined; + } + + interface ResizeOptions { + /** Alternative means of specifying width. If both are present this takes priority. */ + width?: number | undefined; + /** Alternative means of specifying height. If both are present this takes priority. */ + height?: number | undefined; + /** How the image should be resized to fit both provided dimensions, one of cover, contain, fill, inside or outside. (optional, default 'cover') */ + fit?: keyof FitEnum | undefined; + /** Position, gravity or strategy to use when fit is cover or contain. (optional, default 'centre') */ + position?: number | string | undefined; + /** Background colour when using a fit of contain, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */ + background?: Color | undefined; + /** The kernel to use for image reduction. (optional, default 'lanczos3') */ + kernel?: keyof KernelEnum | undefined; + /** Do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's > geometry option. (optional, default false) */ + withoutEnlargement?: boolean | undefined; + /** Do not reduce if the width or height are already greater than the specified dimensions, equivalent to GraphicsMagick's < geometry option. (optional, default false) */ + withoutReduction?: boolean | undefined; + /** Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default true) */ + fastShrinkOnLoad?: boolean | undefined; + } + + interface Region { + /** zero-indexed offset from left edge */ + left: number; + /** zero-indexed offset from top edge */ + top: number; + /** dimension of extracted image */ + width: number; + /** dimension of extracted image */ + height: number; + } + + interface Noise { + /** type of generated noise, currently only gaussian is supported. */ + type?: 'gaussian' | undefined; + /** mean of pixels in generated noise. */ + mean?: number | undefined; + /** standard deviation of pixels in generated noise. */ + sigma?: number | undefined; + } + + type ExtendWith = 'background' | 'copy' | 'repeat' | 'mirror'; + + interface ExtendOptions { + /** single pixel count to top edge (optional, default 0) */ + top?: number | undefined; + /** single pixel count to left edge (optional, default 0) */ + left?: number | undefined; + /** single pixel count to bottom edge (optional, default 0) */ + bottom?: number | undefined; + /** single pixel count to right edge (optional, default 0) */ + right?: number | undefined; + /** background colour, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */ + background?: Color | undefined; + /** how the extension is done, one of: "background", "copy", "repeat", "mirror" (optional, default `'background'`) */ + extendWith?: ExtendWith | undefined; + } + + interface TrimOptions { + /** Background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */ + background?: Color | undefined; + /** Allowed difference from the above colour, a positive number. (optional, default 10) */ + threshold?: number | undefined; + /** Does the input more closely resemble line art (e.g. vector) rather than being photographic? (optional, default false) */ + lineArt?: boolean | undefined; + } + + interface RawOptions { + depth?: 'char' | 'uchar' | 'short' | 'ushort' | 'int' | 'uint' | 'float' | 'complex' | 'double' | 'dpcomplex'; + } + + /** 3 for sRGB, 4 for CMYK */ + type Channels = 3 | 4; + + interface RGBA { + r?: number | undefined; + g?: number | undefined; + b?: number | undefined; + alpha?: number | undefined; + } + + type Color = string | RGBA; + + interface Kernel { + /** width of the kernel in pixels. */ + width: number; + /** height of the kernel in pixels. */ + height: number; + /** Array of length width*height containing the kernel values. */ + kernel: ArrayLike; + /** the scale of the kernel in pixels. (optional, default sum) */ + scale?: number | undefined; + /** the offset of the kernel in pixels. (optional, default 0) */ + offset?: number | undefined; + } + + interface ClaheOptions { + /** width of the region */ + width: number; + /** height of the region */ + height: number; + /** max slope of the cumulative contrast. A value of 0 disables contrast limiting. Valid values are integers in the range 0-100 (inclusive) (optional, default 3) */ + maxSlope?: number | undefined; + } + + interface ThresholdOptions { + /** convert to single channel greyscale. (optional, default true) */ + greyscale?: boolean | undefined; + /** alternative spelling for greyscale. (optional, default true) */ + grayscale?: boolean | undefined; + } + + interface OverlayOptions extends SharpOptions { + /** Buffer containing image data, String containing the path to an image file, or Create object */ + input?: string | Buffer | { create: Create } | { text: CreateText } | { raw: CreateRaw } | undefined; + /** how to blend this image with the image below. (optional, default `'over'`) */ + blend?: Blend | undefined; + /** gravity at which to place the overlay. (optional, default 'centre') */ + gravity?: Gravity | undefined; + /** the pixel offset from the top edge. */ + top?: number | undefined; + /** the pixel offset from the left edge. */ + left?: number | undefined; + /** set to true to repeat the overlay image across the entire image with the given gravity. (optional, default false) */ + tile?: boolean | undefined; + /** Set to true to avoid premultipling the image below. Equivalent to the --premultiplied vips option. */ + premultiplied?: boolean | undefined; + /** number representing the DPI for vector overlay image. (optional, default 72)*/ + density?: number | undefined; + /** Set to true to read all frames/pages of an animated image. (optional, default false) */ + animated?: boolean | undefined; + /** see sharp() constructor, (optional, default 'warning') */ + failOn?: FailOnOptions | undefined; + /** see sharp() constructor, (optional, default 268402689) */ + limitInputPixels?: number | boolean | undefined; + } + + interface TileOptions { + /** Tile size in pixels, a value between 1 and 8192. (optional, default 256) */ + size?: number | undefined; + /** Tile overlap in pixels, a value between 0 and 8192. (optional, default 0) */ + overlap?: number | undefined; + /** Tile angle of rotation, must be a multiple of 90. (optional, default 0) */ + angle?: number | undefined; + /** background colour, parsed by the color module, defaults to white without transparency. (optional, default {r:255,g:255,b:255,alpha:1}) */ + background?: string | RGBA | undefined; + /** How deep to make the pyramid, possible values are "onepixel", "onetile" or "one" (default based on layout) */ + depth?: string | undefined; + /** Threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images */ + skipBlanks?: number | undefined; + /** Tile container, with value fs (filesystem) or zip (compressed file). (optional, default 'fs') */ + container?: TileContainer | undefined; + /** Filesystem layout, possible values are dz, iiif, iiif3, zoomify or google. (optional, default 'dz') */ + layout?: TileLayout | undefined; + /** Centre image in tile. (optional, default false) */ + centre?: boolean | undefined; + /** Alternative spelling of centre. (optional, default false) */ + center?: boolean | undefined; + /** When layout is iiif/iiif3, sets the @id/id attribute of info.json (optional, default 'https://example.com/iiif') */ + id?: string | undefined; + /** The name of the directory within the zip file when container is `zip`. */ + basename?: string | undefined; + } + + interface AnimationOptions { + /** Number of animation iterations, a value between 0 and 65535. Use 0 for infinite animation. (optional, default 0) */ + loop?: number | undefined; + /** delay(s) between animation frames (in milliseconds), each value between 0 and 65535. (optional) */ + delay?: number | number[] | undefined; + } + + interface SharpenOptions { + /** The sigma of the Gaussian mask, where sigma = 1 + radius / 2, between 0.000001 and 10000 */ + sigma: number; + /** The level of sharpening to apply to "flat" areas, between 0 and 1000000 (optional, default 1.0) */ + m1?: number | undefined; + /** The level of sharpening to apply to "jagged" areas, between 0 and 1000000 (optional, default 2.0) */ + m2?: number | undefined; + /** Threshold between "flat" and "jagged", between 0 and 1000000 (optional, default 2.0) */ + x1?: number | undefined; + /** Maximum amount of brightening, between 0 and 1000000 (optional, default 10.0) */ + y2?: number | undefined; + /** Maximum amount of darkening, between 0 and 1000000 (optional, default 20.0) */ + y3?: number | undefined; + } + + interface AffineOptions { + /** Parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */ + background?: string | object | undefined; + /** Input horizontal offset (optional, default 0) */ + idx?: number | undefined; + /** Input vertical offset (optional, default 0) */ + idy?: number | undefined; + /** Output horizontal offset (optional, default 0) */ + odx?: number | undefined; + /** Output horizontal offset (optional, default 0) */ + ody?: number | undefined; + /** Interpolator (optional, default sharp.interpolators.bicubic) */ + interpolator?: Interpolators[keyof Interpolators] | undefined; + } + + interface OutputInfo { + format: string; + size: number; + width: number; + height: number; + channels: 1 | 2 | 3 | 4; + /** indicating if premultiplication was used */ + premultiplied: boolean; + /** Only defined when using a crop strategy */ + cropOffsetLeft?: number | undefined; + /** Only defined when using a crop strategy */ + cropOffsetTop?: number | undefined; + /** Only defined when using a trim method */ + trimOffsetLeft?: number | undefined; + /** Only defined when using a trim method */ + trimOffsetTop?: number | undefined; + /** DPI the font was rendered at, only defined when using `text` input */ + textAutofitDpi?: number | undefined; + /** When using the attention crop strategy, the focal point of the cropped region */ + attentionX?: number | undefined; + attentionY?: number | undefined; + } + + interface AvailableFormatInfo { + id: string; + input: { file: boolean; buffer: boolean; stream: boolean; fileSuffix?: string[] }; + output: { file: boolean; buffer: boolean; stream: boolean; alias?: string[] }; + } + + interface FitEnum { + contain: 'contain'; + cover: 'cover'; + fill: 'fill'; + inside: 'inside'; + outside: 'outside'; + } + + interface KernelEnum { + nearest: 'nearest'; + cubic: 'cubic'; + mitchell: 'mitchell'; + lanczos2: 'lanczos2'; + lanczos3: 'lanczos3'; + } + + interface PresetEnum { + default: 'default'; + picture: 'picture'; + photo: 'photo'; + drawing: 'drawing'; + icon: 'icon'; + text: 'text'; + } + + interface BoolEnum { + and: 'and'; + or: 'or'; + eor: 'eor'; + } + + interface ColourspaceEnum { + multiband: string; + 'b-w': string; + bw: string; + cmyk: string; + srgb: string; + } + + type FailOnOptions = 'none' | 'truncated' | 'error' | 'warning'; + + type TextAlign = 'left' | 'centre' | 'center' | 'right'; + + type TextWrap = 'word' | 'char' | 'word-char' | 'none'; + + type TileContainer = 'fs' | 'zip'; + + type TileLayout = 'dz' | 'iiif' | 'iiif3' | 'zoomify' | 'google'; + + type Blend = + | 'clear' + | 'source' + | 'over' + | 'in' + | 'out' + | 'atop' + | 'dest' + | 'dest-over' + | 'dest-in' + | 'dest-out' + | 'dest-atop' + | 'xor' + | 'add' + | 'saturate' + | 'multiply' + | 'screen' + | 'overlay' + | 'darken' + | 'lighten' + | 'color-dodge' + | 'colour-dodge' + | 'color-burn' + | 'colour-burn' + | 'hard-light' + | 'soft-light' + | 'difference' + | 'exclusion'; + + type Gravity = number | string; + + interface GravityEnum { + north: number; + northeast: number; + southeast: number; + south: number; + southwest: number; + west: number; + northwest: number; + east: number; + center: number; + centre: number; + } + + interface StrategyEnum { + entropy: number; + attention: number; + } + + interface FormatEnum { + avif: AvailableFormatInfo; + dz: AvailableFormatInfo; + fits: AvailableFormatInfo; + gif: AvailableFormatInfo; + heif: AvailableFormatInfo; + input: AvailableFormatInfo; + jpeg: AvailableFormatInfo; + jpg: AvailableFormatInfo; + jp2: AvailableFormatInfo; + jxl: AvailableFormatInfo; + magick: AvailableFormatInfo; + openslide: AvailableFormatInfo; + pdf: AvailableFormatInfo; + png: AvailableFormatInfo; + ppm: AvailableFormatInfo; + raw: AvailableFormatInfo; + svg: AvailableFormatInfo; + tiff: AvailableFormatInfo; + tif: AvailableFormatInfo; + v: AvailableFormatInfo; + webp: AvailableFormatInfo; + } + + interface CacheResult { + memory: { current: number; high: number; max: number }; + files: { current: number; max: number }; + items: { current: number; max: number }; + } + + interface Interpolators { + /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */ + nearest: 'nearest'; + /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */ + bilinear: 'bilinear'; + /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */ + bicubic: 'bicubic'; + /** + * [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). + * Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. + */ + locallyBoundedBicubic: 'lbb'; + /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */ + nohalo: 'nohalo'; + /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */ + vertexSplitQuadraticBasisSpline: 'vsqbs'; + } + + type Matrix2x2 = [[number, number], [number, number]]; + type Matrix3x3 = [[number, number, number], [number, number, number], [number, number, number]]; + type Matrix4x4 = [[number, number, number, number], [number, number, number, number], [number, number, number, number], [number, number, number, number]]; +} + +export = sharp; diff --git a/node_modules/sharp/lib/index.js b/node_modules/sharp/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8cfc08a80d67639b655cc21043ea75e60013f45d --- /dev/null +++ b/node_modules/sharp/lib/index.js @@ -0,0 +1,16 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const Sharp = require('./constructor'); +require('./input')(Sharp); +require('./resize')(Sharp); +require('./composite')(Sharp); +require('./operation')(Sharp); +require('./colour')(Sharp); +require('./channel')(Sharp); +require('./output')(Sharp); +require('./utility')(Sharp); + +module.exports = Sharp; diff --git a/node_modules/sharp/lib/input.js b/node_modules/sharp/lib/input.js new file mode 100644 index 0000000000000000000000000000000000000000..93d4e7411879eaedf4016db9fc23db1378aa7918 --- /dev/null +++ b/node_modules/sharp/lib/input.js @@ -0,0 +1,658 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const color = require('color'); +const is = require('./is'); +const sharp = require('./sharp'); + +/** + * Justication alignment + * @member + * @private + */ +const align = { + left: 'low', + center: 'centre', + centre: 'centre', + right: 'high' +}; + +/** + * Extract input options, if any, from an object. + * @private + */ +function _inputOptionsFromObject (obj) { + const { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } = obj; + return [raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd].some(is.defined) + ? { raw, density, limitInputPixels, ignoreIcc, unlimited, sequentialRead, failOn, failOnError, animated, page, pages, subifd } + : undefined; +} + +/** + * Create Object containing input and input-related options. + * @private + */ +function _createInputDescriptor (input, inputOptions, containerOptions) { + const inputDescriptor = { + failOn: 'warning', + limitInputPixels: Math.pow(0x3FFF, 2), + ignoreIcc: false, + unlimited: false, + sequentialRead: true + }; + if (is.string(input)) { + // filesystem + inputDescriptor.file = input; + } else if (is.buffer(input)) { + // Buffer + if (input.length === 0) { + throw Error('Input Buffer is empty'); + } + inputDescriptor.buffer = input; + } else if (is.arrayBuffer(input)) { + if (input.byteLength === 0) { + throw Error('Input bit Array is empty'); + } + inputDescriptor.buffer = Buffer.from(input, 0, input.byteLength); + } else if (is.typedArray(input)) { + if (input.length === 0) { + throw Error('Input Bit Array is empty'); + } + inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength); + } else if (is.plainObject(input) && !is.defined(inputOptions)) { + // Plain Object descriptor, e.g. create + inputOptions = input; + if (_inputOptionsFromObject(inputOptions)) { + // Stream with options + inputDescriptor.buffer = []; + } + } else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) { + // Stream without options + inputDescriptor.buffer = []; + } else { + throw new Error(`Unsupported input '${input}' of type ${typeof input}${ + is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : '' + }`); + } + if (is.object(inputOptions)) { + // Deprecated: failOnError + if (is.defined(inputOptions.failOnError)) { + if (is.bool(inputOptions.failOnError)) { + inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none'; + } else { + throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError); + } + } + // failOn + if (is.defined(inputOptions.failOn)) { + if (is.string(inputOptions.failOn) && is.inArray(inputOptions.failOn, ['none', 'truncated', 'error', 'warning'])) { + inputDescriptor.failOn = inputOptions.failOn; + } else { + throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn); + } + } + // Density + if (is.defined(inputOptions.density)) { + if (is.inRange(inputOptions.density, 1, 100000)) { + inputDescriptor.density = inputOptions.density; + } else { + throw is.invalidParameterError('density', 'number between 1 and 100000', inputOptions.density); + } + } + // Ignore embeddded ICC profile + if (is.defined(inputOptions.ignoreIcc)) { + if (is.bool(inputOptions.ignoreIcc)) { + inputDescriptor.ignoreIcc = inputOptions.ignoreIcc; + } else { + throw is.invalidParameterError('ignoreIcc', 'boolean', inputOptions.ignoreIcc); + } + } + // limitInputPixels + if (is.defined(inputOptions.limitInputPixels)) { + if (is.bool(inputOptions.limitInputPixels)) { + inputDescriptor.limitInputPixels = inputOptions.limitInputPixels + ? Math.pow(0x3FFF, 2) + : 0; + } else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) { + inputDescriptor.limitInputPixels = inputOptions.limitInputPixels; + } else { + throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels); + } + } + // unlimited + if (is.defined(inputOptions.unlimited)) { + if (is.bool(inputOptions.unlimited)) { + inputDescriptor.unlimited = inputOptions.unlimited; + } else { + throw is.invalidParameterError('unlimited', 'boolean', inputOptions.unlimited); + } + } + // sequentialRead + if (is.defined(inputOptions.sequentialRead)) { + if (is.bool(inputOptions.sequentialRead)) { + inputDescriptor.sequentialRead = inputOptions.sequentialRead; + } else { + throw is.invalidParameterError('sequentialRead', 'boolean', inputOptions.sequentialRead); + } + } + // Raw pixel input + if (is.defined(inputOptions.raw)) { + if ( + is.object(inputOptions.raw) && + is.integer(inputOptions.raw.width) && inputOptions.raw.width > 0 && + is.integer(inputOptions.raw.height) && inputOptions.raw.height > 0 && + is.integer(inputOptions.raw.channels) && is.inRange(inputOptions.raw.channels, 1, 4) + ) { + inputDescriptor.rawWidth = inputOptions.raw.width; + inputDescriptor.rawHeight = inputOptions.raw.height; + inputDescriptor.rawChannels = inputOptions.raw.channels; + inputDescriptor.rawPremultiplied = !!inputOptions.raw.premultiplied; + + switch (input.constructor) { + case Uint8Array: + case Uint8ClampedArray: + inputDescriptor.rawDepth = 'uchar'; + break; + case Int8Array: + inputDescriptor.rawDepth = 'char'; + break; + case Uint16Array: + inputDescriptor.rawDepth = 'ushort'; + break; + case Int16Array: + inputDescriptor.rawDepth = 'short'; + break; + case Uint32Array: + inputDescriptor.rawDepth = 'uint'; + break; + case Int32Array: + inputDescriptor.rawDepth = 'int'; + break; + case Float32Array: + inputDescriptor.rawDepth = 'float'; + break; + case Float64Array: + inputDescriptor.rawDepth = 'double'; + break; + default: + inputDescriptor.rawDepth = 'uchar'; + break; + } + } else { + throw new Error('Expected width, height and channels for raw pixel input'); + } + } + // Multi-page input (GIF, TIFF, PDF) + if (is.defined(inputOptions.animated)) { + if (is.bool(inputOptions.animated)) { + inputDescriptor.pages = inputOptions.animated ? -1 : 1; + } else { + throw is.invalidParameterError('animated', 'boolean', inputOptions.animated); + } + } + if (is.defined(inputOptions.pages)) { + if (is.integer(inputOptions.pages) && is.inRange(inputOptions.pages, -1, 100000)) { + inputDescriptor.pages = inputOptions.pages; + } else { + throw is.invalidParameterError('pages', 'integer between -1 and 100000', inputOptions.pages); + } + } + if (is.defined(inputOptions.page)) { + if (is.integer(inputOptions.page) && is.inRange(inputOptions.page, 0, 100000)) { + inputDescriptor.page = inputOptions.page; + } else { + throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page); + } + } + // Multi-level input (OpenSlide) + if (is.defined(inputOptions.level)) { + if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) { + inputDescriptor.level = inputOptions.level; + } else { + throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level); + } + } + // Sub Image File Directory (TIFF) + if (is.defined(inputOptions.subifd)) { + if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) { + inputDescriptor.subifd = inputOptions.subifd; + } else { + throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd); + } + } + // Create new image + if (is.defined(inputOptions.create)) { + if ( + is.object(inputOptions.create) && + is.integer(inputOptions.create.width) && inputOptions.create.width > 0 && + is.integer(inputOptions.create.height) && inputOptions.create.height > 0 && + is.integer(inputOptions.create.channels) + ) { + inputDescriptor.createWidth = inputOptions.create.width; + inputDescriptor.createHeight = inputOptions.create.height; + inputDescriptor.createChannels = inputOptions.create.channels; + // Noise + if (is.defined(inputOptions.create.noise)) { + if (!is.object(inputOptions.create.noise)) { + throw new Error('Expected noise to be an object'); + } + if (!is.inArray(inputOptions.create.noise.type, ['gaussian'])) { + throw new Error('Only gaussian noise is supported at the moment'); + } + if (!is.inRange(inputOptions.create.channels, 1, 4)) { + throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels); + } + inputDescriptor.createNoiseType = inputOptions.create.noise.type; + if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) { + inputDescriptor.createNoiseMean = inputOptions.create.noise.mean; + } else { + throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean); + } + if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) { + inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma; + } else { + throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma); + } + } else if (is.defined(inputOptions.create.background)) { + if (!is.inRange(inputOptions.create.channels, 3, 4)) { + throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels); + } + const background = color(inputOptions.create.background); + inputDescriptor.createBackground = [ + background.red(), + background.green(), + background.blue(), + Math.round(background.alpha() * 255) + ]; + } else { + throw new Error('Expected valid noise or background to create a new input image'); + } + delete inputDescriptor.buffer; + } else { + throw new Error('Expected valid width, height and channels to create a new input image'); + } + } + // Create a new image with text + if (is.defined(inputOptions.text)) { + if (is.object(inputOptions.text) && is.string(inputOptions.text.text)) { + inputDescriptor.textValue = inputOptions.text.text; + if (is.defined(inputOptions.text.height) && is.defined(inputOptions.text.dpi)) { + throw new Error('Expected only one of dpi or height'); + } + if (is.defined(inputOptions.text.font)) { + if (is.string(inputOptions.text.font)) { + inputDescriptor.textFont = inputOptions.text.font; + } else { + throw is.invalidParameterError('text.font', 'string', inputOptions.text.font); + } + } + if (is.defined(inputOptions.text.fontfile)) { + if (is.string(inputOptions.text.fontfile)) { + inputDescriptor.textFontfile = inputOptions.text.fontfile; + } else { + throw is.invalidParameterError('text.fontfile', 'string', inputOptions.text.fontfile); + } + } + if (is.defined(inputOptions.text.width)) { + if (is.integer(inputOptions.text.width) && inputOptions.text.width > 0) { + inputDescriptor.textWidth = inputOptions.text.width; + } else { + throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width); + } + } + if (is.defined(inputOptions.text.height)) { + if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) { + inputDescriptor.textHeight = inputOptions.text.height; + } else { + throw is.invalidParameterError('text.height', 'positive integer', inputOptions.text.height); + } + } + if (is.defined(inputOptions.text.align)) { + if (is.string(inputOptions.text.align) && is.string(this.constructor.align[inputOptions.text.align])) { + inputDescriptor.textAlign = this.constructor.align[inputOptions.text.align]; + } else { + throw is.invalidParameterError('text.align', 'valid alignment', inputOptions.text.align); + } + } + if (is.defined(inputOptions.text.justify)) { + if (is.bool(inputOptions.text.justify)) { + inputDescriptor.textJustify = inputOptions.text.justify; + } else { + throw is.invalidParameterError('text.justify', 'boolean', inputOptions.text.justify); + } + } + if (is.defined(inputOptions.text.dpi)) { + if (is.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) { + inputDescriptor.textDpi = inputOptions.text.dpi; + } else { + throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', inputOptions.text.dpi); + } + } + if (is.defined(inputOptions.text.rgba)) { + if (is.bool(inputOptions.text.rgba)) { + inputDescriptor.textRgba = inputOptions.text.rgba; + } else { + throw is.invalidParameterError('text.rgba', 'bool', inputOptions.text.rgba); + } + } + if (is.defined(inputOptions.text.spacing)) { + if (is.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) { + inputDescriptor.textSpacing = inputOptions.text.spacing; + } else { + throw is.invalidParameterError('text.spacing', 'integer between -1000000 and 1000000', inputOptions.text.spacing); + } + } + if (is.defined(inputOptions.text.wrap)) { + if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) { + inputDescriptor.textWrap = inputOptions.text.wrap; + } else { + throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap); + } + } + delete inputDescriptor.buffer; + } else { + throw new Error('Expected a valid string to create an image with text.'); + } + } + } else if (is.defined(inputOptions)) { + throw new Error('Invalid input options ' + inputOptions); + } + return inputDescriptor; +} + +/** + * Handle incoming Buffer chunk on Writable Stream. + * @private + * @param {Buffer} chunk + * @param {string} encoding - unused + * @param {Function} callback + */ +function _write (chunk, encoding, callback) { + /* istanbul ignore else */ + if (Array.isArray(this.options.input.buffer)) { + /* istanbul ignore else */ + if (is.buffer(chunk)) { + if (this.options.input.buffer.length === 0) { + this.on('finish', () => { + this.streamInFinished = true; + }); + } + this.options.input.buffer.push(chunk); + callback(); + } else { + callback(new Error('Non-Buffer data on Writable Stream')); + } + } else { + callback(new Error('Unexpected data on Writable Stream')); + } +} + +/** + * Flattens the array of chunks accumulated in input.buffer. + * @private + */ +function _flattenBufferIn () { + if (this._isStreamInput()) { + this.options.input.buffer = Buffer.concat(this.options.input.buffer); + } +} + +/** + * Are we expecting Stream-based input? + * @private + * @returns {boolean} + */ +function _isStreamInput () { + return Array.isArray(this.options.input.buffer); +} + +/** + * Fast access to (uncached) image metadata without decoding any compressed pixel data. + * + * This is read from the header of the input image. + * It does not take into consideration any operations to be applied to the output image, + * such as resize or rotate. + * + * Dimensions in the response will respect the `page` and `pages` properties of the + * {@link /api-constructor#parameters|constructor parameters}. + * + * A `Promise` is returned when `callback` is not provided. + * + * - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg` + * - `size`: Total size of image in bytes, for Stream and Buffer input only + * - `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below) + * - `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below) + * - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation) + * - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK + * - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat) + * - `density`: Number of pixels per inch (DPI), if present + * - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK + * - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan + * - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP + * - `pageHeight`: Number of pixels high each page in a multi-page image will be. + * - `paletteBitDepth`: Bit depth of palette-based image (GIF, PNG). + * - `loop`: Number of times to loop an animated image, zero refers to a continuous loop. + * - `delay`: Delay in ms between each page in an animated image, provided as an array of integers. + * - `pagePrimary`: Number of the primary page in a HEIF image + * - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide + * - `subifds`: Number of Sub Image File Directories in an OME-TIFF image + * - `background`: Default background colour, if present, for PNG (bKGD) and GIF images, either an RGB Object or a single greyscale value + * - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) + * - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present + * - `hasProfile`: Boolean indicating the presence of an embedded ICC profile + * - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel + * - `orientation`: Number value of the EXIF Orientation header, if present + * - `exif`: Buffer containing raw EXIF data, if present + * - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present + * - `iptc`: Buffer containing raw IPTC data, if present + * - `xmp`: Buffer containing raw XMP data, if present + * - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present + * - `formatMagick`: String containing format for images loaded via *magick + * - `comments`: Array of keyword/text pairs representing PNG text blocks, if present. + * + * @example + * const metadata = await sharp(input).metadata(); + * + * @example + * const image = sharp(inputJpg); + * image + * .metadata() + * .then(function(metadata) { + * return image + * .resize(Math.round(metadata.width / 2)) + * .webp() + * .toBuffer(); + * }) + * .then(function(data) { + * // data contains a WebP image half the width and height of the original JPEG + * }); + * + * @example + * // Based on EXIF rotation metadata, get the right-side-up width and height: + * + * const size = getNormalSize(await sharp(input).metadata()); + * + * function getNormalSize({ width, height, orientation }) { + * return (orientation || 0) >= 5 + * ? { width: height, height: width } + * : { width, height }; + * } + * + * @param {Function} [callback] - called with the arguments `(err, metadata)` + * @returns {Promise|Sharp} + */ +function metadata (callback) { + const stack = Error(); + if (is.fn(callback)) { + if (this._isStreamInput()) { + this.on('finish', () => { + this._flattenBufferIn(); + sharp.metadata(this.options, (err, metadata) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, metadata); + } + }); + }); + } else { + sharp.metadata(this.options, (err, metadata) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, metadata); + } + }); + } + return this; + } else { + if (this._isStreamInput()) { + return new Promise((resolve, reject) => { + const finished = () => { + this._flattenBufferIn(); + sharp.metadata(this.options, (err, metadata) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + resolve(metadata); + } + }); + }; + if (this.writableFinished) { + finished(); + } else { + this.once('finish', finished); + } + }); + } else { + return new Promise((resolve, reject) => { + sharp.metadata(this.options, (err, metadata) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + resolve(metadata); + } + }); + }); + } + } +} + +/** + * Access to pixel-derived image statistics for every channel in the image. + * A `Promise` is returned when `callback` is not provided. + * + * - `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains + * - `min` (minimum value in the channel) + * - `max` (maximum value in the channel) + * - `sum` (sum of all values in a channel) + * - `squaresSum` (sum of squared values in a channel) + * - `mean` (mean of the values in a channel) + * - `stdev` (standard deviation for the values in a channel) + * - `minX` (x-coordinate of one of the pixel where the minimum lies) + * - `minY` (y-coordinate of one of the pixel where the minimum lies) + * - `maxX` (x-coordinate of one of the pixel where the maximum lies) + * - `maxY` (y-coordinate of one of the pixel where the maximum lies) + * - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque. + * - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any. + * - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any. + * - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram. + * + * **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be + * written to a buffer in order to run `stats` on the result (see third example). + * + * @example + * const image = sharp(inputJpg); + * image + * .stats() + * .then(function(stats) { + * // stats contains the channel-wise statistics array and the isOpaque value + * }); + * + * @example + * const { entropy, sharpness, dominant } = await sharp(input).stats(); + * const { r, g, b } = dominant; + * + * @example + * const image = sharp(input); + * // store intermediate result + * const part = await image.extract(region).toBuffer(); + * // create new instance to obtain statistics of extracted region + * const stats = await sharp(part).stats(); + * + * @param {Function} [callback] - called with the arguments `(err, stats)` + * @returns {Promise} + */ +function stats (callback) { + const stack = Error(); + if (is.fn(callback)) { + if (this._isStreamInput()) { + this.on('finish', () => { + this._flattenBufferIn(); + sharp.stats(this.options, (err, stats) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, stats); + } + }); + }); + } else { + sharp.stats(this.options, (err, stats) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, stats); + } + }); + } + return this; + } else { + if (this._isStreamInput()) { + return new Promise((resolve, reject) => { + this.on('finish', function () { + this._flattenBufferIn(); + sharp.stats(this.options, (err, stats) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + resolve(stats); + } + }); + }); + }); + } else { + return new Promise((resolve, reject) => { + sharp.stats(this.options, (err, stats) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + resolve(stats); + } + }); + }); + } + } +} + +/** + * Decorate the Sharp prototype with input-related functions. + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + // Private + _inputOptionsFromObject, + _createInputDescriptor, + _write, + _flattenBufferIn, + _isStreamInput, + // Public + metadata, + stats + }); + // Class attributes + Sharp.align = align; +}; diff --git a/node_modules/sharp/lib/is.js b/node_modules/sharp/lib/is.js new file mode 100644 index 0000000000000000000000000000000000000000..a63cb20668cae634f30662b04202fd2cf8902595 --- /dev/null +++ b/node_modules/sharp/lib/is.js @@ -0,0 +1,169 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +/** + * Is this value defined and not null? + * @private + */ +const defined = function (val) { + return typeof val !== 'undefined' && val !== null; +}; + +/** + * Is this value an object? + * @private + */ +const object = function (val) { + return typeof val === 'object'; +}; + +/** + * Is this value a plain object? + * @private + */ +const plainObject = function (val) { + return Object.prototype.toString.call(val) === '[object Object]'; +}; + +/** + * Is this value a function? + * @private + */ +const fn = function (val) { + return typeof val === 'function'; +}; + +/** + * Is this value a boolean? + * @private + */ +const bool = function (val) { + return typeof val === 'boolean'; +}; + +/** + * Is this value a Buffer object? + * @private + */ +const buffer = function (val) { + return val instanceof Buffer; +}; + +/** + * Is this value a typed array object?. E.g. Uint8Array or Uint8ClampedArray? + * @private + */ +const typedArray = function (val) { + if (defined(val)) { + switch (val.constructor) { + case Uint8Array: + case Uint8ClampedArray: + case Int8Array: + case Uint16Array: + case Int16Array: + case Uint32Array: + case Int32Array: + case Float32Array: + case Float64Array: + return true; + } + } + + return false; +}; + +/** + * Is this value an ArrayBuffer object? + * @private + */ +const arrayBuffer = function (val) { + return val instanceof ArrayBuffer; +}; + +/** + * Is this value a non-empty string? + * @private + */ +const string = function (val) { + return typeof val === 'string' && val.length > 0; +}; + +/** + * Is this value a real number? + * @private + */ +const number = function (val) { + return typeof val === 'number' && !Number.isNaN(val); +}; + +/** + * Is this value an integer? + * @private + */ +const integer = function (val) { + return Number.isInteger(val); +}; + +/** + * Is this value within an inclusive given range? + * @private + */ +const inRange = function (val, min, max) { + return val >= min && val <= max; +}; + +/** + * Is this value within the elements of an array? + * @private + */ +const inArray = function (val, list) { + return list.includes(val); +}; + +/** + * Create an Error with a message relating to an invalid parameter. + * + * @param {string} name - parameter name. + * @param {string} expected - description of the type/value/range expected. + * @param {*} actual - the value received. + * @returns {Error} Containing the formatted message. + * @private + */ +const invalidParameterError = function (name, expected, actual) { + return new Error( + `Expected ${expected} for ${name} but received ${actual} of type ${typeof actual}` + ); +}; + +/** + * Ensures an Error from C++ contains a JS stack. + * + * @param {Error} native - Error with message from C++. + * @param {Error} context - Error with stack from JS. + * @returns {Error} Error with message and stack. + * @private + */ +const nativeError = function (native, context) { + context.message = native.message; + return context; +}; + +module.exports = { + defined, + object, + plainObject, + fn, + bool, + buffer, + typedArray, + arrayBuffer, + string, + number, + integer, + inRange, + inArray, + invalidParameterError, + nativeError +}; diff --git a/node_modules/sharp/lib/libvips.js b/node_modules/sharp/lib/libvips.js new file mode 100644 index 0000000000000000000000000000000000000000..c9927e7a934a660f8543f3e6718bc89a49f32e22 --- /dev/null +++ b/node_modules/sharp/lib/libvips.js @@ -0,0 +1,203 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const { spawnSync } = require('node:child_process'); +const { createHash } = require('node:crypto'); +const semverCoerce = require('semver/functions/coerce'); +const semverGreaterThanOrEqualTo = require('semver/functions/gte'); +const semverSatisfies = require('semver/functions/satisfies'); +const detectLibc = require('detect-libc'); + +const { config, engines, optionalDependencies } = require('../package.json'); + +const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */ + config.libvips; +const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version; + +const prebuiltPlatforms = [ + 'darwin-arm64', 'darwin-x64', + 'linux-arm', 'linux-arm64', 'linux-s390x', 'linux-x64', + 'linuxmusl-arm64', 'linuxmusl-x64', + 'win32-ia32', 'win32-x64' +]; + +const spawnSyncOptions = { + encoding: 'utf8', + shell: true +}; + +const log = (item) => { + if (item instanceof Error) { + console.error(`sharp: Installation error: ${item.message}`); + } else { + console.log(`sharp: ${item}`); + } +}; + +/* istanbul ignore next */ +const runtimeLibc = () => detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : ''; + +const runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process.arch}`; + +/* istanbul ignore next */ +const buildPlatformArch = () => { + if (isEmscripten()) { + return 'wasm32'; + } + /* eslint camelcase: ["error", { allow: ["^npm_config_"] }] */ + const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env; + const libc = typeof npm_config_libc === 'string' ? npm_config_libc : runtimeLibc(); + return `${npm_config_platform || process.platform}${libc}-${npm_config_arch || process.arch}`; +}; + +const buildSharpLibvipsIncludeDir = () => { + try { + return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/include`); + } catch { + try { + return require('@img/sharp-libvips-dev/include'); + } catch {} + } + /* istanbul ignore next */ + return ''; +}; + +const buildSharpLibvipsCPlusPlusDir = () => { + try { + return require('@img/sharp-libvips-dev/cplusplus'); + } catch {} + /* istanbul ignore next */ + return ''; +}; + +const buildSharpLibvipsLibDir = () => { + try { + return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/lib`); + } catch { + try { + return require(`@img/sharp-libvips-${buildPlatformArch()}/lib`); + } catch {} + } + /* istanbul ignore next */ + return ''; +}; + +const isUnsupportedNodeRuntime = () => { + /* istanbul ignore next */ + if (process.release?.name === 'node' && process.versions) { + if (!semverSatisfies(process.versions.node, engines.node)) { + return { found: process.versions.node, expected: engines.node }; + } + } +}; + +/* istanbul ignore next */ +const isEmscripten = () => { + const { CC } = process.env; + return Boolean(CC && CC.endsWith('/emcc')); +}; + +const isRosetta = () => { + /* istanbul ignore next */ + if (process.platform === 'darwin' && process.arch === 'x64') { + const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout; + return (translated || '').trim() === 'sysctl.proc_translated: 1'; + } + return false; +}; + +const sha512 = (s) => createHash('sha512').update(s).digest('hex'); + +const yarnLocator = () => { + try { + const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`); + const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`]).version; + return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10); + } catch {} + return ''; +}; + +/* istanbul ignore next */ +const spawnRebuild = () => + spawnSync(`node-gyp rebuild --directory=src ${isEmscripten() ? '--nodedir=emscripten' : ''}`, { + ...spawnSyncOptions, + stdio: 'inherit' + }).status; + +const globalLibvipsVersion = () => { + if (process.platform !== 'win32') { + const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', { + ...spawnSyncOptions, + env: { + ...process.env, + PKG_CONFIG_PATH: pkgConfigPath() + } + }).stdout; + /* istanbul ignore next */ + return (globalLibvipsVersion || '').trim(); + } else { + return ''; + } +}; + +/* istanbul ignore next */ +const pkgConfigPath = () => { + if (process.platform !== 'win32') { + const brewPkgConfigPath = spawnSync( + 'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2', + spawnSyncOptions + ).stdout || ''; + return [ + brewPkgConfigPath.trim(), + process.env.PKG_CONFIG_PATH, + '/usr/local/lib/pkgconfig', + '/usr/lib/pkgconfig', + '/usr/local/libdata/pkgconfig', + '/usr/libdata/pkgconfig' + ].filter(Boolean).join(':'); + } else { + return ''; + } +}; + +const skipSearch = (status, reason, logger) => { + if (logger) { + logger(`Detected ${reason}, skipping search for globally-installed libvips`); + } + return status; +}; + +const useGlobalLibvips = (logger) => { + if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) { + return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS', logger); + } + if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) { + return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS', logger); + } + /* istanbul ignore next */ + if (isRosetta()) { + return skipSearch(false, 'Rosetta', logger); + } + const globalVipsVersion = globalLibvipsVersion(); + return !!globalVipsVersion && /* istanbul ignore next */ + semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion); +}; + +module.exports = { + minimumLibvipsVersion, + prebuiltPlatforms, + buildPlatformArch, + buildSharpLibvipsIncludeDir, + buildSharpLibvipsCPlusPlusDir, + buildSharpLibvipsLibDir, + isUnsupportedNodeRuntime, + runtimePlatformArch, + log, + yarnLocator, + spawnRebuild, + globalLibvipsVersion, + pkgConfigPath, + useGlobalLibvips +}; diff --git a/node_modules/sharp/lib/operation.js b/node_modules/sharp/lib/operation.js new file mode 100644 index 0000000000000000000000000000000000000000..c47fbadf70e3007573ad4383b2da76c88a3e0e03 --- /dev/null +++ b/node_modules/sharp/lib/operation.js @@ -0,0 +1,958 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const color = require('color'); +const is = require('./is'); + +/** + * How accurate an operation should be. + * @member + * @private + */ +const vipsPrecision = { + integer: 'integer', + float: 'float', + approximate: 'approximate' +}; + +/** + * Rotate the output image by either an explicit angle + * or auto-orient based on the EXIF `Orientation` tag. + * + * If an angle is provided, it is converted to a valid positive degree rotation. + * For example, `-450` will produce a 270 degree rotation. + * + * When rotating by an angle other than a multiple of 90, + * the background colour can be provided with the `background` option. + * + * If no angle is provided, it is determined from the EXIF data. + * Mirroring is supported and may infer the use of a flip operation. + * + * The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any. + * + * Only one rotation can occur per pipeline. + * Previous calls to `rotate` in the same pipeline will be ignored. + * + * Multi-page images can only be rotated by 180 degrees. + * + * Method order is important when rotating, resizing and/or extracting regions, + * for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`. + * + * @example + * const pipeline = sharp() + * .rotate() + * .resize(null, 200) + * .toBuffer(function (err, outputBuffer, info) { + * // outputBuffer contains 200px high JPEG image data, + * // auto-rotated using EXIF Orientation tag + * // info.width and info.height contain the dimensions of the resized image + * }); + * readableStream.pipe(pipeline); + * + * @example + * const rotateThenResize = await sharp(input) + * .rotate(90) + * .resize({ width: 16, height: 8, fit: 'fill' }) + * .toBuffer(); + * const resizeThenRotate = await sharp(input) + * .resize({ width: 16, height: 8, fit: 'fill' }) + * .rotate(90) + * .toBuffer(); + * + * @param {number} [angle=auto] angle of rotation. + * @param {Object} [options] - if present, is an Object with optional attributes. + * @param {string|Object} [options.background="#000000"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function rotate (angle, options) { + if (this.options.useExifOrientation || this.options.angle || this.options.rotationAngle) { + this.options.debuglog('ignoring previous rotate options'); + } + if (!is.defined(angle)) { + this.options.useExifOrientation = true; + } else if (is.integer(angle) && !(angle % 90)) { + this.options.angle = angle; + } else if (is.number(angle)) { + this.options.rotationAngle = angle; + if (is.object(options) && options.background) { + const backgroundColour = color(options.background); + this.options.rotationBackground = [ + backgroundColour.red(), + backgroundColour.green(), + backgroundColour.blue(), + Math.round(backgroundColour.alpha() * 255) + ]; + } + } else { + throw is.invalidParameterError('angle', 'numeric', angle); + } + return this; +} + +/** + * Mirror the image vertically (up-down) about the x-axis. + * This always occurs before rotation, if any. + * + * This operation does not work correctly with multi-page images. + * + * @example + * const output = await sharp(input).flip().toBuffer(); + * + * @param {Boolean} [flip=true] + * @returns {Sharp} + */ +function flip (flip) { + this.options.flip = is.bool(flip) ? flip : true; + return this; +} + +/** + * Mirror the image horizontally (left-right) about the y-axis. + * This always occurs before rotation, if any. + * + * @example + * const output = await sharp(input).flop().toBuffer(); + * + * @param {Boolean} [flop=true] + * @returns {Sharp} + */ +function flop (flop) { + this.options.flop = is.bool(flop) ? flop : true; + return this; +} + +/** + * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. + * + * You must provide an array of length 4 or a 2x2 affine transformation matrix. + * By default, new pixels are filled with a black background. You can provide a background color with the `background` option. + * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. + * + * In the case of a 2x2 matrix, the transform is: + * - X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx` + * - Y = `matrix[1, 0]` \* (x + `idx`) + `matrix[1, 1]` \* (y + `idy`) + `ody` + * + * where: + * - x and y are the coordinates in input image. + * - X and Y are the coordinates in output image. + * - (0,0) is the upper left corner. + * + * @since 0.27.0 + * + * @example + * const pipeline = sharp() + * .affine([[1, 0.3], [0.1, 0.7]], { + * background: 'white', + * interpolator: sharp.interpolators.nohalo + * }) + * .toBuffer((err, outputBuffer, info) => { + * // outputBuffer contains the transformed image + * // info.width and info.height contain the new dimensions + * }); + * + * inputStream + * .pipe(pipeline); + * + * @param {Array>|Array} matrix - affine transformation matrix + * @param {Object} [options] - if present, is an Object with optional attributes. + * @param {String|Object} [options.background="#000000"] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @param {Number} [options.idx=0] - input horizontal offset + * @param {Number} [options.idy=0] - input vertical offset + * @param {Number} [options.odx=0] - output horizontal offset + * @param {Number} [options.ody=0] - output vertical offset + * @param {String} [options.interpolator=sharp.interpolators.bicubic] - interpolator + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function affine (matrix, options) { + const flatMatrix = [].concat(...matrix); + if (flatMatrix.length === 4 && flatMatrix.every(is.number)) { + this.options.affineMatrix = flatMatrix; + } else { + throw is.invalidParameterError('matrix', '1x4 or 2x2 array', matrix); + } + + if (is.defined(options)) { + if (is.object(options)) { + this._setBackgroundColourOption('affineBackground', options.background); + if (is.defined(options.idx)) { + if (is.number(options.idx)) { + this.options.affineIdx = options.idx; + } else { + throw is.invalidParameterError('options.idx', 'number', options.idx); + } + } + if (is.defined(options.idy)) { + if (is.number(options.idy)) { + this.options.affineIdy = options.idy; + } else { + throw is.invalidParameterError('options.idy', 'number', options.idy); + } + } + if (is.defined(options.odx)) { + if (is.number(options.odx)) { + this.options.affineOdx = options.odx; + } else { + throw is.invalidParameterError('options.odx', 'number', options.odx); + } + } + if (is.defined(options.ody)) { + if (is.number(options.ody)) { + this.options.affineOdy = options.ody; + } else { + throw is.invalidParameterError('options.ody', 'number', options.ody); + } + } + if (is.defined(options.interpolator)) { + if (is.inArray(options.interpolator, Object.values(this.constructor.interpolators))) { + this.options.affineInterpolator = options.interpolator; + } else { + throw is.invalidParameterError('options.interpolator', 'valid interpolator name', options.interpolator); + } + } + } else { + throw is.invalidParameterError('options', 'object', options); + } + } + + return this; +} + +/** + * Sharpen the image. + * + * When used without parameters, performs a fast, mild sharpen of the output image. + * + * When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. + * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. + * + * See {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation. + * + * @example + * const data = await sharp(input).sharpen().toBuffer(); + * + * @example + * const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer(); + * + * @example + * const data = await sharp(input) + * .sharpen({ + * sigma: 2, + * m1: 0, + * m2: 3, + * x1: 3, + * y2: 15, + * y3: 15, + * }) + * .toBuffer(); + * + * @param {Object|number} [options] - if present, is an Object with attributes + * @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10 + * @param {number} [options.m1=1.0] - the level of sharpening to apply to "flat" areas, between 0 and 1000000 + * @param {number} [options.m2=2.0] - the level of sharpening to apply to "jagged" areas, between 0 and 1000000 + * @param {number} [options.x1=2.0] - threshold between "flat" and "jagged", between 0 and 1000000 + * @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000 + * @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000 + * @param {number} [flat] - (deprecated) see `options.m1`. + * @param {number} [jagged] - (deprecated) see `options.m2`. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function sharpen (options, flat, jagged) { + if (!is.defined(options)) { + // No arguments: default to mild sharpen + this.options.sharpenSigma = -1; + } else if (is.bool(options)) { + // Deprecated boolean argument: apply mild sharpen? + this.options.sharpenSigma = options ? -1 : 0; + } else if (is.number(options) && is.inRange(options, 0.01, 10000)) { + // Deprecated numeric argument: specific sigma + this.options.sharpenSigma = options; + // Deprecated control over flat areas + if (is.defined(flat)) { + if (is.number(flat) && is.inRange(flat, 0, 10000)) { + this.options.sharpenM1 = flat; + } else { + throw is.invalidParameterError('flat', 'number between 0 and 10000', flat); + } + } + // Deprecated control over jagged areas + if (is.defined(jagged)) { + if (is.number(jagged) && is.inRange(jagged, 0, 10000)) { + this.options.sharpenM2 = jagged; + } else { + throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged); + } + } + } else if (is.plainObject(options)) { + if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10)) { + this.options.sharpenSigma = options.sigma; + } else { + throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10', options.sigma); + } + if (is.defined(options.m1)) { + if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) { + this.options.sharpenM1 = options.m1; + } else { + throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1); + } + } + if (is.defined(options.m2)) { + if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) { + this.options.sharpenM2 = options.m2; + } else { + throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2); + } + } + if (is.defined(options.x1)) { + if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) { + this.options.sharpenX1 = options.x1; + } else { + throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1); + } + } + if (is.defined(options.y2)) { + if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) { + this.options.sharpenY2 = options.y2; + } else { + throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2); + } + } + if (is.defined(options.y3)) { + if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) { + this.options.sharpenY3 = options.y3; + } else { + throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3); + } + } + } else { + throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', options); + } + return this; +} + +/** + * Apply median filter. + * When used without parameters the default window is 3x3. + * + * @example + * const output = await sharp(input).median().toBuffer(); + * + * @example + * const output = await sharp(input).median(5).toBuffer(); + * + * @param {number} [size=3] square mask size: size x size + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function median (size) { + if (!is.defined(size)) { + // No arguments: default to 3x3 + this.options.medianSize = 3; + } else if (is.integer(size) && is.inRange(size, 1, 1000)) { + // Numeric argument: specific sigma + this.options.medianSize = size; + } else { + throw is.invalidParameterError('size', 'integer between 1 and 1000', size); + } + return this; +} + +/** + * Blur the image. + * + * When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter). + * + * When a `sigma` is provided, performs a slower, more accurate Gaussian blur. + * + * @example + * const boxBlurred = await sharp(input) + * .blur() + * .toBuffer(); + * + * @example + * const gaussianBlurred = await sharp(input) + * .blur(5) + * .toBuffer(); + * + * @param {Object|number|Boolean} [options] + * @param {number} [options.sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. + * @param {string} [options.precision='integer'] How accurate the operation should be, one of: integer, float, approximate. + * @param {number} [options.minAmplitude=0.2] A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function blur (options) { + let sigma; + if (is.number(options)) { + sigma = options; + } else if (is.plainObject(options)) { + if (!is.number(options.sigma)) { + throw is.invalidParameterError('options.sigma', 'number between 0.3 and 1000', sigma); + } + sigma = options.sigma; + if ('precision' in options) { + if (is.string(vipsPrecision[options.precision])) { + this.options.precision = vipsPrecision[options.precision]; + } else { + throw is.invalidParameterError('precision', 'one of: integer, float, approximate', options.precision); + } + } + if ('minAmplitude' in options) { + if (is.number(options.minAmplitude) && is.inRange(options.minAmplitude, 0.001, 1)) { + this.options.minAmpl = options.minAmplitude; + } else { + throw is.invalidParameterError('minAmplitude', 'number between 0.001 and 1', options.minAmplitude); + } + } + } + + if (!is.defined(options)) { + // No arguments: default to mild blur + this.options.blurSigma = -1; + } else if (is.bool(options)) { + // Boolean argument: apply mild blur? + this.options.blurSigma = options ? -1 : 0; + } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) { + // Numeric argument: specific sigma + this.options.blurSigma = sigma; + } else { + throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma); + } + + return this; +} + +/** + * Merge alpha transparency channel, if any, with a background, then remove the alpha channel. + * + * See also {@link /api-channel#removealpha|removeAlpha}. + * + * @example + * await sharp(rgbaInput) + * .flatten({ background: '#F0A703' }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {string|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black. + * @returns {Sharp} + */ +function flatten (options) { + this.options.flatten = is.bool(options) ? options : true; + if (is.object(options)) { + this._setBackgroundColourOption('flattenBackground', options.background); + } + return this; +} + +/** + * Ensure the image has an alpha channel + * with all white pixel values made fully transparent. + * + * Existing alpha channel values for non-white pixels remain unchanged. + * + * This feature is experimental and the API may change. + * + * @since 0.32.1 + * + * @example + * await sharp(rgbInput) + * .unflatten() + * .toBuffer(); + * + * @example + * await sharp(rgbInput) + * .threshold(128, { grayscale: false }) // converter bright pixels to white + * .unflatten() + * .toBuffer(); + */ +function unflatten () { + this.options.unflatten = true; + return this; +} + +/** + * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma` + * then increasing the encoding (brighten) post-resize at a factor of `gamma`. + * This can improve the perceived brightness of a resized image in non-linear colour spaces. + * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation + * when applying a gamma correction. + * + * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases. + * + * @param {number} [gamma=2.2] value between 1.0 and 3.0. + * @param {number} [gammaOut] value between 1.0 and 3.0. (optional, defaults to same as `gamma`) + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function gamma (gamma, gammaOut) { + if (!is.defined(gamma)) { + // Default gamma correction of 2.2 (sRGB) + this.options.gamma = 2.2; + } else if (is.number(gamma) && is.inRange(gamma, 1, 3)) { + this.options.gamma = gamma; + } else { + throw is.invalidParameterError('gamma', 'number between 1.0 and 3.0', gamma); + } + if (!is.defined(gammaOut)) { + // Default gamma correction for output is same as input + this.options.gammaOut = this.options.gamma; + } else if (is.number(gammaOut) && is.inRange(gammaOut, 1, 3)) { + this.options.gammaOut = gammaOut; + } else { + throw is.invalidParameterError('gammaOut', 'number between 1.0 and 3.0', gammaOut); + } + return this; +} + +/** + * Produce the "negative" of the image. + * + * @example + * const output = await sharp(input) + * .negate() + * .toBuffer(); + * + * @example + * const output = await sharp(input) + * .negate({ alpha: false }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel + * @returns {Sharp} + */ +function negate (options) { + this.options.negate = is.bool(options) ? options : true; + if (is.plainObject(options) && 'alpha' in options) { + if (!is.bool(options.alpha)) { + throw is.invalidParameterError('alpha', 'should be boolean value', options.alpha); + } else { + this.options.negateAlpha = options.alpha; + } + } + return this; +} + +/** + * Enhance output image contrast by stretching its luminance to cover a full dynamic range. + * + * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes. + * + * Luminance values below the `lower` percentile will be underexposed by clipping to zero. + * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value. + * + * @example + * const output = await sharp(input) + * .normalise() + * .toBuffer(); + * + * @example + * const output = await sharp(input) + * .normalise({ lower: 0, upper: 100 }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed. + * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed. + * @returns {Sharp} + */ +function normalise (options) { + if (is.plainObject(options)) { + if (is.defined(options.lower)) { + if (is.number(options.lower) && is.inRange(options.lower, 0, 99)) { + this.options.normaliseLower = options.lower; + } else { + throw is.invalidParameterError('lower', 'number between 0 and 99', options.lower); + } + } + if (is.defined(options.upper)) { + if (is.number(options.upper) && is.inRange(options.upper, 1, 100)) { + this.options.normaliseUpper = options.upper; + } else { + throw is.invalidParameterError('upper', 'number between 1 and 100', options.upper); + } + } + } + if (this.options.normaliseLower >= this.options.normaliseUpper) { + throw is.invalidParameterError('range', 'lower to be less than upper', + `${this.options.normaliseLower} >= ${this.options.normaliseUpper}`); + } + this.options.normalise = true; + return this; +} + +/** + * Alternative spelling of normalise. + * + * @example + * const output = await sharp(input) + * .normalize() + * .toBuffer(); + * + * @param {Object} [options] + * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed. + * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed. + * @returns {Sharp} + */ +function normalize (options) { + return this.normalise(options); +} + +/** + * Perform contrast limiting adaptive histogram equalization + * {@link https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE|CLAHE}. + * + * This will, in general, enhance the clarity of the image by bringing out darker details. + * + * @since 0.28.3 + * + * @example + * const output = await sharp(input) + * .clahe({ + * width: 3, + * height: 3, + * }) + * .toBuffer(); + * + * @param {Object} options + * @param {number} options.width - Integral width of the search window, in pixels. + * @param {number} options.height - Integral height of the search window, in pixels. + * @param {number} [options.maxSlope=3] - Integral level of brightening, between 0 and 100, where 0 disables contrast limiting. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function clahe (options) { + if (is.plainObject(options)) { + if (is.integer(options.width) && options.width > 0) { + this.options.claheWidth = options.width; + } else { + throw is.invalidParameterError('width', 'integer greater than zero', options.width); + } + if (is.integer(options.height) && options.height > 0) { + this.options.claheHeight = options.height; + } else { + throw is.invalidParameterError('height', 'integer greater than zero', options.height); + } + if (is.defined(options.maxSlope)) { + if (is.integer(options.maxSlope) && is.inRange(options.maxSlope, 0, 100)) { + this.options.claheMaxSlope = options.maxSlope; + } else { + throw is.invalidParameterError('maxSlope', 'integer between 0 and 100', options.maxSlope); + } + } + } else { + throw is.invalidParameterError('options', 'plain object', options); + } + return this; +} + +/** + * Convolve the image with the specified kernel. + * + * @example + * sharp(input) + * .convolve({ + * width: 3, + * height: 3, + * kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1] + * }) + * .raw() + * .toBuffer(function(err, data, info) { + * // data contains the raw pixel data representing the convolution + * // of the input image with the horizontal Sobel operator + * }); + * + * @param {Object} kernel + * @param {number} kernel.width - width of the kernel in pixels. + * @param {number} kernel.height - height of the kernel in pixels. + * @param {Array} kernel.kernel - Array of length `width*height` containing the kernel values. + * @param {number} [kernel.scale=sum] - the scale of the kernel in pixels. + * @param {number} [kernel.offset=0] - the offset of the kernel in pixels. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function convolve (kernel) { + if (!is.object(kernel) || !Array.isArray(kernel.kernel) || + !is.integer(kernel.width) || !is.integer(kernel.height) || + !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) || + kernel.height * kernel.width !== kernel.kernel.length + ) { + // must pass in a kernel + throw new Error('Invalid convolution kernel'); + } + // Default scale is sum of kernel values + if (!is.integer(kernel.scale)) { + kernel.scale = kernel.kernel.reduce(function (a, b) { + return a + b; + }, 0); + } + // Clip scale to a minimum value of 1 + if (kernel.scale < 1) { + kernel.scale = 1; + } + if (!is.integer(kernel.offset)) { + kernel.offset = 0; + } + this.options.convKernel = kernel; + return this; +} + +/** + * Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0. + * @param {number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied. + * @param {Object} [options] + * @param {Boolean} [options.greyscale=true] - convert to single channel greyscale. + * @param {Boolean} [options.grayscale=true] - alternative spelling for greyscale. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function threshold (threshold, options) { + if (!is.defined(threshold)) { + this.options.threshold = 128; + } else if (is.bool(threshold)) { + this.options.threshold = threshold ? 128 : 0; + } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) { + this.options.threshold = threshold; + } else { + throw is.invalidParameterError('threshold', 'integer between 0 and 255', threshold); + } + if (!is.object(options) || options.greyscale === true || options.grayscale === true) { + this.options.thresholdGrayscale = true; + } else { + this.options.thresholdGrayscale = false; + } + return this; +} + +/** + * Perform a bitwise boolean operation with operand image. + * + * This operation creates an output image where each pixel is the result of + * the selected bitwise boolean `operation` between the corresponding pixels of the input images. + * + * @param {Buffer|string} operand - Buffer containing image data or string containing the path to an image file. + * @param {string} operator - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. + * @param {Object} [options] + * @param {Object} [options.raw] - describes operand when using raw pixel data. + * @param {number} [options.raw.width] + * @param {number} [options.raw.height] + * @param {number} [options.raw.channels] + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function boolean (operand, operator, options) { + this.options.boolean = this._createInputDescriptor(operand, options); + if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) { + this.options.booleanOp = operator; + } else { + throw is.invalidParameterError('operator', 'one of: and, or, eor', operator); + } + return this; +} + +/** + * Apply the linear formula `a` * input + `b` to the image to adjust image levels. + * + * When a single number is provided, it will be used for all image channels. + * When an array of numbers is provided, the array length must match the number of channels. + * + * @example + * await sharp(input) + * .linear(0.5, 2) + * .toBuffer(); + * + * @example + * await sharp(rgbInput) + * .linear( + * [0.25, 0.5, 0.75], + * [150, 100, 50] + * ) + * .toBuffer(); + * + * @param {(number|number[])} [a=[]] multiplier + * @param {(number|number[])} [b=[]] offset + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function linear (a, b) { + if (!is.defined(a) && is.number(b)) { + a = 1.0; + } else if (is.number(a) && !is.defined(b)) { + b = 0.0; + } + if (!is.defined(a)) { + this.options.linearA = []; + } else if (is.number(a)) { + this.options.linearA = [a]; + } else if (Array.isArray(a) && a.length && a.every(is.number)) { + this.options.linearA = a; + } else { + throw is.invalidParameterError('a', 'number or array of numbers', a); + } + if (!is.defined(b)) { + this.options.linearB = []; + } else if (is.number(b)) { + this.options.linearB = [b]; + } else if (Array.isArray(b) && b.length && b.every(is.number)) { + this.options.linearB = b; + } else { + throw is.invalidParameterError('b', 'number or array of numbers', b); + } + if (this.options.linearA.length !== this.options.linearB.length) { + throw new Error('Expected a and b to be arrays of the same length'); + } + return this; +} + +/** + * Recombine the image with the specified matrix. + * + * @since 0.21.1 + * + * @example + * sharp(input) + * .recomb([ + * [0.3588, 0.7044, 0.1368], + * [0.2990, 0.5870, 0.1140], + * [0.2392, 0.4696, 0.0912], + * ]) + * .raw() + * .toBuffer(function(err, data, info) { + * // data contains the raw pixel data after applying the matrix + * // With this example input, a sepia filter has been applied + * }); + * + * @param {Array>} inputMatrix - 3x3 or 4x4 Recombination matrix + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function recomb (inputMatrix) { + if (!Array.isArray(inputMatrix)) { + throw is.invalidParameterError('inputMatrix', 'array', inputMatrix); + } + if (inputMatrix.length !== 3 && inputMatrix.length !== 4) { + throw is.invalidParameterError('inputMatrix', '3x3 or 4x4 array', inputMatrix.length); + } + const recombMatrix = inputMatrix.flat().map(Number); + if (recombMatrix.length !== 9 && recombMatrix.length !== 16) { + throw is.invalidParameterError('inputMatrix', 'cardinality of 9 or 16', recombMatrix.length); + } + this.options.recombMatrix = recombMatrix; + return this; +} + +/** + * Transforms the image using brightness, saturation, hue rotation, and lightness. + * Brightness and lightness both operate on luminance, with the difference being that + * brightness is multiplicative whereas lightness is additive. + * + * @since 0.22.1 + * + * @example + * // increase brightness by a factor of 2 + * const output = await sharp(input) + * .modulate({ + * brightness: 2 + * }) + * .toBuffer(); + * + * @example + * // hue-rotate by 180 degrees + * const output = await sharp(input) + * .modulate({ + * hue: 180 + * }) + * .toBuffer(); + * + * @example + * // increase lightness by +50 + * const output = await sharp(input) + * .modulate({ + * lightness: 50 + * }) + * .toBuffer(); + * + * @example + * // decrease brightness and saturation while also hue-rotating by 90 degrees + * const output = await sharp(input) + * .modulate({ + * brightness: 0.5, + * saturation: 0.5, + * hue: 90, + * }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {number} [options.brightness] Brightness multiplier + * @param {number} [options.saturation] Saturation multiplier + * @param {number} [options.hue] Degrees for hue rotation + * @param {number} [options.lightness] Lightness addend + * @returns {Sharp} + */ +function modulate (options) { + if (!is.plainObject(options)) { + throw is.invalidParameterError('options', 'plain object', options); + } + if ('brightness' in options) { + if (is.number(options.brightness) && options.brightness >= 0) { + this.options.brightness = options.brightness; + } else { + throw is.invalidParameterError('brightness', 'number above zero', options.brightness); + } + } + if ('saturation' in options) { + if (is.number(options.saturation) && options.saturation >= 0) { + this.options.saturation = options.saturation; + } else { + throw is.invalidParameterError('saturation', 'number above zero', options.saturation); + } + } + if ('hue' in options) { + if (is.integer(options.hue)) { + this.options.hue = options.hue % 360; + } else { + throw is.invalidParameterError('hue', 'number', options.hue); + } + } + if ('lightness' in options) { + if (is.number(options.lightness)) { + this.options.lightness = options.lightness; + } else { + throw is.invalidParameterError('lightness', 'number', options.lightness); + } + } + return this; +} + +/** + * Decorate the Sharp prototype with operation-related functions. + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + rotate, + flip, + flop, + affine, + sharpen, + median, + blur, + flatten, + unflatten, + gamma, + negate, + normalise, + normalize, + clahe, + convolve, + threshold, + boolean, + linear, + recomb, + modulate + }); +}; diff --git a/node_modules/sharp/lib/output.js b/node_modules/sharp/lib/output.js new file mode 100644 index 0000000000000000000000000000000000000000..137932cc0806ccc30c91966fd498e29b2db9f22b --- /dev/null +++ b/node_modules/sharp/lib/output.js @@ -0,0 +1,1587 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const path = require('node:path'); +const is = require('./is'); +const sharp = require('./sharp'); + +const formats = new Map([ + ['heic', 'heif'], + ['heif', 'heif'], + ['avif', 'avif'], + ['jpeg', 'jpeg'], + ['jpg', 'jpeg'], + ['jpe', 'jpeg'], + ['tile', 'tile'], + ['dz', 'tile'], + ['png', 'png'], + ['raw', 'raw'], + ['tiff', 'tiff'], + ['tif', 'tiff'], + ['webp', 'webp'], + ['gif', 'gif'], + ['jp2', 'jp2'], + ['jpx', 'jp2'], + ['j2k', 'jp2'], + ['j2c', 'jp2'], + ['jxl', 'jxl'] +]); + +const jp2Regex = /\.(jp[2x]|j2[kc])$/i; + +const errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG'); + +const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours))); + +/** + * Write output image data to a file. + * + * If an explicit output format is not selected, it will be inferred from the extension, + * with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported. + * Note that raw pixel data is only supported for buffer output. + * + * By default all metadata will be removed, which includes EXIF-based orientation. + * See {@link #withmetadata|withMetadata} for control over this. + * + * The caller is responsible for ensuring directory structures and permissions exist. + * + * A `Promise` is returned when `callback` is not provided. + * + * @example + * sharp(input) + * .toFile('output.png', (err, info) => { ... }); + * + * @example + * sharp(input) + * .toFile('output.png') + * .then(info => { ... }) + * .catch(err => { ... }); + * + * @param {string} fileOut - the path to write the image data to. + * @param {Function} [callback] - called on completion with two arguments `(err, info)`. + * `info` contains the output image `format`, `size` (bytes), `width`, `height`, + * `channels` and `premultiplied` (indicating if premultiplication was used). + * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. + * When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. + * Animated output will also contain `pageHeight` and `pages`. + * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. + * @returns {Promise} - when no callback is provided + * @throws {Error} Invalid parameters + */ +function toFile (fileOut, callback) { + let err; + if (!is.string(fileOut)) { + err = new Error('Missing output file path'); + } else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) { + err = new Error('Cannot use same file for input and output'); + } else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2k.output.file) { + err = errJp2Save(); + } + if (err) { + if (is.fn(callback)) { + callback(err); + } else { + return Promise.reject(err); + } + } else { + this.options.fileOut = fileOut; + const stack = Error(); + return this._pipeline(callback, stack); + } + return this; +} + +/** + * Write output to a Buffer. + * JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported. + * + * Use {@link #toformat|toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format. + * + * If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output. + * + * By default all metadata will be removed, which includes EXIF-based orientation. + * See {@link #withmetadata|withMetadata} for control over this. + * + * `callback`, if present, gets three arguments `(err, data, info)` where: + * - `err` is an error, if any. + * - `data` is the output image data. + * - `info` contains the output image `format`, `size` (bytes), `width`, `height`, + * `channels` and `premultiplied` (indicating if premultiplication was used). + * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. + * Animated output will also contain `pageHeight` and `pages`. + * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. + * + * A `Promise` is returned when `callback` is not provided. + * + * @example + * sharp(input) + * .toBuffer((err, data, info) => { ... }); + * + * @example + * sharp(input) + * .toBuffer() + * .then(data => { ... }) + * .catch(err => { ... }); + * + * @example + * sharp(input) + * .png() + * .toBuffer({ resolveWithObject: true }) + * .then(({ data, info }) => { ... }) + * .catch(err => { ... }); + * + * @example + * const { data, info } = await sharp('my-image.jpg') + * // output the raw pixels + * .raw() + * .toBuffer({ resolveWithObject: true }); + * + * // create a more type safe way to work with the raw pixel data + * // this will not copy the data, instead it will change `data`s underlying ArrayBuffer + * // so `data` and `pixelArray` point to the same memory location + * const pixelArray = new Uint8ClampedArray(data.buffer); + * + * // When you are done changing the pixelArray, sharp takes the `pixelArray` as an input + * const { width, height, channels } = info; + * await sharp(pixelArray, { raw: { width, height, channels } }) + * .toFile('my-changed-image.jpg'); + * + * @param {Object} [options] + * @param {boolean} [options.resolveWithObject] Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`. + * @param {Function} [callback] + * @returns {Promise} - when no callback is provided + */ +function toBuffer (options, callback) { + if (is.object(options)) { + this._setBooleanOption('resolveWithObject', options.resolveWithObject); + } else if (this.options.resolveWithObject) { + this.options.resolveWithObject = false; + } + this.options.fileOut = ''; + const stack = Error(); + return this._pipeline(is.fn(options) ? options : callback, stack); +} + +/** + * Keep all EXIF metadata from the input image in the output image. + * + * EXIF metadata is unsupported for TIFF output. + * + * @since 0.33.0 + * + * @example + * const outputWithExif = await sharp(inputWithExif) + * .keepExif() + * .toBuffer(); + * + * @returns {Sharp} + */ +function keepExif () { + this.options.keepMetadata |= 0b00001; + return this; +} + +/** + * Set EXIF metadata in the output image, ignoring any EXIF in the input image. + * + * @since 0.33.0 + * + * @example + * const dataWithExif = await sharp(input) + * .withExif({ + * IFD0: { + * Copyright: 'The National Gallery' + * }, + * IFD3: { + * GPSLatitudeRef: 'N', + * GPSLatitude: '51/1 30/1 3230/100', + * GPSLongitudeRef: 'W', + * GPSLongitude: '0/1 7/1 4366/100' + * } + * }) + * .toBuffer(); + * + * @param {Object>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function withExif (exif) { + if (is.object(exif)) { + for (const [ifd, entries] of Object.entries(exif)) { + if (is.object(entries)) { + for (const [k, v] of Object.entries(entries)) { + if (is.string(v)) { + this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v; + } else { + throw is.invalidParameterError(`${ifd}.${k}`, 'string', v); + } + } + } else { + throw is.invalidParameterError(ifd, 'object', entries); + } + } + } else { + throw is.invalidParameterError('exif', 'object', exif); + } + this.options.withExifMerge = false; + return this.keepExif(); +} + +/** + * Update EXIF metadata from the input image in the output image. + * + * @since 0.33.0 + * + * @example + * const dataWithMergedExif = await sharp(inputWithExif) + * .withExifMerge({ + * IFD0: { + * Copyright: 'The National Gallery' + * } + * }) + * .toBuffer(); + * + * @param {Object>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function withExifMerge (exif) { + this.withExif(exif); + this.options.withExifMerge = true; + return this; +} + +/** + * Keep ICC profile from the input image in the output image. + * + * Where necessary, will attempt to convert the output colour space to match the profile. + * + * @since 0.33.0 + * + * @example + * const outputWithIccProfile = await sharp(inputWithIccProfile) + * .keepIccProfile() + * .toBuffer(); + * + * @returns {Sharp} + */ +function keepIccProfile () { + this.options.keepMetadata |= 0b01000; + return this; +} + +/** + * Transform using an ICC profile and attach to the output image. + * + * This can either be an absolute filesystem path or + * built-in profile name (`srgb`, `p3`, `cmyk`). + * + * @since 0.33.0 + * + * @example + * const outputWithP3 = await sharp(input) + * .withIccProfile('p3') + * .toBuffer(); + * + * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk). + * @param {Object} [options] + * @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata? + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function withIccProfile (icc, options) { + if (is.string(icc)) { + this.options.withIccProfile = icc; + } else { + throw is.invalidParameterError('icc', 'string', icc); + } + this.keepIccProfile(); + if (is.object(options)) { + if (is.defined(options.attach)) { + if (is.bool(options.attach)) { + if (!options.attach) { + this.options.keepMetadata &= ~0b01000; + } + } else { + throw is.invalidParameterError('attach', 'boolean', options.attach); + } + } + } + return this; +} + +/** + * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image. + * + * The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent + * sRGB colour space and strip all metadata, including the removal of any ICC profile. + * + * @since 0.33.0 + * + * @example + * const outputWithMetadata = await sharp(inputWithMetadata) + * .keepMetadata() + * .toBuffer(); + * + * @returns {Sharp} + */ +function keepMetadata () { + this.options.keepMetadata = 0b11111; + return this; +} + +/** + * Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image. + * + * This will also convert to and add a web-friendly sRGB ICC profile if appropriate. + * + * Allows orientation and density to be set or updated. + * + * @example + * const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata) + * .withMetadata() + * .toBuffer(); + * + * @example + * // Set output metadata to 96 DPI + * const data = await sharp(input) + * .withMetadata({ density: 96 }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8. + * @param {number} [options.density] Number of pixels per inch (DPI). + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function withMetadata (options) { + this.keepMetadata(); + this.withIccProfile('srgb'); + if (is.object(options)) { + if (is.defined(options.orientation)) { + if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) { + this.options.withMetadataOrientation = options.orientation; + } else { + throw is.invalidParameterError('orientation', 'integer between 1 and 8', options.orientation); + } + } + if (is.defined(options.density)) { + if (is.number(options.density) && options.density > 0) { + this.options.withMetadataDensity = options.density; + } else { + throw is.invalidParameterError('density', 'positive number', options.density); + } + } + if (is.defined(options.icc)) { + this.withIccProfile(options.icc); + } + if (is.defined(options.exif)) { + this.withExifMerge(options.exif); + } + } + return this; +} + +/** + * Force output to a given format. + * + * @example + * // Convert any input to PNG output + * const data = await sharp(input) + * .toFormat('png') + * .toBuffer(); + * + * @param {(string|Object)} format - as a string or an Object with an 'id' attribute + * @param {Object} options - output options + * @returns {Sharp} + * @throws {Error} unsupported format or options + */ +function toFormat (format, options) { + const actualFormat = formats.get((is.object(format) && is.string(format.id) ? format.id : format).toLowerCase()); + if (!actualFormat) { + throw is.invalidParameterError('format', `one of: ${[...formats.keys()].join(', ')}`, format); + } + return this[actualFormat](options); +} + +/** + * Use these JPEG options for output image. + * + * @example + * // Convert any input to very high quality JPEG output + * const data = await sharp(input) + * .jpeg({ + * quality: 100, + * chromaSubsampling: '4:4:4' + * }) + * .toBuffer(); + * + * @example + * // Use mozjpeg to reduce output JPEG file size (slower) + * const data = await sharp(input) + * .jpeg({ mozjpeg: true }) + * .toBuffer(); + * + * @param {Object} [options] - output options + * @param {number} [options.quality=80] - quality, integer 1-100 + * @param {boolean} [options.progressive=false] - use progressive (interlace) scan + * @param {string} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling + * @param {boolean} [options.optimiseCoding=true] - optimise Huffman coding tables + * @param {boolean} [options.optimizeCoding=true] - alternative spelling of optimiseCoding + * @param {boolean} [options.mozjpeg=false] - use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` + * @param {boolean} [options.trellisQuantisation=false] - apply trellis quantisation + * @param {boolean} [options.overshootDeringing=false] - apply overshoot deringing + * @param {boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive + * @param {boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans + * @param {number} [options.quantisationTable=0] - quantization table to use, integer 0-8 + * @param {number} [options.quantizationTable=0] - alternative spelling of quantisationTable + * @param {boolean} [options.force=true] - force JPEG output, otherwise attempt to use input format + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function jpeg (options) { + if (is.object(options)) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + this.options.jpegQuality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } + if (is.defined(options.progressive)) { + this._setBooleanOption('jpegProgressive', options.progressive); + } + if (is.defined(options.chromaSubsampling)) { + if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { + this.options.jpegChromaSubsampling = options.chromaSubsampling; + } else { + throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling); + } + } + const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding; + if (is.defined(optimiseCoding)) { + this._setBooleanOption('jpegOptimiseCoding', optimiseCoding); + } + if (is.defined(options.mozjpeg)) { + if (is.bool(options.mozjpeg)) { + if (options.mozjpeg) { + this.options.jpegTrellisQuantisation = true; + this.options.jpegOvershootDeringing = true; + this.options.jpegOptimiseScans = true; + this.options.jpegProgressive = true; + this.options.jpegQuantisationTable = 3; + } + } else { + throw is.invalidParameterError('mozjpeg', 'boolean', options.mozjpeg); + } + } + const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation; + if (is.defined(trellisQuantisation)) { + this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation); + } + if (is.defined(options.overshootDeringing)) { + this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing); + } + const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans; + if (is.defined(optimiseScans)) { + this._setBooleanOption('jpegOptimiseScans', optimiseScans); + if (optimiseScans) { + this.options.jpegProgressive = true; + } + } + const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable; + if (is.defined(quantisationTable)) { + if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) { + this.options.jpegQuantisationTable = quantisationTable; + } else { + throw is.invalidParameterError('quantisationTable', 'integer between 0 and 8', quantisationTable); + } + } + } + return this._updateFormatOut('jpeg', options); +} + +/** + * Use these PNG options for output image. + * + * By default, PNG output is full colour at 8 bits per pixel. + * + * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel. + * Set `palette` to `true` for slower, indexed PNG output. + * + * For 16 bits per pixel output, convert to `rgb16` via + * {@link /api-colour#tocolourspace|toColourspace}. + * + * @example + * // Convert any input to full colour PNG output + * const data = await sharp(input) + * .png() + * .toBuffer(); + * + * @example + * // Convert any input to indexed PNG output (slower) + * const data = await sharp(input) + * .png({ palette: true }) + * .toBuffer(); + * + * @example + * // Output 16 bits per pixel RGB(A) + * const data = await sharp(input) + * .toColourspace('rgb16') + * .png() + * .toBuffer(); + * + * @param {Object} [options] + * @param {boolean} [options.progressive=false] - use progressive (interlace) scan + * @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) + * @param {boolean} [options.adaptiveFiltering=false] - use adaptive row filtering + * @param {boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support + * @param {number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, sets `palette` to `true` + * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` + * @param {number} [options.colours=256] - maximum number of palette entries, sets `palette` to `true` + * @param {number} [options.colors=256] - alternative spelling of `options.colours`, sets `palette` to `true` + * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, sets `palette` to `true` + * @param {boolean} [options.force=true] - force PNG output, otherwise attempt to use input format + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function png (options) { + if (is.object(options)) { + if (is.defined(options.progressive)) { + this._setBooleanOption('pngProgressive', options.progressive); + } + if (is.defined(options.compressionLevel)) { + if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) { + this.options.pngCompressionLevel = options.compressionLevel; + } else { + throw is.invalidParameterError('compressionLevel', 'integer between 0 and 9', options.compressionLevel); + } + } + if (is.defined(options.adaptiveFiltering)) { + this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering); + } + const colours = options.colours || options.colors; + if (is.defined(colours)) { + if (is.integer(colours) && is.inRange(colours, 2, 256)) { + this.options.pngBitdepth = bitdepthFromColourCount(colours); + } else { + throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); + } + } + if (is.defined(options.palette)) { + this._setBooleanOption('pngPalette', options.palette); + } else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) { + this._setBooleanOption('pngPalette', true); + } + if (this.options.pngPalette) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) { + this.options.pngQuality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality); + } + } + if (is.defined(options.effort)) { + if (is.integer(options.effort) && is.inRange(options.effort, 1, 10)) { + this.options.pngEffort = options.effort; + } else { + throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort); + } + } + if (is.defined(options.dither)) { + if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { + this.options.pngDither = options.dither; + } else { + throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); + } + } + } + } + return this._updateFormatOut('png', options); +} + +/** + * Use these WebP options for output image. + * + * @example + * // Convert any input to lossless WebP output + * const data = await sharp(input) + * .webp({ lossless: true }) + * .toBuffer(); + * + * @example + * // Optimise the file size of an animated WebP + * const outputWebp = await sharp(inputWebp, { animated: true }) + * .webp({ effort: 6 }) + * .toBuffer(); + * + * @param {Object} [options] - output options + * @param {number} [options.quality=80] - quality, integer 1-100 + * @param {number} [options.alphaQuality=100] - quality of alpha layer, integer 0-100 + * @param {boolean} [options.lossless=false] - use lossless compression mode + * @param {boolean} [options.nearLossless=false] - use near_lossless compression mode + * @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling + * @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text + * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest) + * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation + * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds) + * @param {boolean} [options.minSize=false] - prevent use of animation key frames to minimise file size (slow) + * @param {boolean} [options.mixed=false] - allow mixture of lossy and lossless animation frames (slow) + * @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function webp (options) { + if (is.object(options)) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + this.options.webpQuality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } + if (is.defined(options.alphaQuality)) { + if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) { + this.options.webpAlphaQuality = options.alphaQuality; + } else { + throw is.invalidParameterError('alphaQuality', 'integer between 0 and 100', options.alphaQuality); + } + } + if (is.defined(options.lossless)) { + this._setBooleanOption('webpLossless', options.lossless); + } + if (is.defined(options.nearLossless)) { + this._setBooleanOption('webpNearLossless', options.nearLossless); + } + if (is.defined(options.smartSubsample)) { + this._setBooleanOption('webpSmartSubsample', options.smartSubsample); + } + if (is.defined(options.preset)) { + if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) { + this.options.webpPreset = options.preset; + } else { + throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset); + } + } + if (is.defined(options.effort)) { + if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) { + this.options.webpEffort = options.effort; + } else { + throw is.invalidParameterError('effort', 'integer between 0 and 6', options.effort); + } + } + if (is.defined(options.minSize)) { + this._setBooleanOption('webpMinSize', options.minSize); + } + if (is.defined(options.mixed)) { + this._setBooleanOption('webpMixed', options.mixed); + } + } + trySetAnimationOptions(options, this.options); + return this._updateFormatOut('webp', options); +} + +/** + * Use these GIF options for the output image. + * + * The first entry in the palette is reserved for transparency. + * + * The palette of the input image will be re-used if possible. + * + * @since 0.30.0 + * + * @example + * // Convert PNG to GIF + * await sharp(pngBuffer) + * .gif() + * .toBuffer(); + * + * @example + * // Convert animated WebP to animated GIF + * await sharp('animated.webp', { animated: true }) + * .toFile('animated.gif'); + * + * @example + * // Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF + * const out = await sharp('in.gif', { animated: true }) + * .resize({ width: 128, height: 128 }) + * .gif({ dither: 0 }) + * .toBuffer(); + * + * @example + * // Lossy file size reduction of animated GIF + * await sharp('in.gif', { animated: true }) + * .gif({ interFrameMaxError: 8 }) + * .toFile('optim.gif'); + * + * @param {Object} [options] - output options + * @param {boolean} [options.reuse=true] - re-use existing palette, otherwise generate new (slow) + * @param {boolean} [options.progressive=false] - use progressive (interlace) scan + * @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256 + * @param {number} [options.colors=256] - alternative spelling of `options.colours` + * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest) + * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) + * @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32 + * @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256 + * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation + * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds) + * @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function gif (options) { + if (is.object(options)) { + if (is.defined(options.reuse)) { + this._setBooleanOption('gifReuse', options.reuse); + } + if (is.defined(options.progressive)) { + this._setBooleanOption('gifProgressive', options.progressive); + } + const colours = options.colours || options.colors; + if (is.defined(colours)) { + if (is.integer(colours) && is.inRange(colours, 2, 256)) { + this.options.gifBitdepth = bitdepthFromColourCount(colours); + } else { + throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); + } + } + if (is.defined(options.effort)) { + if (is.number(options.effort) && is.inRange(options.effort, 1, 10)) { + this.options.gifEffort = options.effort; + } else { + throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort); + } + } + if (is.defined(options.dither)) { + if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { + this.options.gifDither = options.dither; + } else { + throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); + } + } + if (is.defined(options.interFrameMaxError)) { + if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) { + this.options.gifInterFrameMaxError = options.interFrameMaxError; + } else { + throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError); + } + } + if (is.defined(options.interPaletteMaxError)) { + if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) { + this.options.gifInterPaletteMaxError = options.interPaletteMaxError; + } else { + throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError); + } + } + } + trySetAnimationOptions(options, this.options); + return this._updateFormatOut('gif', options); +} + +/* istanbul ignore next */ +/** + * Use these JP2 options for output image. + * + * Requires libvips compiled with support for OpenJPEG. + * The prebuilt binaries do not include this - see + * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. + * + * @example + * // Convert any input to lossless JP2 output + * const data = await sharp(input) + * .jp2({ lossless: true }) + * .toBuffer(); + * + * @example + * // Convert any input to very high quality JP2 output + * const data = await sharp(input) + * .jp2({ + * quality: 100, + * chromaSubsampling: '4:4:4' + * }) + * .toBuffer(); + * + * @since 0.29.1 + * + * @param {Object} [options] - output options + * @param {number} [options.quality=80] - quality, integer 1-100 + * @param {boolean} [options.lossless=false] - use lossless compression mode + * @param {number} [options.tileWidth=512] - horizontal tile size + * @param {number} [options.tileHeight=512] - vertical tile size + * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function jp2 (options) { + if (!this.constructor.format.jp2k.output.buffer) { + throw errJp2Save(); + } + if (is.object(options)) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + this.options.jp2Quality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } + if (is.defined(options.lossless)) { + if (is.bool(options.lossless)) { + this.options.jp2Lossless = options.lossless; + } else { + throw is.invalidParameterError('lossless', 'boolean', options.lossless); + } + } + if (is.defined(options.tileWidth)) { + if (is.integer(options.tileWidth) && is.inRange(options.tileWidth, 1, 32768)) { + this.options.jp2TileWidth = options.tileWidth; + } else { + throw is.invalidParameterError('tileWidth', 'integer between 1 and 32768', options.tileWidth); + } + } + if (is.defined(options.tileHeight)) { + if (is.integer(options.tileHeight) && is.inRange(options.tileHeight, 1, 32768)) { + this.options.jp2TileHeight = options.tileHeight; + } else { + throw is.invalidParameterError('tileHeight', 'integer between 1 and 32768', options.tileHeight); + } + } + if (is.defined(options.chromaSubsampling)) { + if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { + this.options.jp2ChromaSubsampling = options.chromaSubsampling; + } else { + throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling); + } + } + } + return this._updateFormatOut('jp2', options); +} + +/** + * Set animation options if available. + * @private + * + * @param {Object} [source] - output options + * @param {number} [source.loop=0] - number of animation iterations, use 0 for infinite animation + * @param {number[]} [source.delay] - list of delays between animation frames (in milliseconds) + * @param {Object} [target] - target object for valid options + * @throws {Error} Invalid options + */ +function trySetAnimationOptions (source, target) { + if (is.object(source) && is.defined(source.loop)) { + if (is.integer(source.loop) && is.inRange(source.loop, 0, 65535)) { + target.loop = source.loop; + } else { + throw is.invalidParameterError('loop', 'integer between 0 and 65535', source.loop); + } + } + if (is.object(source) && is.defined(source.delay)) { + // We allow singular values as well + if (is.integer(source.delay) && is.inRange(source.delay, 0, 65535)) { + target.delay = [source.delay]; + } else if ( + Array.isArray(source.delay) && + source.delay.every(is.integer) && + source.delay.every(v => is.inRange(v, 0, 65535))) { + target.delay = source.delay; + } else { + throw is.invalidParameterError('delay', 'integer or an array of integers between 0 and 65535', source.delay); + } + } +} + +/** + * Use these TIFF options for output image. + * + * The `density` can be set in pixels/inch via {@link #withmetadata|withMetadata} + * instead of providing `xres` and `yres` in pixels/mm. + * + * @example + * // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output + * sharp('input.svg') + * .tiff({ + * compression: 'lzw', + * bitdepth: 1 + * }) + * .toFile('1-bpp-output.tiff') + * .then(info => { ... }); + * + * @param {Object} [options] - output options + * @param {number} [options.quality=80] - quality, integer 1-100 + * @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format + * @param {string} [options.compression='jpeg'] - compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k + * @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float + * @param {boolean} [options.pyramid=false] - write an image pyramid + * @param {boolean} [options.tile=false] - write a tiled tiff + * @param {number} [options.tileWidth=256] - horizontal tile size + * @param {number} [options.tileHeight=256] - vertical tile size + * @param {number} [options.xres=1.0] - horizontal resolution in pixels/mm + * @param {number} [options.yres=1.0] - vertical resolution in pixels/mm + * @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm + * @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit + * @param {boolean} [options.miniswhite=false] - write 1-bit images as miniswhite + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function tiff (options) { + if (is.object(options)) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + this.options.tiffQuality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } + if (is.defined(options.bitdepth)) { + if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [1, 2, 4, 8])) { + this.options.tiffBitdepth = options.bitdepth; + } else { + throw is.invalidParameterError('bitdepth', '1, 2, 4 or 8', options.bitdepth); + } + } + // tiling + if (is.defined(options.tile)) { + this._setBooleanOption('tiffTile', options.tile); + } + if (is.defined(options.tileWidth)) { + if (is.integer(options.tileWidth) && options.tileWidth > 0) { + this.options.tiffTileWidth = options.tileWidth; + } else { + throw is.invalidParameterError('tileWidth', 'integer greater than zero', options.tileWidth); + } + } + if (is.defined(options.tileHeight)) { + if (is.integer(options.tileHeight) && options.tileHeight > 0) { + this.options.tiffTileHeight = options.tileHeight; + } else { + throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight); + } + } + // miniswhite + if (is.defined(options.miniswhite)) { + this._setBooleanOption('tiffMiniswhite', options.miniswhite); + } + // pyramid + if (is.defined(options.pyramid)) { + this._setBooleanOption('tiffPyramid', options.pyramid); + } + // resolution + if (is.defined(options.xres)) { + if (is.number(options.xres) && options.xres > 0) { + this.options.tiffXres = options.xres; + } else { + throw is.invalidParameterError('xres', 'number greater than zero', options.xres); + } + } + if (is.defined(options.yres)) { + if (is.number(options.yres) && options.yres > 0) { + this.options.tiffYres = options.yres; + } else { + throw is.invalidParameterError('yres', 'number greater than zero', options.yres); + } + } + // compression + if (is.defined(options.compression)) { + if (is.string(options.compression) && is.inArray(options.compression, ['none', 'jpeg', 'deflate', 'packbits', 'ccittfax4', 'lzw', 'webp', 'zstd', 'jp2k'])) { + this.options.tiffCompression = options.compression; + } else { + throw is.invalidParameterError('compression', 'one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k', options.compression); + } + } + // predictor + if (is.defined(options.predictor)) { + if (is.string(options.predictor) && is.inArray(options.predictor, ['none', 'horizontal', 'float'])) { + this.options.tiffPredictor = options.predictor; + } else { + throw is.invalidParameterError('predictor', 'one of: none, horizontal, float', options.predictor); + } + } + // resolutionUnit + if (is.defined(options.resolutionUnit)) { + if (is.string(options.resolutionUnit) && is.inArray(options.resolutionUnit, ['inch', 'cm'])) { + this.options.tiffResolutionUnit = options.resolutionUnit; + } else { + throw is.invalidParameterError('resolutionUnit', 'one of: inch, cm', options.resolutionUnit); + } + } + } + return this._updateFormatOut('tiff', options); +} + +/** + * Use these AVIF options for output image. + * + * AVIF image sequences are not supported. + * Prebuilt binaries support a bitdepth of 8 only. + * + * @example + * const data = await sharp(input) + * .avif({ effort: 2 }) + * .toBuffer(); + * + * @example + * const data = await sharp(input) + * .avif({ lossless: true }) + * .toBuffer(); + * + * @since 0.27.0 + * + * @param {Object} [options] - output options + * @param {number} [options.quality=50] - quality, integer 1-100 + * @param {boolean} [options.lossless=false] - use lossless compression + * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest) + * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling + * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function avif (options) { + return this.heif({ ...options, compression: 'av1' }); +} + +/** + * Use these HEIF options for output image. + * + * Support for patent-encumbered HEIC images using `hevc` compression requires the use of a + * globally-installed libvips compiled with support for libheif, libde265 and x265. + * + * @example + * const data = await sharp(input) + * .heif({ compression: 'hevc' }) + * .toBuffer(); + * + * @since 0.23.0 + * + * @param {Object} options - output options + * @param {string} options.compression - compression format: av1, hevc + * @param {number} [options.quality=50] - quality, integer 1-100 + * @param {boolean} [options.lossless=false] - use lossless compression + * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest) + * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling + * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function heif (options) { + if (is.object(options)) { + if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) { + this.options.heifCompression = options.compression; + } else { + throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression); + } + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + this.options.heifQuality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } + if (is.defined(options.lossless)) { + if (is.bool(options.lossless)) { + this.options.heifLossless = options.lossless; + } else { + throw is.invalidParameterError('lossless', 'boolean', options.lossless); + } + } + if (is.defined(options.effort)) { + if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) { + this.options.heifEffort = options.effort; + } else { + throw is.invalidParameterError('effort', 'integer between 0 and 9', options.effort); + } + } + if (is.defined(options.chromaSubsampling)) { + if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { + this.options.heifChromaSubsampling = options.chromaSubsampling; + } else { + throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling); + } + } + if (is.defined(options.bitdepth)) { + if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [8, 10, 12])) { + if (options.bitdepth !== 8 && this.constructor.versions.heif) { + throw is.invalidParameterError('bitdepth when using prebuilt binaries', 8, options.bitdepth); + } + this.options.heifBitdepth = options.bitdepth; + } else { + throw is.invalidParameterError('bitdepth', '8, 10 or 12', options.bitdepth); + } + } + } else { + throw is.invalidParameterError('options', 'Object', options); + } + return this._updateFormatOut('heif', options); +} + +/** + * Use these JPEG-XL (JXL) options for output image. + * + * This feature is experimental, please do not use in production systems. + * + * Requires libvips compiled with support for libjxl. + * The prebuilt binaries do not include this - see + * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. + * + * Image metadata (EXIF, XMP) is unsupported. + * + * @since 0.31.3 + * + * @param {Object} [options] - output options + * @param {number} [options.distance=1.0] - maximum encoding error, between 0 (highest quality) and 15 (lowest quality) + * @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified + * @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality) + * @param {boolean} [options.lossless=false] - use lossless compression + * @param {number} [options.effort=7] - CPU effort, between 3 (fastest) and 9 (slowest) + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function jxl (options) { + if (is.object(options)) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + // https://github.com/libjxl/libjxl/blob/0aeea7f180bafd6893c1db8072dcb67d2aa5b03d/tools/cjxl_main.cc#L640-L644 + this.options.jxlDistance = options.quality >= 30 + ? 0.1 + (100 - options.quality) * 0.09 + : 53 / 3000 * options.quality * options.quality - 23 / 20 * options.quality + 25; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } else if (is.defined(options.distance)) { + if (is.number(options.distance) && is.inRange(options.distance, 0, 15)) { + this.options.jxlDistance = options.distance; + } else { + throw is.invalidParameterError('distance', 'number between 0.0 and 15.0', options.distance); + } + } + if (is.defined(options.decodingTier)) { + if (is.integer(options.decodingTier) && is.inRange(options.decodingTier, 0, 4)) { + this.options.jxlDecodingTier = options.decodingTier; + } else { + throw is.invalidParameterError('decodingTier', 'integer between 0 and 4', options.decodingTier); + } + } + if (is.defined(options.lossless)) { + if (is.bool(options.lossless)) { + this.options.jxlLossless = options.lossless; + } else { + throw is.invalidParameterError('lossless', 'boolean', options.lossless); + } + } + if (is.defined(options.effort)) { + if (is.integer(options.effort) && is.inRange(options.effort, 3, 9)) { + this.options.jxlEffort = options.effort; + } else { + throw is.invalidParameterError('effort', 'integer between 3 and 9', options.effort); + } + } + } + return this._updateFormatOut('jxl', options); +} + +/** + * Force output to be raw, uncompressed pixel data. + * Pixel ordering is left-to-right, top-to-bottom, without padding. + * Channel ordering will be RGB or RGBA for non-greyscale colourspaces. + * + * @example + * // Extract raw, unsigned 8-bit RGB pixel data from JPEG input + * const { data, info } = await sharp('input.jpg') + * .raw() + * .toBuffer({ resolveWithObject: true }); + * + * @example + * // Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input + * const data = await sharp('input.png') + * .ensureAlpha() + * .extractChannel(3) + * .toColourspace('b-w') + * .raw({ depth: 'ushort' }) + * .toBuffer(); + * + * @param {Object} [options] - output options + * @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function raw (options) { + if (is.object(options)) { + if (is.defined(options.depth)) { + if (is.string(options.depth) && is.inArray(options.depth, + ['char', 'uchar', 'short', 'ushort', 'int', 'uint', 'float', 'complex', 'double', 'dpcomplex'] + )) { + this.options.rawDepth = options.depth; + } else { + throw is.invalidParameterError('depth', 'one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex', options.depth); + } + } + } + return this._updateFormatOut('raw'); +} + +/** + * Use tile-based deep zoom (image pyramid) output. + * + * Set the format and options for tile images via the `toFormat`, `jpeg`, `png` or `webp` functions. + * Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed archive file format. + * + * The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`. + * + * Requires libvips compiled with support for libgsf. + * The prebuilt binaries do not include this - see + * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. + * + * @example + * sharp('input.tiff') + * .png() + * .tile({ + * size: 512 + * }) + * .toFile('output.dz', function(err, info) { + * // output.dzi is the Deep Zoom XML definition + * // output_files contains 512x512 tiles grouped by zoom level + * }); + * + * @example + * const zipFileWithTiles = await sharp(input) + * .tile({ basename: "tiles" }) + * .toBuffer(); + * + * @example + * const iiififier = sharp().tile({ layout: "iiif" }); + * readableStream + * .pipe(iiififier) + * .pipe(writeableStream); + * + * @param {Object} [options] + * @param {number} [options.size=256] tile size in pixels, a value between 1 and 8192. + * @param {number} [options.overlap=0] tile overlap in pixels, a value between 0 and 8192. + * @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90. + * @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency. + * @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout. + * @param {number} [options.skipBlanks=-1] Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise. + * @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file). + * @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. + * @param {boolean} [options.centre=false] centre image in tile. + * @param {boolean} [options.center=false] alternative spelling of centre. + * @param {string} [options.id='https://example.com/iiif'] when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` + * @param {string} [options.basename] the name of the directory within the zip file when container is `zip`. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function tile (options) { + if (is.object(options)) { + // Size of square tiles, in pixels + if (is.defined(options.size)) { + if (is.integer(options.size) && is.inRange(options.size, 1, 8192)) { + this.options.tileSize = options.size; + } else { + throw is.invalidParameterError('size', 'integer between 1 and 8192', options.size); + } + } + // Overlap of tiles, in pixels + if (is.defined(options.overlap)) { + if (is.integer(options.overlap) && is.inRange(options.overlap, 0, 8192)) { + if (options.overlap > this.options.tileSize) { + throw is.invalidParameterError('overlap', `<= size (${this.options.tileSize})`, options.overlap); + } + this.options.tileOverlap = options.overlap; + } else { + throw is.invalidParameterError('overlap', 'integer between 0 and 8192', options.overlap); + } + } + // Container + if (is.defined(options.container)) { + if (is.string(options.container) && is.inArray(options.container, ['fs', 'zip'])) { + this.options.tileContainer = options.container; + } else { + throw is.invalidParameterError('container', 'one of: fs, zip', options.container); + } + } + // Layout + if (is.defined(options.layout)) { + if (is.string(options.layout) && is.inArray(options.layout, ['dz', 'google', 'iiif', 'iiif3', 'zoomify'])) { + this.options.tileLayout = options.layout; + } else { + throw is.invalidParameterError('layout', 'one of: dz, google, iiif, iiif3, zoomify', options.layout); + } + } + // Angle of rotation, + if (is.defined(options.angle)) { + if (is.integer(options.angle) && !(options.angle % 90)) { + this.options.tileAngle = options.angle; + } else { + throw is.invalidParameterError('angle', 'positive/negative multiple of 90', options.angle); + } + } + // Background colour + this._setBackgroundColourOption('tileBackground', options.background); + // Depth of tiles + if (is.defined(options.depth)) { + if (is.string(options.depth) && is.inArray(options.depth, ['onepixel', 'onetile', 'one'])) { + this.options.tileDepth = options.depth; + } else { + throw is.invalidParameterError('depth', 'one of: onepixel, onetile, one', options.depth); + } + } + // Threshold to skip blank tiles + if (is.defined(options.skipBlanks)) { + if (is.integer(options.skipBlanks) && is.inRange(options.skipBlanks, -1, 65535)) { + this.options.tileSkipBlanks = options.skipBlanks; + } else { + throw is.invalidParameterError('skipBlanks', 'integer between -1 and 255/65535', options.skipBlanks); + } + } else if (is.defined(options.layout) && options.layout === 'google') { + this.options.tileSkipBlanks = 5; + } + // Center image in tile + const centre = is.bool(options.center) ? options.center : options.centre; + if (is.defined(centre)) { + this._setBooleanOption('tileCentre', centre); + } + // @id attribute for IIIF layout + if (is.defined(options.id)) { + if (is.string(options.id)) { + this.options.tileId = options.id; + } else { + throw is.invalidParameterError('id', 'string', options.id); + } + } + // Basename for zip container + if (is.defined(options.basename)) { + if (is.string(options.basename)) { + this.options.tileBasename = options.basename; + } else { + throw is.invalidParameterError('basename', 'string', options.basename); + } + } + } + // Format + if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) { + this.options.tileFormat = this.options.formatOut; + } else if (this.options.formatOut !== 'input') { + throw is.invalidParameterError('format', 'one of: jpeg, png, webp', this.options.formatOut); + } + return this._updateFormatOut('dz'); +} + +/** + * Set a timeout for processing, in seconds. + * Use a value of zero to continue processing indefinitely, the default behaviour. + * + * The clock starts when libvips opens an input image for processing. + * Time spent waiting for a libuv thread to become available is not included. + * + * @example + * // Ensure processing takes no longer than 3 seconds + * try { + * const data = await sharp(input) + * .blur(1000) + * .timeout({ seconds: 3 }) + * .toBuffer(); + * } catch (err) { + * if (err.message.includes('timeout')) { ... } + * } + * + * @since 0.29.2 + * + * @param {Object} options + * @param {number} options.seconds - Number of seconds after which processing will be stopped + * @returns {Sharp} + */ +function timeout (options) { + if (!is.plainObject(options)) { + throw is.invalidParameterError('options', 'object', options); + } + if (is.integer(options.seconds) && is.inRange(options.seconds, 0, 3600)) { + this.options.timeoutSeconds = options.seconds; + } else { + throw is.invalidParameterError('seconds', 'integer between 0 and 3600', options.seconds); + } + return this; +} + +/** + * Update the output format unless options.force is false, + * in which case revert to input format. + * @private + * @param {string} formatOut + * @param {Object} [options] + * @param {boolean} [options.force=true] - force output format, otherwise attempt to use input format + * @returns {Sharp} + */ +function _updateFormatOut (formatOut, options) { + if (!(is.object(options) && options.force === false)) { + this.options.formatOut = formatOut; + } + return this; +} + +/** + * Update a boolean attribute of the this.options Object. + * @private + * @param {string} key + * @param {boolean} val + * @throws {Error} Invalid key + */ +function _setBooleanOption (key, val) { + if (is.bool(val)) { + this.options[key] = val; + } else { + throw is.invalidParameterError(key, 'boolean', val); + } +} + +/** + * Called by a WriteableStream to notify us it is ready for data. + * @private + */ +function _read () { + /* istanbul ignore else */ + if (!this.options.streamOut) { + this.options.streamOut = true; + const stack = Error(); + this._pipeline(undefined, stack); + } +} + +/** + * Invoke the C++ image processing pipeline + * Supports callback, stream and promise variants + * @private + */ +function _pipeline (callback, stack) { + if (typeof callback === 'function') { + // output=file/buffer + if (this._isStreamInput()) { + // output=file/buffer, input=stream + this.on('finish', () => { + this._flattenBufferIn(); + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, data, info); + } + }); + }); + } else { + // output=file/buffer, input=file/buffer + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, data, info); + } + }); + } + return this; + } else if (this.options.streamOut) { + // output=stream + if (this._isStreamInput()) { + // output=stream, input=stream + this.once('finish', () => { + this._flattenBufferIn(); + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + this.emit('error', is.nativeError(err, stack)); + } else { + this.emit('info', info); + this.push(data); + } + this.push(null); + this.on('end', () => this.emit('close')); + }); + }); + if (this.streamInFinished) { + this.emit('finish'); + } + } else { + // output=stream, input=file/buffer + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + this.emit('error', is.nativeError(err, stack)); + } else { + this.emit('info', info); + this.push(data); + } + this.push(null); + this.on('end', () => this.emit('close')); + }); + } + return this; + } else { + // output=promise + if (this._isStreamInput()) { + // output=promise, input=stream + return new Promise((resolve, reject) => { + this.once('finish', () => { + this._flattenBufferIn(); + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + if (this.options.resolveWithObject) { + resolve({ data, info }); + } else { + resolve(data); + } + } + }); + }); + }); + } else { + // output=promise, input=file/buffer + return new Promise((resolve, reject) => { + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + if (this.options.resolveWithObject) { + resolve({ data, info }); + } else { + resolve(data); + } + } + }); + }); + } + } +} + +/** + * Decorate the Sharp prototype with output-related functions. + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + // Public + toFile, + toBuffer, + keepExif, + withExif, + withExifMerge, + keepIccProfile, + withIccProfile, + keepMetadata, + withMetadata, + toFormat, + jpeg, + jp2, + png, + webp, + tiff, + avif, + heif, + jxl, + gif, + raw, + tile, + timeout, + // Private + _updateFormatOut, + _setBooleanOption, + _read, + _pipeline + }); +}; diff --git a/node_modules/sharp/lib/resize.js b/node_modules/sharp/lib/resize.js new file mode 100644 index 0000000000000000000000000000000000000000..e31f85271d6f38f9928fb7c25666e1c12b7cf396 --- /dev/null +++ b/node_modules/sharp/lib/resize.js @@ -0,0 +1,587 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const is = require('./is'); + +/** + * Weighting to apply when using contain/cover fit. + * @member + * @private + */ +const gravity = { + center: 0, + centre: 0, + north: 1, + east: 2, + south: 3, + west: 4, + northeast: 5, + southeast: 6, + southwest: 7, + northwest: 8 +}; + +/** + * Position to apply when using contain/cover fit. + * @member + * @private + */ +const position = { + top: 1, + right: 2, + bottom: 3, + left: 4, + 'right top': 5, + 'right bottom': 6, + 'left bottom': 7, + 'left top': 8 +}; + +/** + * How to extend the image. + * @member + * @private + */ +const extendWith = { + background: 'background', + copy: 'copy', + repeat: 'repeat', + mirror: 'mirror' +}; + +/** + * Strategies for automagic cover behaviour. + * @member + * @private + */ +const strategy = { + entropy: 16, + attention: 17 +}; + +/** + * Reduction kernels. + * @member + * @private + */ +const kernel = { + nearest: 'nearest', + linear: 'linear', + cubic: 'cubic', + mitchell: 'mitchell', + lanczos2: 'lanczos2', + lanczos3: 'lanczos3' +}; + +/** + * Methods by which an image can be resized to fit the provided dimensions. + * @member + * @private + */ +const fit = { + contain: 'contain', + cover: 'cover', + fill: 'fill', + inside: 'inside', + outside: 'outside' +}; + +/** + * Map external fit property to internal canvas property. + * @member + * @private + */ +const mapFitToCanvas = { + contain: 'embed', + cover: 'crop', + fill: 'ignore_aspect', + inside: 'max', + outside: 'min' +}; + +/** + * @private + */ +function isRotationExpected (options) { + return (options.angle % 360) !== 0 || options.useExifOrientation === true || options.rotationAngle !== 0; +} + +/** + * @private + */ +function isResizeExpected (options) { + return options.width !== -1 || options.height !== -1; +} + +/** + * Resize image to `width`, `height` or `width x height`. + * + * When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are: + * - `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit. + * - `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary. + * - `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions. + * - `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified. + * - `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified. + * + * Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property. + * + * Examples of various values for the fit property when resizing + * + * When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are: + * - `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`. + * - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`. + * - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy. + * + * Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property. + * + * The strategy-based approach initially resizes so one dimension is at its target length + * then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy. + * - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29). + * - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones. + * + * Possible downsizing kernels are: + * - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). + * - `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function). + * - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline). + * - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf). + * - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`. + * - `lanczos3`: Use a Lanczos kernel with `a=3` (the default). + * + * When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators. + * Downsampling kernels without a matching upsampling interpolator map to `cubic`. + * + * Only one resize can occur per pipeline. + * Previous calls to `resize` in the same pipeline will be ignored. + * + * @example + * sharp(input) + * .resize({ width: 100 }) + * .toBuffer() + * .then(data => { + * // 100 pixels wide, auto-scaled height + * }); + * + * @example + * sharp(input) + * .resize({ height: 100 }) + * .toBuffer() + * .then(data => { + * // 100 pixels high, auto-scaled width + * }); + * + * @example + * sharp(input) + * .resize(200, 300, { + * kernel: sharp.kernel.nearest, + * fit: 'contain', + * position: 'right top', + * background: { r: 255, g: 255, b: 255, alpha: 0.5 } + * }) + * .toFile('output.png') + * .then(() => { + * // output.png is a 200 pixels wide and 300 pixels high image + * // containing a nearest-neighbour scaled version + * // contained within the north-east corner of a semi-transparent white canvas + * }); + * + * @example + * const transformer = sharp() + * .resize({ + * width: 200, + * height: 200, + * fit: sharp.fit.cover, + * position: sharp.strategy.entropy + * }); + * // Read image data from readableStream + * // Write 200px square auto-cropped image data to writableStream + * readableStream + * .pipe(transformer) + * .pipe(writableStream); + * + * @example + * sharp(input) + * .resize(200, 200, { + * fit: sharp.fit.inside, + * withoutEnlargement: true + * }) + * .toFormat('jpeg') + * .toBuffer() + * .then(function(outputBuffer) { + * // outputBuffer contains JPEG image data + * // no wider and no higher than 200 pixels + * // and no larger than the input image + * }); + * + * @example + * sharp(input) + * .resize(200, 200, { + * fit: sharp.fit.outside, + * withoutReduction: true + * }) + * .toFormat('jpeg') + * .toBuffer() + * .then(function(outputBuffer) { + * // outputBuffer contains JPEG image data + * // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio + * // and no smaller than the input image + * }); + * + * @example + * const scaleByHalf = await sharp(input) + * .metadata() + * .then(({ width }) => sharp(input) + * .resize(Math.round(width * 0.5)) + * .toBuffer() + * ); + * + * @param {number} [width] - How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. + * @param {number} [height] - How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. + * @param {Object} [options] + * @param {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority. + * @param {number} [options.height] - An alternative means of specifying `height`. If both are present this takes priority. + * @param {String} [options.fit='cover'] - How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`. + * @param {String} [options.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`. + * @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. + * @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load. + * @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions. + * @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions. + * @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function resize (widthOrOptions, height, options) { + if (isResizeExpected(this.options)) { + this.options.debuglog('ignoring previous resize options'); + } + if (this.options.widthPost !== -1) { + this.options.debuglog('operation order will be: extract, resize, extract'); + } + if (is.defined(widthOrOptions)) { + if (is.object(widthOrOptions) && !is.defined(options)) { + options = widthOrOptions; + } else if (is.integer(widthOrOptions) && widthOrOptions > 0) { + this.options.width = widthOrOptions; + } else { + throw is.invalidParameterError('width', 'positive integer', widthOrOptions); + } + } else { + this.options.width = -1; + } + if (is.defined(height)) { + if (is.integer(height) && height > 0) { + this.options.height = height; + } else { + throw is.invalidParameterError('height', 'positive integer', height); + } + } else { + this.options.height = -1; + } + if (is.object(options)) { + // Width + if (is.defined(options.width)) { + if (is.integer(options.width) && options.width > 0) { + this.options.width = options.width; + } else { + throw is.invalidParameterError('width', 'positive integer', options.width); + } + } + // Height + if (is.defined(options.height)) { + if (is.integer(options.height) && options.height > 0) { + this.options.height = options.height; + } else { + throw is.invalidParameterError('height', 'positive integer', options.height); + } + } + // Fit + if (is.defined(options.fit)) { + const canvas = mapFitToCanvas[options.fit]; + if (is.string(canvas)) { + this.options.canvas = canvas; + } else { + throw is.invalidParameterError('fit', 'valid fit', options.fit); + } + } + // Position + if (is.defined(options.position)) { + const pos = is.integer(options.position) + ? options.position + : strategy[options.position] || position[options.position] || gravity[options.position]; + if (is.integer(pos) && (is.inRange(pos, 0, 8) || is.inRange(pos, 16, 17))) { + this.options.position = pos; + } else { + throw is.invalidParameterError('position', 'valid position/gravity/strategy', options.position); + } + } + // Background + this._setBackgroundColourOption('resizeBackground', options.background); + // Kernel + if (is.defined(options.kernel)) { + if (is.string(kernel[options.kernel])) { + this.options.kernel = kernel[options.kernel]; + } else { + throw is.invalidParameterError('kernel', 'valid kernel name', options.kernel); + } + } + // Without enlargement + if (is.defined(options.withoutEnlargement)) { + this._setBooleanOption('withoutEnlargement', options.withoutEnlargement); + } + // Without reduction + if (is.defined(options.withoutReduction)) { + this._setBooleanOption('withoutReduction', options.withoutReduction); + } + // Shrink on load + if (is.defined(options.fastShrinkOnLoad)) { + this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad); + } + } + if (isRotationExpected(this.options) && isResizeExpected(this.options)) { + this.options.rotateBeforePreExtract = true; + } + return this; +} + +/** + * Extend / pad / extrude one or more edges of the image with either + * the provided background colour or pixels derived from the image. + * This operation will always occur after resizing and extraction, if any. + * + * @example + * // Resize to 140 pixels wide, then add 10 transparent pixels + * // to the top, left and right edges and 20 to the bottom edge + * sharp(input) + * .resize(140) + * .extend({ + * top: 10, + * bottom: 20, + * left: 10, + * right: 10, + * background: { r: 0, g: 0, b: 0, alpha: 0 } + * }) + * ... + * +* @example + * // Add a row of 10 red pixels to the bottom + * sharp(input) + * .extend({ + * bottom: 10, + * background: 'red' + * }) + * ... + * + * @example + * // Extrude image by 8 pixels to the right, mirroring existing right hand edge + * sharp(input) + * .extend({ + * right: 8, + * background: 'mirror' + * }) + * ... + * + * @param {(number|Object)} extend - single pixel count to add to all edges or an Object with per-edge counts + * @param {number} [extend.top=0] + * @param {number} [extend.left=0] + * @param {number} [extend.bottom=0] + * @param {number} [extend.right=0] + * @param {String} [extend.extendWith='background'] - populate new pixels using this method, one of: background, copy, repeat, mirror. + * @param {String|Object} [extend.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. + * @returns {Sharp} + * @throws {Error} Invalid parameters +*/ +function extend (extend) { + if (is.integer(extend) && extend > 0) { + this.options.extendTop = extend; + this.options.extendBottom = extend; + this.options.extendLeft = extend; + this.options.extendRight = extend; + } else if (is.object(extend)) { + if (is.defined(extend.top)) { + if (is.integer(extend.top) && extend.top >= 0) { + this.options.extendTop = extend.top; + } else { + throw is.invalidParameterError('top', 'positive integer', extend.top); + } + } + if (is.defined(extend.bottom)) { + if (is.integer(extend.bottom) && extend.bottom >= 0) { + this.options.extendBottom = extend.bottom; + } else { + throw is.invalidParameterError('bottom', 'positive integer', extend.bottom); + } + } + if (is.defined(extend.left)) { + if (is.integer(extend.left) && extend.left >= 0) { + this.options.extendLeft = extend.left; + } else { + throw is.invalidParameterError('left', 'positive integer', extend.left); + } + } + if (is.defined(extend.right)) { + if (is.integer(extend.right) && extend.right >= 0) { + this.options.extendRight = extend.right; + } else { + throw is.invalidParameterError('right', 'positive integer', extend.right); + } + } + this._setBackgroundColourOption('extendBackground', extend.background); + if (is.defined(extend.extendWith)) { + if (is.string(extendWith[extend.extendWith])) { + this.options.extendWith = extendWith[extend.extendWith]; + } else { + throw is.invalidParameterError('extendWith', 'one of: background, copy, repeat, mirror', extend.extendWith); + } + } + } else { + throw is.invalidParameterError('extend', 'integer or object', extend); + } + return this; +} + +/** + * Extract/crop a region of the image. + * + * - Use `extract` before `resize` for pre-resize extraction. + * - Use `extract` after `resize` for post-resize extraction. + * - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order. + * + * @example + * sharp(input) + * .extract({ left: left, top: top, width: width, height: height }) + * .toFile(output, function(err) { + * // Extract a region of the input image, saving in the same format. + * }); + * @example + * sharp(input) + * .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre }) + * .resize(width, height) + * .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost }) + * .toFile(output, function(err) { + * // Extract a region, resize, then extract from the resized image + * }); + * + * @param {Object} options - describes the region to extract using integral pixel values + * @param {number} options.left - zero-indexed offset from left edge + * @param {number} options.top - zero-indexed offset from top edge + * @param {number} options.width - width of region to extract + * @param {number} options.height - height of region to extract + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function extract (options) { + const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre'; + if (this.options[`width${suffix}`] !== -1) { + this.options.debuglog('ignoring previous extract options'); + } + ['left', 'top', 'width', 'height'].forEach(function (name) { + const value = options[name]; + if (is.integer(value) && value >= 0) { + this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value; + } else { + throw is.invalidParameterError(name, 'integer', value); + } + }, this); + // Ensure existing rotation occurs before pre-resize extraction + if (isRotationExpected(this.options) && !isResizeExpected(this.options)) { + if (this.options.widthPre === -1 || this.options.widthPost === -1) { + this.options.rotateBeforePreExtract = true; + } + } + return this; +} + +/** + * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel. + * + * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels. + * + * If the result of this operation would trim an image to nothing then no change is made. + * + * The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties. + * + * @example + * // Trim pixels with a colour similar to that of the top-left pixel. + * await sharp(input) + * .trim() + * .toFile(output); + * + * @example + * // Trim pixels with the exact same colour as that of the top-left pixel. + * await sharp(input) + * .trim({ + * threshold: 0 + * }) + * .toFile(output); + * + * @example + * // Assume input is line art and trim only pixels with a similar colour to red. + * const output = await sharp(input) + * .trim({ + * background: "#FF0000", + * lineArt: true + * }) + * .toBuffer(); + * + * @example + * // Trim all "yellow-ish" pixels, being more lenient with the higher threshold. + * const output = await sharp(input) + * .trim({ + * background: "yellow", + * threshold: 42, + * }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. + * @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number. + * @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic? + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function trim (options) { + this.options.trimThreshold = 10; + if (is.defined(options)) { + if (is.object(options)) { + if (is.defined(options.background)) { + this._setBackgroundColourOption('trimBackground', options.background); + } + if (is.defined(options.threshold)) { + if (is.number(options.threshold) && options.threshold >= 0) { + this.options.trimThreshold = options.threshold; + } else { + throw is.invalidParameterError('threshold', 'positive number', options.threshold); + } + } + if (is.defined(options.lineArt)) { + this._setBooleanOption('trimLineArt', options.lineArt); + } + } else { + throw is.invalidParameterError('trim', 'object', options); + } + } + if (isRotationExpected(this.options)) { + this.options.rotateBeforePreExtract = true; + } + return this; +} + +/** + * Decorate the Sharp prototype with resize-related functions. + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + resize, + extend, + extract, + trim + }); + // Class attributes + Sharp.gravity = gravity; + Sharp.strategy = strategy; + Sharp.kernel = kernel; + Sharp.fit = fit; + Sharp.position = position; +}; diff --git a/node_modules/sharp/lib/sharp.js b/node_modules/sharp/lib/sharp.js new file mode 100644 index 0000000000000000000000000000000000000000..3428c5fefae5c7fc02f18a6a9026ac6a7df190e4 --- /dev/null +++ b/node_modules/sharp/lib/sharp.js @@ -0,0 +1,114 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +// Inspects the runtime environment and exports the relevant sharp.node binary + +const { familySync, versionSync } = require('detect-libc'); + +const { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips'); +const runtimePlatform = runtimePlatformArch(); + +const paths = [ + `../src/build/Release/sharp-${runtimePlatform}.node`, + '../src/build/Release/sharp-wasm32.node', + `@img/sharp-${runtimePlatform}/sharp.node`, + '@img/sharp-wasm32/sharp.node' +]; + +let sharp; +const errors = []; +for (const path of paths) { + try { + sharp = require(path); + break; + } catch (err) { + /* istanbul ignore next */ + errors.push(err); + } +} + +/* istanbul ignore next */ +if (sharp) { + module.exports = sharp; +} else { + const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os)); + + const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`]; + errors.forEach(err => { + if (err.code !== 'MODULE_NOT_FOUND') { + help.push(`${err.code}: ${err.message}`); + } + }); + const messages = errors.map(err => err.message).join(' '); + help.push('Possible solutions:'); + // Common error messages + if (isUnsupportedNodeRuntime()) { + const { found, expected } = isUnsupportedNodeRuntime(); + help.push( + '- Please upgrade Node.js:', + ` Found ${found}`, + ` Requires ${expected}` + ); + } else if (prebuiltPlatforms.includes(runtimePlatform)) { + const [os, cpu] = runtimePlatform.split('-'); + const libc = os.endsWith('musl') ? ' --libc=musl' : ''; + help.push( + '- Ensure optional dependencies can be installed:', + ' npm install --include=optional sharp', + '- Ensure your package manager supports multi-platform installation:', + ' See https://sharp.pixelplumbing.com/install#cross-platform', + '- Add platform-specific dependencies:', + ` npm install --os=${os.replace('musl', '')}${libc} --cpu=${cpu} sharp` + ); + } else { + help.push( + `- Manually install libvips >= ${minimumLibvipsVersion}`, + '- Add experimental WebAssembly-based dependencies:', + ' npm install --cpu=wasm32 sharp', + ' npm install @img/sharp-wasm32' + ); + } + if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) { + try { + const { config } = require(`@img/sharp-libvips-${runtimePlatform}/package`); + const libcFound = `${familySync()} ${versionSync()}`; + const libcRequires = `${config.musl ? 'musl' : 'glibc'} ${config.musl || config.glibc}`; + help.push( + '- Update your OS:', + ` Found ${libcFound}`, + ` Requires ${libcRequires}` + ); + } catch (errEngines) {} + } + if (isLinux && /\/snap\/core[0-9]{2}/.test(messages)) { + help.push( + '- Remove the Node.js Snap, which does not support native modules', + ' snap remove node' + ); + } + if (isMacOs && /Incompatible library version/.test(messages)) { + help.push( + '- Update Homebrew:', + ' brew update && brew upgrade vips' + ); + } + if (errors.some(err => err.code === 'ERR_DLOPEN_DISABLED')) { + help.push('- Run Node.js without using the --no-addons flag'); + } + // Link to installation docs + if (isWindows && /The specified procedure could not be found/.test(messages)) { + help.push( + '- Using the canvas package on Windows?', + ' See https://sharp.pixelplumbing.com/install#canvas-and-windows', + '- Check for outdated versions of sharp in the dependency tree:', + ' npm ls sharp' + ); + } + help.push( + '- Consult the installation documentation:', + ' See https://sharp.pixelplumbing.com/install' + ); + throw new Error(help.join('\n')); +} diff --git a/node_modules/sharp/lib/utility.js b/node_modules/sharp/lib/utility.js new file mode 100644 index 0000000000000000000000000000000000000000..89ee9dfdb4916afe1d111aaddd1c8a61faa90955 --- /dev/null +++ b/node_modules/sharp/lib/utility.js @@ -0,0 +1,296 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const events = require('node:events'); +const detectLibc = require('detect-libc'); + +const is = require('./is'); +const { runtimePlatformArch } = require('./libvips'); +const sharp = require('./sharp'); + +const runtimePlatform = runtimePlatformArch(); +const libvipsVersion = sharp.libvipsVersion(); + +/** + * An Object containing nested boolean values representing the available input and output formats/methods. + * @member + * @example + * console.log(sharp.format); + * @returns {Object} + */ +const format = sharp.format(); +format.heif.output.alias = ['avif', 'heic']; +format.jpeg.output.alias = ['jpe', 'jpg']; +format.tiff.output.alias = ['tif']; +format.jp2k.output.alias = ['j2c', 'j2k', 'jp2', 'jpx']; + +/** + * An Object containing the available interpolators and their proper values + * @readonly + * @enum {string} + */ +const interpolators = { + /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */ + nearest: 'nearest', + /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */ + bilinear: 'bilinear', + /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */ + bicubic: 'bicubic', + /** [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. */ + locallyBoundedBicubic: 'lbb', + /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */ + nohalo: 'nohalo', + /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */ + vertexSplitQuadraticBasisSpline: 'vsqbs' +}; + +/** + * An Object containing the version numbers of sharp, libvips + * and (when using prebuilt binaries) its dependencies. + * + * @member + * @example + * console.log(sharp.versions); + */ +let versions = { + vips: libvipsVersion.semver +}; +/* istanbul ignore next */ +if (!libvipsVersion.isGlobal) { + if (!libvipsVersion.isWasm) { + try { + versions = require(`@img/sharp-${runtimePlatform}/versions`); + } catch (_) { + try { + versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`); + } catch (_) {} + } + } else { + try { + versions = require('@img/sharp-wasm32/versions'); + } catch (_) {} + } +} +versions.sharp = require('../package.json').version; + +/* istanbul ignore next */ +if (versions.heif && format.heif) { + // Prebuilt binaries provide AV1 + format.heif.input.fileSuffix = ['.avif']; + format.heif.output.alias = ['avif']; +} + +/** + * Gets or, when options are provided, sets the limits of _libvips'_ operation cache. + * Existing entries in the cache will be trimmed after any change in limits. + * This method always returns cache statistics, + * useful for determining how much working memory is required for a particular task. + * + * @example + * const stats = sharp.cache(); + * @example + * sharp.cache( { items: 200 } ); + * sharp.cache( { files: 0 } ); + * sharp.cache(false); + * + * @param {Object|boolean} [options=true] - Object with the following attributes, or boolean where true uses default cache settings and false removes all caching + * @param {number} [options.memory=50] - is the maximum memory in MB to use for this cache + * @param {number} [options.files=20] - is the maximum number of files to hold open + * @param {number} [options.items=100] - is the maximum number of operations to cache + * @returns {Object} + */ +function cache (options) { + if (is.bool(options)) { + if (options) { + // Default cache settings of 50MB, 20 files, 100 items + return sharp.cache(50, 20, 100); + } else { + return sharp.cache(0, 0, 0); + } + } else if (is.object(options)) { + return sharp.cache(options.memory, options.files, options.items); + } else { + return sharp.cache(); + } +} +cache(true); + +/** + * Gets or, when a concurrency is provided, sets + * the maximum number of threads _libvips_ should use to process _each image_. + * These are from a thread pool managed by glib, + * which helps avoid the overhead of creating new threads. + * + * This method always returns the current concurrency. + * + * The default value is the number of CPU cores, + * except when using glibc-based Linux without jemalloc, + * where the default is `1` to help reduce memory fragmentation. + * + * A value of `0` will reset this to the number of CPU cores. + * + * Some image format libraries spawn additional threads, + * e.g. libaom manages its own 4 threads when encoding AVIF images, + * and these are independent of the value set here. + * + * The maximum number of images that sharp can process in parallel + * is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable, + * which defaults to 4. + * + * https://nodejs.org/api/cli.html#uv_threadpool_sizesize + * + * For example, by default, a machine with 8 CPU cores will process + * 4 images in parallel and use up to 8 threads per image, + * so there will be up to 32 concurrent threads. + * + * @example + * const threads = sharp.concurrency(); // 4 + * sharp.concurrency(2); // 2 + * sharp.concurrency(0); // 4 + * + * @param {number} [concurrency] + * @returns {number} concurrency + */ +function concurrency (concurrency) { + return sharp.concurrency(is.integer(concurrency) ? concurrency : null); +} +/* istanbul ignore next */ +if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) { + // Reduce default concurrency to 1 when using glibc memory allocator + sharp.concurrency(1); +} else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) { + // Reduce default concurrency when musl thread over-subscription detected + sharp.concurrency(require('node:os').availableParallelism()); +} + +/** + * An EventEmitter that emits a `change` event when a task is either: + * - queued, waiting for _libuv_ to provide a worker thread + * - complete + * @member + * @example + * sharp.queue.on('change', function(queueLength) { + * console.log('Queue contains ' + queueLength + ' task(s)'); + * }); + */ +const queue = new events.EventEmitter(); + +/** + * Provides access to internal task counters. + * - queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool. + * - process is the number of resize tasks currently being processed. + * + * @example + * const counters = sharp.counters(); // { queue: 2, process: 4 } + * + * @returns {Object} + */ +function counters () { + return sharp.counters(); +} + +/** + * Get and set use of SIMD vector unit instructions. + * Requires libvips to have been compiled with highway support. + * + * Improves the performance of `resize`, `blur` and `sharpen` operations + * by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON. + * + * @example + * const simd = sharp.simd(); + * // simd is `true` if the runtime use of highway is currently enabled + * @example + * const simd = sharp.simd(false); + * // prevent libvips from using highway at runtime + * + * @param {boolean} [simd=true] + * @returns {boolean} + */ +function simd (simd) { + return sharp.simd(is.bool(simd) ? simd : null); +} + +/** + * Block libvips operations at runtime. + * + * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable, + * which when set will block all "untrusted" operations. + * + * @since 0.32.4 + * + * @example Block all TIFF input. + * sharp.block({ + * operation: ['VipsForeignLoadTiff'] + * }); + * + * @param {Object} options + * @param {Array} options.operation - List of libvips low-level operation names to block. + */ +function block (options) { + if (is.object(options)) { + if (Array.isArray(options.operation) && options.operation.every(is.string)) { + sharp.block(options.operation, true); + } else { + throw is.invalidParameterError('operation', 'Array', options.operation); + } + } else { + throw is.invalidParameterError('options', 'object', options); + } +} + +/** + * Unblock libvips operations at runtime. + * + * This is useful for defining a list of allowed operations. + * + * @since 0.32.4 + * + * @example Block all input except WebP from the filesystem. + * sharp.block({ + * operation: ['VipsForeignLoad'] + * }); + * sharp.unblock({ + * operation: ['VipsForeignLoadWebpFile'] + * }); + * + * @example Block all input except JPEG and PNG from a Buffer or Stream. + * sharp.block({ + * operation: ['VipsForeignLoad'] + * }); + * sharp.unblock({ + * operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer'] + * }); + * + * @param {Object} options + * @param {Array} options.operation - List of libvips low-level operation names to unblock. + */ +function unblock (options) { + if (is.object(options)) { + if (Array.isArray(options.operation) && options.operation.every(is.string)) { + sharp.block(options.operation, false); + } else { + throw is.invalidParameterError('operation', 'Array', options.operation); + } + } else { + throw is.invalidParameterError('options', 'object', options); + } +} + +/** + * Decorate the Sharp class with utility-related functions. + * @private + */ +module.exports = function (Sharp) { + Sharp.cache = cache; + Sharp.concurrency = concurrency; + Sharp.counters = counters; + Sharp.simd = simd; + Sharp.format = format; + Sharp.interpolators = interpolators; + Sharp.versions = versions; + Sharp.queue = queue; + Sharp.block = block; + Sharp.unblock = unblock; +}; diff --git a/node_modules/sharp/package.json b/node_modules/sharp/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6882e53d1faca99558fb64ab5f4599b9fef0ad33 --- /dev/null +++ b/node_modules/sharp/package.json @@ -0,0 +1,222 @@ +{ + "name": "sharp", + "description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images", + "version": "0.33.5", + "author": "Lovell Fuller ", + "homepage": "https://sharp.pixelplumbing.com", + "contributors": [ + "Pierre Inglebert ", + "Jonathan Ong ", + "Chanon Sajjamanochai ", + "Juliano Julio ", + "Daniel Gasienica ", + "Julian Walker ", + "Amit Pitaru ", + "Brandon Aaron ", + "Andreas Lind ", + "Maurus Cuelenaere ", + "Linus Unnebäck ", + "Victor Mateevitsi ", + "Alaric Holloway ", + "Bernhard K. Weisshuhn ", + "Chris Riley ", + "David Carley ", + "John Tobin ", + "Kenton Gray ", + "Felix Bünemann ", + "Samy Al Zahrani ", + "Chintan Thakkar ", + "F. Orlando Galashan ", + "Kleis Auke Wolthuizen ", + "Matt Hirsch ", + "Matthias Thoemmes ", + "Patrick Paskaris ", + "Jérémy Lal ", + "Rahul Nanwani ", + "Alice Monday ", + "Kristo Jorgenson ", + "YvesBos ", + "Guy Maliar ", + "Nicolas Coden ", + "Matt Parrish ", + "Marcel Bretschneider ", + "Matthew McEachen ", + "Jarda Kotěšovec ", + "Kenric D'Souza ", + "Oleh Aleinyk ", + "Marcel Bretschneider ", + "Andrea Bianco ", + "Rik Heywood ", + "Thomas Parisot ", + "Nathan Graves ", + "Tom Lokhorst ", + "Espen Hovlandsdal ", + "Sylvain Dumont ", + "Alun Davies ", + "Aidan Hoolachan ", + "Axel Eirola ", + "Freezy ", + "Daiz ", + "Julian Aubourg ", + "Keith Belovay ", + "Michael B. Klein ", + "Jordan Prudhomme ", + "Ilya Ovdin ", + "Andargor ", + "Paul Neave ", + "Brendan Kennedy ", + "Brychan Bennett-Odlum ", + "Edward Silverton ", + "Roman Malieiev ", + "Tomas Szabo ", + "Robert O'Rourke ", + "Guillermo Alfonso Varela Chouciño ", + "Christian Flintrup ", + "Manan Jadhav ", + "Leon Radley ", + "alza54 ", + "Jacob Smith ", + "Michael Nutt ", + "Brad Parham ", + "Taneli Vatanen ", + "Joris Dugué ", + "Chris Banks ", + "Ompal Singh ", + "Brodan ", + "Ankur Parihar ", + "Brahim Ait elhaj ", + "Mart Jansink ", + "Lachlan Newman ", + "Dennis Beatty ", + "Ingvar Stepanyan ", + "Don Denton " + ], + "scripts": { + "install": "node install/check", + "clean": "rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*", + "test": "npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types", + "test-lint": "semistandard && cpplint", + "test-unit": "nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha", + "test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\"", + "test-leak": "./test/leak/leak.sh", + "test-types": "tsd", + "package-from-local-build": "node npm/from-local-build", + "package-from-github-release": "node npm/from-github-release", + "docs-build": "node docs/build && node docs/search-index/build", + "docs-serve": "cd docs && npx serve", + "docs-publish": "cd docs && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp" + }, + "type": "commonjs", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "files": [ + "install", + "lib", + "src/*.{cc,h,gyp}" + ], + "repository": { + "type": "git", + "url": "git://github.com/lovell/sharp.git" + }, + "keywords": [ + "jpeg", + "png", + "webp", + "avif", + "tiff", + "gif", + "svg", + "jp2", + "dzi", + "image", + "resize", + "thumbnail", + "crop", + "embed", + "libvips", + "vips" + ], + "dependencies": { + "color": "^4.2.3", + "detect-libc": "^2.0.3", + "semver": "^7.6.3" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.33.5", + "@img/sharp-darwin-x64": "0.33.5", + "@img/sharp-libvips-darwin-arm64": "1.0.4", + "@img/sharp-libvips-darwin-x64": "1.0.4", + "@img/sharp-libvips-linux-arm": "1.0.5", + "@img/sharp-libvips-linux-arm64": "1.0.4", + "@img/sharp-libvips-linux-s390x": "1.0.4", + "@img/sharp-libvips-linux-x64": "1.0.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.0.4", + "@img/sharp-libvips-linuxmusl-x64": "1.0.4", + "@img/sharp-linux-arm": "0.33.5", + "@img/sharp-linux-arm64": "0.33.5", + "@img/sharp-linux-s390x": "0.33.5", + "@img/sharp-linux-x64": "0.33.5", + "@img/sharp-linuxmusl-arm64": "0.33.5", + "@img/sharp-linuxmusl-x64": "0.33.5", + "@img/sharp-wasm32": "0.33.5", + "@img/sharp-win32-ia32": "0.33.5", + "@img/sharp-win32-x64": "0.33.5" + }, + "devDependencies": { + "@emnapi/runtime": "^1.2.0", + "@img/sharp-libvips-dev": "1.0.4", + "@img/sharp-libvips-dev-wasm32": "1.0.5", + "@img/sharp-libvips-win32-ia32": "1.0.4", + "@img/sharp-libvips-win32-x64": "1.0.4", + "@types/node": "*", + "async": "^3.2.5", + "cc": "^3.0.1", + "emnapi": "^1.2.0", + "exif-reader": "^2.0.1", + "extract-zip": "^2.0.1", + "icc": "^3.0.0", + "jsdoc-to-markdown": "^8.0.3", + "license-checker": "^25.0.1", + "mocha": "^10.7.3", + "node-addon-api": "^8.1.0", + "nyc": "^17.0.0", + "prebuild": "^13.0.1", + "semistandard": "^17.0.0", + "tar-fs": "^3.0.6", + "tsd": "^0.31.1" + }, + "license": "Apache-2.0", + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "config": { + "libvips": ">=8.15.3" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "binary": { + "napi_versions": [ + 9 + ] + }, + "semistandard": { + "env": [ + "mocha" + ] + }, + "cc": { + "linelength": "120", + "filter": [ + "build/include" + ] + }, + "nyc": { + "include": [ + "lib" + ] + }, + "tsd": { + "directory": "test/types/" + } +} diff --git a/node_modules/sharp/src/binding.gyp b/node_modules/sharp/src/binding.gyp new file mode 100644 index 0000000000000000000000000000000000000000..33607f9aaf8230af07d486480c9db75df99f4317 --- /dev/null +++ b/node_modules/sharp/src/binding.gyp @@ -0,0 +1,280 @@ +# Copyright 2013 Lovell Fuller and others. +# SPDX-License-Identifier: Apache-2.0 + +{ + 'variables': { + 'vips_version': ' +#include +#include +#include +#include +#include +#include // NOLINT(build/c++11) + +#include +#include + +#include "common.h" + +using vips::VImage; + +namespace sharp { + + // Convenience methods to access the attributes of a Napi::Object + bool HasAttr(Napi::Object obj, std::string attr) { + return obj.Has(attr); + } + std::string AttrAsStr(Napi::Object obj, std::string attr) { + return obj.Get(attr).As(); + } + std::string AttrAsStr(Napi::Object obj, unsigned int const attr) { + return obj.Get(attr).As(); + } + uint32_t AttrAsUint32(Napi::Object obj, std::string attr) { + return obj.Get(attr).As().Uint32Value(); + } + int32_t AttrAsInt32(Napi::Object obj, std::string attr) { + return obj.Get(attr).As().Int32Value(); + } + int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr) { + return obj.Get(attr).As().Int32Value(); + } + int64_t AttrAsInt64(Napi::Object obj, std::string attr) { + return obj.Get(attr).As().Int64Value(); + } + double AttrAsDouble(Napi::Object obj, std::string attr) { + return obj.Get(attr).As().DoubleValue(); + } + double AttrAsDouble(Napi::Object obj, unsigned int const attr) { + return obj.Get(attr).As().DoubleValue(); + } + bool AttrAsBool(Napi::Object obj, std::string attr) { + return obj.Get(attr).As().Value(); + } + std::vector AttrAsVectorOfDouble(Napi::Object obj, std::string attr) { + Napi::Array napiArray = obj.Get(attr).As(); + std::vector vectorOfDouble(napiArray.Length()); + for (unsigned int i = 0; i < napiArray.Length(); i++) { + vectorOfDouble[i] = AttrAsDouble(napiArray, i); + } + return vectorOfDouble; + } + std::vector AttrAsInt32Vector(Napi::Object obj, std::string attr) { + Napi::Array array = obj.Get(attr).As(); + std::vector vector(array.Length()); + for (unsigned int i = 0; i < array.Length(); i++) { + vector[i] = AttrAsInt32(array, i); + } + return vector; + } + + // Create an InputDescriptor instance from a Napi::Object describing an input image + InputDescriptor* CreateInputDescriptor(Napi::Object input) { + InputDescriptor *descriptor = new InputDescriptor; + if (HasAttr(input, "file")) { + descriptor->file = AttrAsStr(input, "file"); + } else if (HasAttr(input, "buffer")) { + Napi::Buffer buffer = input.Get("buffer").As>(); + descriptor->bufferLength = buffer.Length(); + descriptor->buffer = buffer.Data(); + descriptor->isBuffer = true; + } + descriptor->failOn = AttrAsEnum(input, "failOn", VIPS_TYPE_FAIL_ON); + // Density for vector-based input + if (HasAttr(input, "density")) { + descriptor->density = AttrAsDouble(input, "density"); + } + // Should we ignore any embedded ICC profile + if (HasAttr(input, "ignoreIcc")) { + descriptor->ignoreIcc = AttrAsBool(input, "ignoreIcc"); + } + // Raw pixel input + if (HasAttr(input, "rawChannels")) { + descriptor->rawDepth = AttrAsEnum(input, "rawDepth", VIPS_TYPE_BAND_FORMAT); + descriptor->rawChannels = AttrAsUint32(input, "rawChannels"); + descriptor->rawWidth = AttrAsUint32(input, "rawWidth"); + descriptor->rawHeight = AttrAsUint32(input, "rawHeight"); + descriptor->rawPremultiplied = AttrAsBool(input, "rawPremultiplied"); + } + // Multi-page input (GIF, TIFF, PDF) + if (HasAttr(input, "pages")) { + descriptor->pages = AttrAsInt32(input, "pages"); + } + if (HasAttr(input, "page")) { + descriptor->page = AttrAsUint32(input, "page"); + } + // Multi-level input (OpenSlide) + if (HasAttr(input, "level")) { + descriptor->level = AttrAsUint32(input, "level"); + } + // subIFD (OME-TIFF) + if (HasAttr(input, "subifd")) { + descriptor->subifd = AttrAsInt32(input, "subifd"); + } + // Create new image + if (HasAttr(input, "createChannels")) { + descriptor->createChannels = AttrAsUint32(input, "createChannels"); + descriptor->createWidth = AttrAsUint32(input, "createWidth"); + descriptor->createHeight = AttrAsUint32(input, "createHeight"); + if (HasAttr(input, "createNoiseType")) { + descriptor->createNoiseType = AttrAsStr(input, "createNoiseType"); + descriptor->createNoiseMean = AttrAsDouble(input, "createNoiseMean"); + descriptor->createNoiseSigma = AttrAsDouble(input, "createNoiseSigma"); + } else { + descriptor->createBackground = AttrAsVectorOfDouble(input, "createBackground"); + } + } + // Create new image with text + if (HasAttr(input, "textValue")) { + descriptor->textValue = AttrAsStr(input, "textValue"); + if (HasAttr(input, "textFont")) { + descriptor->textFont = AttrAsStr(input, "textFont"); + } + if (HasAttr(input, "textFontfile")) { + descriptor->textFontfile = AttrAsStr(input, "textFontfile"); + } + if (HasAttr(input, "textWidth")) { + descriptor->textWidth = AttrAsUint32(input, "textWidth"); + } + if (HasAttr(input, "textHeight")) { + descriptor->textHeight = AttrAsUint32(input, "textHeight"); + } + if (HasAttr(input, "textAlign")) { + descriptor->textAlign = AttrAsEnum(input, "textAlign", VIPS_TYPE_ALIGN); + } + if (HasAttr(input, "textJustify")) { + descriptor->textJustify = AttrAsBool(input, "textJustify"); + } + if (HasAttr(input, "textDpi")) { + descriptor->textDpi = AttrAsUint32(input, "textDpi"); + } + if (HasAttr(input, "textRgba")) { + descriptor->textRgba = AttrAsBool(input, "textRgba"); + } + if (HasAttr(input, "textSpacing")) { + descriptor->textSpacing = AttrAsUint32(input, "textSpacing"); + } + if (HasAttr(input, "textWrap")) { + descriptor->textWrap = AttrAsEnum(input, "textWrap", VIPS_TYPE_TEXT_WRAP); + } + } + // Limit input images to a given number of pixels, where pixels = width * height + descriptor->limitInputPixels = static_cast(AttrAsInt64(input, "limitInputPixels")); + // Allow switch from random to sequential access + descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM; + // Remove safety features and allow unlimited input + descriptor->unlimited = AttrAsBool(input, "unlimited"); + return descriptor; + } + + // How many tasks are in the queue? + std::atomic counterQueue{0}; + + // How many tasks are being processed? + std::atomic counterProcess{0}; + + // Filename extension checkers + static bool EndsWith(std::string const &str, std::string const &end) { + return str.length() >= end.length() && 0 == str.compare(str.length() - end.length(), end.length(), end); + } + bool IsJpeg(std::string const &str) { + return EndsWith(str, ".jpg") || EndsWith(str, ".jpeg") || EndsWith(str, ".JPG") || EndsWith(str, ".JPEG"); + } + bool IsPng(std::string const &str) { + return EndsWith(str, ".png") || EndsWith(str, ".PNG"); + } + bool IsWebp(std::string const &str) { + return EndsWith(str, ".webp") || EndsWith(str, ".WEBP"); + } + bool IsGif(std::string const &str) { + return EndsWith(str, ".gif") || EndsWith(str, ".GIF"); + } + bool IsJp2(std::string const &str) { + return EndsWith(str, ".jp2") || EndsWith(str, ".jpx") || EndsWith(str, ".j2k") || EndsWith(str, ".j2c") + || EndsWith(str, ".JP2") || EndsWith(str, ".JPX") || EndsWith(str, ".J2K") || EndsWith(str, ".J2C"); + } + bool IsTiff(std::string const &str) { + return EndsWith(str, ".tif") || EndsWith(str, ".tiff") || EndsWith(str, ".TIF") || EndsWith(str, ".TIFF"); + } + bool IsHeic(std::string const &str) { + return EndsWith(str, ".heic") || EndsWith(str, ".HEIC"); + } + bool IsHeif(std::string const &str) { + return EndsWith(str, ".heif") || EndsWith(str, ".HEIF") || IsHeic(str) || IsAvif(str); + } + bool IsAvif(std::string const &str) { + return EndsWith(str, ".avif") || EndsWith(str, ".AVIF"); + } + bool IsJxl(std::string const &str) { + return EndsWith(str, ".jxl") || EndsWith(str, ".JXL"); + } + bool IsDz(std::string const &str) { + return EndsWith(str, ".dzi") || EndsWith(str, ".DZI"); + } + bool IsDzZip(std::string const &str) { + return EndsWith(str, ".zip") || EndsWith(str, ".ZIP") || EndsWith(str, ".szi") || EndsWith(str, ".SZI"); + } + bool IsV(std::string const &str) { + return EndsWith(str, ".v") || EndsWith(str, ".V") || EndsWith(str, ".vips") || EndsWith(str, ".VIPS"); + } + + /* + Trim space from end of string. + */ + std::string TrimEnd(std::string const &str) { + return str.substr(0, str.find_last_not_of(" \n\r\f") + 1); + } + + /* + Provide a string identifier for the given image type. + */ + std::string ImageTypeId(ImageType const imageType) { + std::string id; + switch (imageType) { + case ImageType::JPEG: id = "jpeg"; break; + case ImageType::PNG: id = "png"; break; + case ImageType::WEBP: id = "webp"; break; + case ImageType::TIFF: id = "tiff"; break; + case ImageType::GIF: id = "gif"; break; + case ImageType::JP2: id = "jp2"; break; + case ImageType::SVG: id = "svg"; break; + case ImageType::HEIF: id = "heif"; break; + case ImageType::PDF: id = "pdf"; break; + case ImageType::MAGICK: id = "magick"; break; + case ImageType::OPENSLIDE: id = "openslide"; break; + case ImageType::PPM: id = "ppm"; break; + case ImageType::FITS: id = "fits"; break; + case ImageType::EXR: id = "exr"; break; + case ImageType::JXL: id = "jxl"; break; + case ImageType::VIPS: id = "vips"; break; + case ImageType::RAW: id = "raw"; break; + case ImageType::UNKNOWN: id = "unknown"; break; + case ImageType::MISSING: id = "missing"; break; + } + return id; + } + + /** + * Regenerate this table with something like: + * + * $ vips -l foreign | grep -i load | awk '{ print $2, $1; }' + * + * Plus a bit of editing. + */ + std::map loaderToType = { + { "VipsForeignLoadJpegFile", ImageType::JPEG }, + { "VipsForeignLoadJpegBuffer", ImageType::JPEG }, + { "VipsForeignLoadPngFile", ImageType::PNG }, + { "VipsForeignLoadPngBuffer", ImageType::PNG }, + { "VipsForeignLoadWebpFile", ImageType::WEBP }, + { "VipsForeignLoadWebpBuffer", ImageType::WEBP }, + { "VipsForeignLoadTiffFile", ImageType::TIFF }, + { "VipsForeignLoadTiffBuffer", ImageType::TIFF }, + { "VipsForeignLoadGifFile", ImageType::GIF }, + { "VipsForeignLoadGifBuffer", ImageType::GIF }, + { "VipsForeignLoadNsgifFile", ImageType::GIF }, + { "VipsForeignLoadNsgifBuffer", ImageType::GIF }, + { "VipsForeignLoadJp2kBuffer", ImageType::JP2 }, + { "VipsForeignLoadJp2kFile", ImageType::JP2 }, + { "VipsForeignLoadSvgFile", ImageType::SVG }, + { "VipsForeignLoadSvgBuffer", ImageType::SVG }, + { "VipsForeignLoadHeifFile", ImageType::HEIF }, + { "VipsForeignLoadHeifBuffer", ImageType::HEIF }, + { "VipsForeignLoadPdfFile", ImageType::PDF }, + { "VipsForeignLoadPdfBuffer", ImageType::PDF }, + { "VipsForeignLoadMagickFile", ImageType::MAGICK }, + { "VipsForeignLoadMagickBuffer", ImageType::MAGICK }, + { "VipsForeignLoadMagick7File", ImageType::MAGICK }, + { "VipsForeignLoadMagick7Buffer", ImageType::MAGICK }, + { "VipsForeignLoadOpenslideFile", ImageType::OPENSLIDE }, + { "VipsForeignLoadPpmFile", ImageType::PPM }, + { "VipsForeignLoadFitsFile", ImageType::FITS }, + { "VipsForeignLoadOpenexr", ImageType::EXR }, + { "VipsForeignLoadJxlFile", ImageType::JXL }, + { "VipsForeignLoadJxlBuffer", ImageType::JXL }, + { "VipsForeignLoadVips", ImageType::VIPS }, + { "VipsForeignLoadVipsFile", ImageType::VIPS }, + { "VipsForeignLoadRaw", ImageType::RAW } + }; + + /* + Determine image format of a buffer. + */ + ImageType DetermineImageType(void *buffer, size_t const length) { + ImageType imageType = ImageType::UNKNOWN; + char const *load = vips_foreign_find_load_buffer(buffer, length); + if (load != nullptr) { + auto it = loaderToType.find(load); + if (it != loaderToType.end()) { + imageType = it->second; + } + } + return imageType; + } + + /* + Determine image format, reads the first few bytes of the file + */ + ImageType DetermineImageType(char const *file) { + ImageType imageType = ImageType::UNKNOWN; + char const *load = vips_foreign_find_load(file); + if (load != nullptr) { + auto it = loaderToType.find(load); + if (it != loaderToType.end()) { + imageType = it->second; + } + } else { + if (EndsWith(vips::VError().what(), " does not exist\n")) { + imageType = ImageType::MISSING; + } + } + return imageType; + } + + /* + Does this image type support multiple pages? + */ + bool ImageTypeSupportsPage(ImageType imageType) { + return + imageType == ImageType::WEBP || + imageType == ImageType::MAGICK || + imageType == ImageType::GIF || + imageType == ImageType::JP2 || + imageType == ImageType::TIFF || + imageType == ImageType::HEIF || + imageType == ImageType::PDF; + } + + /* + Does this image type support removal of safety limits? + */ + bool ImageTypeSupportsUnlimited(ImageType imageType) { + return + imageType == ImageType::JPEG || + imageType == ImageType::PNG || + imageType == ImageType::SVG || + imageType == ImageType::HEIF; + } + + /* + Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data) + */ + std::tuple OpenInput(InputDescriptor *descriptor) { + VImage image; + ImageType imageType; + if (descriptor->isBuffer) { + if (descriptor->rawChannels > 0) { + // Raw, uncompressed pixel data + bool const is8bit = vips_band_format_is8bit(descriptor->rawDepth); + image = VImage::new_from_memory(descriptor->buffer, descriptor->bufferLength, + descriptor->rawWidth, descriptor->rawHeight, descriptor->rawChannels, descriptor->rawDepth); + if (descriptor->rawChannels < 3) { + image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_GREY16; + } else { + image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_sRGB : VIPS_INTERPRETATION_RGB16; + } + if (descriptor->rawPremultiplied) { + image = image.unpremultiply(); + } + imageType = ImageType::RAW; + } else { + // Compressed data + imageType = DetermineImageType(descriptor->buffer, descriptor->bufferLength); + if (imageType != ImageType::UNKNOWN) { + try { + vips::VOption *option = VImage::option() + ->set("access", descriptor->access) + ->set("fail_on", descriptor->failOn); + if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) { + option->set("unlimited", true); + } + if (imageType == ImageType::SVG || imageType == ImageType::PDF) { + option->set("dpi", descriptor->density); + } + if (imageType == ImageType::MAGICK) { + option->set("density", std::to_string(descriptor->density).data()); + } + if (ImageTypeSupportsPage(imageType)) { + option->set("n", descriptor->pages); + option->set("page", descriptor->page); + } + if (imageType == ImageType::OPENSLIDE) { + option->set("level", descriptor->level); + } + if (imageType == ImageType::TIFF) { + option->set("subifd", descriptor->subifd); + } + image = VImage::new_from_buffer(descriptor->buffer, descriptor->bufferLength, nullptr, option); + if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) { + image = SetDensity(image, descriptor->density); + } + } catch (vips::VError const &err) { + throw vips::VError(std::string("Input buffer has corrupt header: ") + err.what()); + } + } else { + throw vips::VError("Input buffer contains unsupported image format"); + } + } + } else { + int const channels = descriptor->createChannels; + if (channels > 0) { + // Create new image + if (descriptor->createNoiseType == "gaussian") { + std::vector bands = {}; + bands.reserve(channels); + for (int _band = 0; _band < channels; _band++) { + bands.push_back(VImage::gaussnoise(descriptor->createWidth, descriptor->createHeight, VImage::option() + ->set("mean", descriptor->createNoiseMean) + ->set("sigma", descriptor->createNoiseSigma))); + } + image = VImage::bandjoin(bands).copy(VImage::option()->set("interpretation", + channels < 3 ? VIPS_INTERPRETATION_B_W: VIPS_INTERPRETATION_sRGB)); + } else { + std::vector background = { + descriptor->createBackground[0], + descriptor->createBackground[1], + descriptor->createBackground[2] + }; + if (channels == 4) { + background.push_back(descriptor->createBackground[3]); + } + image = VImage::new_matrix(descriptor->createWidth, descriptor->createHeight) + .copy(VImage::option()->set("interpretation", + channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB)) + .new_from_image(background); + } + image = image.cast(VIPS_FORMAT_UCHAR); + imageType = ImageType::RAW; + } else if (descriptor->textValue.length() > 0) { + // Create a new image with text + vips::VOption *textOptions = VImage::option() + ->set("align", descriptor->textAlign) + ->set("justify", descriptor->textJustify) + ->set("rgba", descriptor->textRgba) + ->set("spacing", descriptor->textSpacing) + ->set("wrap", descriptor->textWrap) + ->set("autofit_dpi", &descriptor->textAutofitDpi); + if (descriptor->textWidth > 0) { + textOptions->set("width", descriptor->textWidth); + } + // Ignore dpi if height is set + if (descriptor->textWidth > 0 && descriptor->textHeight > 0) { + textOptions->set("height", descriptor->textHeight); + } else if (descriptor->textDpi > 0) { + textOptions->set("dpi", descriptor->textDpi); + } + if (descriptor->textFont.length() > 0) { + textOptions->set("font", const_cast(descriptor->textFont.data())); + } + if (descriptor->textFontfile.length() > 0) { + textOptions->set("fontfile", const_cast(descriptor->textFontfile.data())); + } + image = VImage::text(const_cast(descriptor->textValue.data()), textOptions); + if (!descriptor->textRgba) { + image = image.copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_B_W)); + } + imageType = ImageType::RAW; + } else { + // From filesystem + imageType = DetermineImageType(descriptor->file.data()); + if (imageType == ImageType::MISSING) { + if (descriptor->file.find("file.substr(0, 8) + "...')?"); + } + throw vips::VError("Input file is missing: " + descriptor->file); + } + if (imageType != ImageType::UNKNOWN) { + try { + vips::VOption *option = VImage::option() + ->set("access", descriptor->access) + ->set("fail_on", descriptor->failOn); + if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) { + option->set("unlimited", true); + } + if (imageType == ImageType::SVG || imageType == ImageType::PDF) { + option->set("dpi", descriptor->density); + } + if (imageType == ImageType::MAGICK) { + option->set("density", std::to_string(descriptor->density).data()); + } + if (ImageTypeSupportsPage(imageType)) { + option->set("n", descriptor->pages); + option->set("page", descriptor->page); + } + if (imageType == ImageType::OPENSLIDE) { + option->set("level", descriptor->level); + } + if (imageType == ImageType::TIFF) { + option->set("subifd", descriptor->subifd); + } + image = VImage::new_from_file(descriptor->file.data(), option); + if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) { + image = SetDensity(image, descriptor->density); + } + } catch (vips::VError const &err) { + throw vips::VError(std::string("Input file has corrupt header: ") + err.what()); + } + } else { + throw vips::VError("Input file contains unsupported image format"); + } + } + } + + // Limit input images to a given number of pixels, where pixels = width * height + if (descriptor->limitInputPixels > 0 && + static_cast(image.width()) * image.height() > descriptor->limitInputPixels) { + throw vips::VError("Input image exceeds pixel limit"); + } + return std::make_tuple(image, imageType); + } + + /* + Does this image have an embedded profile? + */ + bool HasProfile(VImage image) { + return image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB; + } + + /* + Get copy of embedded profile. + */ + std::pair GetProfile(VImage image) { + std::pair icc(nullptr, 0); + if (HasProfile(image)) { + size_t length; + const void *data = image.get_blob(VIPS_META_ICC_NAME, &length); + icc.first = static_cast(g_malloc(length)); + icc.second = length; + memcpy(icc.first, data, length); + } + return icc; + } + + /* + Set embedded profile. + */ + VImage SetProfile(VImage image, std::pair icc) { + if (icc.first != nullptr) { + image = image.copy(); + image.set(VIPS_META_ICC_NAME, reinterpret_cast(vips_area_free_cb), icc.first, icc.second); + } + return image; + } + + /* + Does this image have an alpha channel? + Uses colour space interpretation with number of channels to guess this. + */ + bool HasAlpha(VImage image) { + return image.has_alpha(); + } + + static void* RemoveExifCallback(VipsImage *image, char const *field, GValue *value, void *data) { + std::vector *fieldNames = static_cast *>(data); + std::string fieldName(field); + if (fieldName.substr(0, 8) == ("exif-ifd")) { + fieldNames->push_back(fieldName); + } + return nullptr; + } + + /* + Remove all EXIF-related image fields. + */ + VImage RemoveExif(VImage image) { + std::vector fieldNames; + vips_image_map(image.get_image(), static_cast(RemoveExifCallback), &fieldNames); + for (const auto& f : fieldNames) { + image.remove(f.data()); + } + return image; + } + + /* + Get EXIF Orientation of image, if any. + */ + int ExifOrientation(VImage image) { + int orientation = 0; + if (image.get_typeof(VIPS_META_ORIENTATION) != 0) { + orientation = image.get_int(VIPS_META_ORIENTATION); + } + return orientation; + } + + /* + Set EXIF Orientation of image. + */ + VImage SetExifOrientation(VImage image, int const orientation) { + VImage copy = image.copy(); + copy.set(VIPS_META_ORIENTATION, orientation); + return copy; + } + + /* + Remove EXIF Orientation from image. + */ + VImage RemoveExifOrientation(VImage image) { + VImage copy = image.copy(); + copy.remove(VIPS_META_ORIENTATION); + copy.remove("exif-ifd0-Orientation"); + return copy; + } + + /* + Set animation properties if necessary. + */ + VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector delay, int loop) { + bool hasDelay = !delay.empty(); + + // Avoid a copy if none of the animation properties are needed. + if (nPages == 1 && !hasDelay && loop == -1) return image; + + if (delay.size() == 1) { + // We have just one delay, repeat that value for all frames. + delay.insert(delay.end(), nPages - 1, delay[0]); + } + + // Attaching metadata, need to copy the image. + VImage copy = image.copy(); + + // Only set page-height if we have more than one page, or this could + // accidentally turn into an animated image later. + if (nPages > 1) copy.set(VIPS_META_PAGE_HEIGHT, pageHeight); + if (hasDelay) copy.set("delay", delay); + if (loop != -1) copy.set("loop", loop); + + return copy; + } + + /* + Remove animation properties from image. + */ + VImage RemoveAnimationProperties(VImage image) { + VImage copy = image.copy(); + copy.remove(VIPS_META_PAGE_HEIGHT); + copy.remove("delay"); + copy.remove("loop"); + return copy; + } + + /* + Remove GIF palette from image. + */ + VImage RemoveGifPalette(VImage image) { + VImage copy = image.copy(); + copy.remove("gif-palette"); + return copy; + } + + /* + Does this image have a non-default density? + */ + bool HasDensity(VImage image) { + return image.xres() > 1.0; + } + + /* + Get pixels/mm resolution as pixels/inch density. + */ + int GetDensity(VImage image) { + return static_cast(round(image.xres() * 25.4)); + } + + /* + Set pixels/mm resolution based on a pixels/inch density. + */ + VImage SetDensity(VImage image, const double density) { + const double pixelsPerMm = density / 25.4; + VImage copy = image.copy(); + copy.get_image()->Xres = pixelsPerMm; + copy.get_image()->Yres = pixelsPerMm; + return copy; + } + + /* + Multi-page images can have a page height. Fetch it, and sanity check it. + If page-height is not set, it defaults to the image height + */ + int GetPageHeight(VImage image) { + return vips_image_get_page_height(image.get_image()); + } + + /* + Check the proposed format supports the current dimensions. + */ + void AssertImageTypeDimensions(VImage image, ImageType const imageType) { + const int height = image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT + ? image.get_int(VIPS_META_PAGE_HEIGHT) + : image.height(); + if (imageType == ImageType::JPEG) { + if (image.width() > 65535 || height > 65535) { + throw vips::VError("Processed image is too large for the JPEG format"); + } + } else if (imageType == ImageType::WEBP) { + if (image.width() > 16383 || height > 16383) { + throw vips::VError("Processed image is too large for the WebP format"); + } + } else if (imageType == ImageType::GIF) { + if (image.width() > 65535 || height > 65535) { + throw vips::VError("Processed image is too large for the GIF format"); + } + } else if (imageType == ImageType::HEIF) { + if (image.width() > 16384 || height > 16384) { + throw vips::VError("Processed image is too large for the HEIF format"); + } + } + } + + /* + Called when a Buffer undergoes GC, required to support mixed runtime libraries in Windows + */ + std::function FreeCallback = [](void*, char* data) { + g_free(data); + }; + + /* + Temporary buffer of warnings + */ + std::queue vipsWarnings; + std::mutex vipsWarningsMutex; + + /* + Called with warnings from the glib-registered "VIPS" domain + */ + void VipsWarningCallback(char const* log_domain, GLogLevelFlags log_level, char const* message, void* ignore) { + std::lock_guard lock(vipsWarningsMutex); + vipsWarnings.emplace(message); + } + + /* + Pop the oldest warning message from the queue + */ + std::string VipsWarningPop() { + std::string warning; + std::lock_guard lock(vipsWarningsMutex); + if (!vipsWarnings.empty()) { + warning = vipsWarnings.front(); + vipsWarnings.pop(); + } + return warning; + } + + /* + Attach an event listener for progress updates, used to detect timeout + */ + void SetTimeout(VImage image, int const seconds) { + if (seconds > 0) { + VipsImage *im = image.get_image(); + if (im->progress_signal == NULL) { + int *timeout = VIPS_NEW(im, int); + *timeout = seconds; + g_signal_connect(im, "eval", G_CALLBACK(VipsProgressCallBack), timeout); + vips_image_set_progress(im, true); + } + } + } + + /* + Event listener for progress updates, used to detect timeout + */ + void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) { + if (*timeout > 0 && progress->run >= *timeout) { + vips_image_set_kill(im, true); + vips_error("timeout", "%d%% complete", progress->percent); + *timeout = 0; + } + } + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given gravity during an embed. + + @Azurebyte: We are basically swapping the inWidth and outWidth, inHeight and outHeight from the CalculateCrop function. + */ + std::tuple CalculateEmbedPosition(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const gravity) { + + int left = 0; + int top = 0; + switch (gravity) { + case 1: + // North + left = (outWidth - inWidth) / 2; + break; + case 2: + // East + left = outWidth - inWidth; + top = (outHeight - inHeight) / 2; + break; + case 3: + // South + left = (outWidth - inWidth) / 2; + top = outHeight - inHeight; + break; + case 4: + // West + top = (outHeight - inHeight) / 2; + break; + case 5: + // Northeast + left = outWidth - inWidth; + break; + case 6: + // Southeast + left = outWidth - inWidth; + top = outHeight - inHeight; + break; + case 7: + // Southwest + top = outHeight - inHeight; + break; + case 8: + // Northwest + // Which is the default is 0,0 so we do not assign anything here. + break; + default: + // Centre + left = (outWidth - inWidth) / 2; + top = (outHeight - inHeight) / 2; + } + return std::make_tuple(left, top); + } + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given gravity during a crop. + */ + std::tuple CalculateCrop(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const gravity) { + + int left = 0; + int top = 0; + switch (gravity) { + case 1: + // North + left = (inWidth - outWidth + 1) / 2; + break; + case 2: + // East + left = inWidth - outWidth; + top = (inHeight - outHeight + 1) / 2; + break; + case 3: + // South + left = (inWidth - outWidth + 1) / 2; + top = inHeight - outHeight; + break; + case 4: + // West + top = (inHeight - outHeight + 1) / 2; + break; + case 5: + // Northeast + left = inWidth - outWidth; + break; + case 6: + // Southeast + left = inWidth - outWidth; + top = inHeight - outHeight; + break; + case 7: + // Southwest + top = inHeight - outHeight; + break; + case 8: + // Northwest + break; + default: + // Centre + left = (inWidth - outWidth + 1) / 2; + top = (inHeight - outHeight + 1) / 2; + } + return std::make_tuple(left, top); + } + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given x and y offsets. + */ + std::tuple CalculateCrop(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const x, int const y) { + + // default values + int left = 0; + int top = 0; + + // assign only if valid + if (x < (inWidth - outWidth)) { + left = x; + } else if (x >= (inWidth - outWidth)) { + left = inWidth - outWidth; + } + + if (y < (inHeight - outHeight)) { + top = y; + } else if (y >= (inHeight - outHeight)) { + top = inHeight - outHeight; + } + + return std::make_tuple(left, top); + } + + /* + Are pixel values in this image 16-bit integer? + */ + bool Is16Bit(VipsInterpretation const interpretation) { + return interpretation == VIPS_INTERPRETATION_RGB16 || interpretation == VIPS_INTERPRETATION_GREY16; + } + + /* + Return the image alpha maximum. Useful for combining alpha bands. scRGB + images are 0 - 1 for image data, but the alpha is 0 - 255. + */ + double MaximumImageAlpha(VipsInterpretation const interpretation) { + return Is16Bit(interpretation) ? 65535.0 : 255.0; + } + + /* + Convert RGBA value to another colourspace + */ + std::vector GetRgbaAsColourspace(std::vector const rgba, + VipsInterpretation const interpretation, bool premultiply) { + int const bands = static_cast(rgba.size()); + if (bands < 3) { + return rgba; + } + VImage pixel = VImage::new_matrix(1, 1); + pixel.set("bands", bands); + pixel = pixel + .new_from_image(rgba) + .colourspace(interpretation, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)); + if (premultiply) { + pixel = pixel.premultiply(); + } + return pixel(0, 0); + } + + /* + Apply the alpha channel to a given colour + */ + std::tuple> ApplyAlpha(VImage image, std::vector colour, bool premultiply) { + // Scale up 8-bit values to match 16-bit input image + double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0; + // Create alphaColour colour + std::vector alphaColour; + if (image.bands() > 2) { + alphaColour = { + multiplier * colour[0], + multiplier * colour[1], + multiplier * colour[2] + }; + } else { + // Convert sRGB to greyscale + alphaColour = { multiplier * ( + 0.2126 * colour[0] + + 0.7152 * colour[1] + + 0.0722 * colour[2]) + }; + } + // Add alpha channel to alphaColour colour + if (colour[3] < 255.0 || HasAlpha(image)) { + alphaColour.push_back(colour[3] * multiplier); + } + // Ensure alphaColour colour uses correct colourspace + alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation(), premultiply); + // Add non-transparent alpha channel, if required + if (colour[3] < 255.0 && !HasAlpha(image)) { + image = image.bandjoin( + VImage::new_matrix(image.width(), image.height()).new_from_image(255 * multiplier).cast(image.format())); + } + return std::make_tuple(image, alphaColour); + } + + /* + Removes alpha channel, if any. + */ + VImage RemoveAlpha(VImage image) { + if (HasAlpha(image)) { + image = image.extract_band(0, VImage::option()->set("n", image.bands() - 1)); + } + return image; + } + + /* + Ensures alpha channel, if missing. + */ + VImage EnsureAlpha(VImage image, double const value) { + if (!HasAlpha(image)) { + std::vector alpha; + alpha.push_back(value * sharp::MaximumImageAlpha(image.interpretation())); + image = image.bandjoin_const(alpha); + } + return image; + } + + std::pair ResolveShrink(int width, int height, int targetWidth, int targetHeight, + Canvas canvas, bool withoutEnlargement, bool withoutReduction) { + double hshrink = 1.0; + double vshrink = 1.0; + + if (targetWidth > 0 && targetHeight > 0) { + // Fixed width and height + hshrink = static_cast(width) / targetWidth; + vshrink = static_cast(height) / targetHeight; + + switch (canvas) { + case Canvas::CROP: + case Canvas::MIN: + if (hshrink < vshrink) { + vshrink = hshrink; + } else { + hshrink = vshrink; + } + break; + case Canvas::EMBED: + case Canvas::MAX: + if (hshrink > vshrink) { + vshrink = hshrink; + } else { + hshrink = vshrink; + } + break; + case Canvas::IGNORE_ASPECT: + break; + } + } else if (targetWidth > 0) { + // Fixed width + hshrink = static_cast(width) / targetWidth; + + if (canvas != Canvas::IGNORE_ASPECT) { + // Auto height + vshrink = hshrink; + } + } else if (targetHeight > 0) { + // Fixed height + vshrink = static_cast(height) / targetHeight; + + if (canvas != Canvas::IGNORE_ASPECT) { + // Auto width + hshrink = vshrink; + } + } + + // We should not reduce or enlarge the output image, if + // withoutReduction or withoutEnlargement is specified. + if (withoutReduction) { + // Equivalent of VIPS_SIZE_UP + hshrink = std::min(1.0, hshrink); + vshrink = std::min(1.0, vshrink); + } else if (withoutEnlargement) { + // Equivalent of VIPS_SIZE_DOWN + hshrink = std::max(1.0, hshrink); + vshrink = std::max(1.0, vshrink); + } + + // We don't want to shrink so much that we send an axis to 0 + hshrink = std::min(hshrink, static_cast(width)); + vshrink = std::min(vshrink, static_cast(height)); + + return std::make_pair(hshrink, vshrink); + } + + /* + Ensure decoding remains sequential. + */ + VImage StaySequential(VImage image, bool condition) { + if (vips_image_is_sequential(image.get_image()) && condition) { + image = image.copy_memory().copy(); + image.remove(VIPS_META_SEQUENTIAL); + } + return image; + } +} // namespace sharp diff --git a/node_modules/sharp/src/common.h b/node_modules/sharp/src/common.h new file mode 100644 index 0000000000000000000000000000000000000000..225f6129ca73e16918082643724a6052ee355ccc --- /dev/null +++ b/node_modules/sharp/src/common.h @@ -0,0 +1,393 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_COMMON_H_ +#define SRC_COMMON_H_ + +#include +#include +#include +#include + +#include +#include + +// Verify platform and compiler compatibility + +#if (VIPS_MAJOR_VERSION < 8) || \ + (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 15) || \ + (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 15 && VIPS_MICRO_VERSION < 3) +#error "libvips version 8.15.3+ is required - please see https://sharp.pixelplumbing.com/install" +#endif + +#if ((!defined(__clang__)) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 6))) +#error "GCC version 4.6+ is required for C++11 features - please see https://sharp.pixelplumbing.com/install" +#endif + +#if (defined(__clang__) && defined(__has_feature)) +#if (!__has_feature(cxx_range_for)) +#error "clang version 3.0+ is required for C++11 features - please see https://sharp.pixelplumbing.com/install" +#endif +#endif + +using vips::VImage; + +namespace sharp { + + struct InputDescriptor { // NOLINT(runtime/indentation_namespace) + std::string name; + std::string file; + char *buffer; + VipsFailOn failOn; + uint64_t limitInputPixels; + bool unlimited; + VipsAccess access; + size_t bufferLength; + bool isBuffer; + double density; + bool ignoreIcc; + VipsBandFormat rawDepth; + int rawChannels; + int rawWidth; + int rawHeight; + bool rawPremultiplied; + int pages; + int page; + int level; + int subifd; + int createChannels; + int createWidth; + int createHeight; + std::vector createBackground; + std::string createNoiseType; + double createNoiseMean; + double createNoiseSigma; + std::string textValue; + std::string textFont; + std::string textFontfile; + int textWidth; + int textHeight; + VipsAlign textAlign; + bool textJustify; + int textDpi; + bool textRgba; + int textSpacing; + VipsTextWrap textWrap; + int textAutofitDpi; + + InputDescriptor(): + buffer(nullptr), + failOn(VIPS_FAIL_ON_WARNING), + limitInputPixels(0x3FFF * 0x3FFF), + unlimited(false), + access(VIPS_ACCESS_RANDOM), + bufferLength(0), + isBuffer(false), + density(72.0), + ignoreIcc(false), + rawDepth(VIPS_FORMAT_UCHAR), + rawChannels(0), + rawWidth(0), + rawHeight(0), + rawPremultiplied(false), + pages(1), + page(0), + level(0), + subifd(-1), + createChannels(0), + createWidth(0), + createHeight(0), + createBackground{ 0.0, 0.0, 0.0, 255.0 }, + createNoiseMean(0.0), + createNoiseSigma(0.0), + textWidth(0), + textHeight(0), + textAlign(VIPS_ALIGN_LOW), + textJustify(false), + textDpi(72), + textRgba(false), + textSpacing(0), + textWrap(VIPS_TEXT_WRAP_WORD), + textAutofitDpi(0) {} + }; + + // Convenience methods to access the attributes of a Napi::Object + bool HasAttr(Napi::Object obj, std::string attr); + std::string AttrAsStr(Napi::Object obj, std::string attr); + std::string AttrAsStr(Napi::Object obj, unsigned int const attr); + uint32_t AttrAsUint32(Napi::Object obj, std::string attr); + int32_t AttrAsInt32(Napi::Object obj, std::string attr); + int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr); + double AttrAsDouble(Napi::Object obj, std::string attr); + double AttrAsDouble(Napi::Object obj, unsigned int const attr); + bool AttrAsBool(Napi::Object obj, std::string attr); + std::vector AttrAsVectorOfDouble(Napi::Object obj, std::string attr); + std::vector AttrAsInt32Vector(Napi::Object obj, std::string attr); + template T AttrAsEnum(Napi::Object obj, std::string attr, GType type) { + return static_cast( + vips_enum_from_nick(nullptr, type, AttrAsStr(obj, attr).data())); + } + + // Create an InputDescriptor instance from a Napi::Object describing an input image + InputDescriptor* CreateInputDescriptor(Napi::Object input); + + enum class ImageType { + JPEG, + PNG, + WEBP, + JP2, + TIFF, + GIF, + SVG, + HEIF, + PDF, + MAGICK, + OPENSLIDE, + PPM, + FITS, + EXR, + JXL, + VIPS, + RAW, + UNKNOWN, + MISSING + }; + + enum class Canvas { + CROP, + EMBED, + MAX, + MIN, + IGNORE_ASPECT + }; + + // How many tasks are in the queue? + extern std::atomic counterQueue; + + // How many tasks are being processed? + extern std::atomic counterProcess; + + // Filename extension checkers + bool IsJpeg(std::string const &str); + bool IsPng(std::string const &str); + bool IsWebp(std::string const &str); + bool IsJp2(std::string const &str); + bool IsGif(std::string const &str); + bool IsTiff(std::string const &str); + bool IsHeic(std::string const &str); + bool IsHeif(std::string const &str); + bool IsAvif(std::string const &str); + bool IsJxl(std::string const &str); + bool IsDz(std::string const &str); + bool IsDzZip(std::string const &str); + bool IsV(std::string const &str); + + /* + Trim space from end of string. + */ + std::string TrimEnd(std::string const &str); + + /* + Provide a string identifier for the given image type. + */ + std::string ImageTypeId(ImageType const imageType); + + /* + Determine image format of a buffer. + */ + ImageType DetermineImageType(void *buffer, size_t const length); + + /* + Determine image format of a file. + */ + ImageType DetermineImageType(char const *file); + + /* + Does this image type support multiple pages? + */ + bool ImageTypeSupportsPage(ImageType imageType); + + /* + Does this image type support removal of safety limits? + */ + bool ImageTypeSupportsUnlimited(ImageType imageType); + + /* + Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data) + */ + std::tuple OpenInput(InputDescriptor *descriptor); + + /* + Does this image have an embedded profile? + */ + bool HasProfile(VImage image); + + /* + Get copy of embedded profile. + */ + std::pair GetProfile(VImage image); + + /* + Set embedded profile. + */ + VImage SetProfile(VImage image, std::pair icc); + + /* + Does this image have an alpha channel? + Uses colour space interpretation with number of channels to guess this. + */ + bool HasAlpha(VImage image); + + /* + Remove all EXIF-related image fields. + */ + VImage RemoveExif(VImage image); + + /* + Get EXIF Orientation of image, if any. + */ + int ExifOrientation(VImage image); + + /* + Set EXIF Orientation of image. + */ + VImage SetExifOrientation(VImage image, int const orientation); + + /* + Remove EXIF Orientation from image. + */ + VImage RemoveExifOrientation(VImage image); + + /* + Set animation properties if necessary. + */ + VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector delay, int loop); + + /* + Remove animation properties from image. + */ + VImage RemoveAnimationProperties(VImage image); + + /* + Remove GIF palette from image. + */ + VImage RemoveGifPalette(VImage image); + + /* + Does this image have a non-default density? + */ + bool HasDensity(VImage image); + + /* + Get pixels/mm resolution as pixels/inch density. + */ + int GetDensity(VImage image); + + /* + Set pixels/mm resolution based on a pixels/inch density. + */ + VImage SetDensity(VImage image, const double density); + + /* + Multi-page images can have a page height. Fetch it, and sanity check it. + If page-height is not set, it defaults to the image height + */ + int GetPageHeight(VImage image); + + /* + Check the proposed format supports the current dimensions. + */ + void AssertImageTypeDimensions(VImage image, ImageType const imageType); + + /* + Called when a Buffer undergoes GC, required to support mixed runtime libraries in Windows + */ + extern std::function FreeCallback; + + /* + Called with warnings from the glib-registered "VIPS" domain + */ + void VipsWarningCallback(char const* log_domain, GLogLevelFlags log_level, char const* message, void* ignore); + + /* + Pop the oldest warning message from the queue + */ + std::string VipsWarningPop(); + + /* + Attach an event listener for progress updates, used to detect timeout + */ + void SetTimeout(VImage image, int const timeoutSeconds); + + /* + Event listener for progress updates, used to detect timeout + */ + void VipsProgressCallBack(VipsImage *image, VipsProgress *progress, int *timeoutSeconds); + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given gravity during an embed. + */ + std::tuple CalculateEmbedPosition(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const gravity); + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given gravity. + */ + std::tuple CalculateCrop(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const gravity); + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given x and y offsets of the output image. + */ + std::tuple CalculateCrop(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const x, int const y); + + /* + Are pixel values in this image 16-bit integer? + */ + bool Is16Bit(VipsInterpretation const interpretation); + + /* + Return the image alpha maximum. Useful for combining alpha bands. scRGB + images are 0 - 1 for image data, but the alpha is 0 - 255. + */ + double MaximumImageAlpha(VipsInterpretation const interpretation); + + /* + Convert RGBA value to another colourspace + */ + std::vector GetRgbaAsColourspace(std::vector const rgba, + VipsInterpretation const interpretation, bool premultiply); + + /* + Apply the alpha channel to a given colour + */ + std::tuple> ApplyAlpha(VImage image, std::vector colour, bool premultiply); + + /* + Removes alpha channel, if any. + */ + VImage RemoveAlpha(VImage image); + + /* + Ensures alpha channel, if missing. + */ + VImage EnsureAlpha(VImage image, double const value); + + /* + Calculate the horizontal and vertical shrink factors, taking the canvas mode into account. + */ + std::pair ResolveShrink(int width, int height, int targetWidth, int targetHeight, + Canvas canvas, bool withoutEnlargement, bool withoutReduction); + + /* + Ensure decoding remains sequential. + */ + VImage StaySequential(VImage image, bool condition = true); + +} // namespace sharp + +#endif // SRC_COMMON_H_ diff --git a/node_modules/sharp/src/metadata.cc b/node_modules/sharp/src/metadata.cc new file mode 100644 index 0000000000000000000000000000000000000000..9d0ac6f38c0127b59523ffcb1a390343c6ef5439 --- /dev/null +++ b/node_modules/sharp/src/metadata.cc @@ -0,0 +1,320 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include + +#include +#include + +#include "common.h" +#include "metadata.h" + +static void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p); + +class MetadataWorker : public Napi::AsyncWorker { + public: + MetadataWorker(Napi::Function callback, MetadataBaton *baton, Napi::Function debuglog) : + Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {} + ~MetadataWorker() {} + + void Execute() { + // Decrement queued task counter + sharp::counterQueue--; + + vips::VImage image; + sharp::ImageType imageType = sharp::ImageType::UNKNOWN; + try { + std::tie(image, imageType) = OpenInput(baton->input); + } catch (vips::VError const &err) { + (baton->err).append(err.what()); + } + if (imageType != sharp::ImageType::UNKNOWN) { + // Image type + baton->format = sharp::ImageTypeId(imageType); + // VipsImage attributes + baton->width = image.width(); + baton->height = image.height(); + baton->space = vips_enum_nick(VIPS_TYPE_INTERPRETATION, image.interpretation()); + baton->channels = image.bands(); + baton->depth = vips_enum_nick(VIPS_TYPE_BAND_FORMAT, image.format()); + if (sharp::HasDensity(image)) { + baton->density = sharp::GetDensity(image); + } + if (image.get_typeof("jpeg-chroma-subsample") == VIPS_TYPE_REF_STRING) { + baton->chromaSubsampling = image.get_string("jpeg-chroma-subsample"); + } + if (image.get_typeof("interlaced") == G_TYPE_INT) { + baton->isProgressive = image.get_int("interlaced") == 1; + } + if (image.get_typeof("palette-bit-depth") == G_TYPE_INT) { + baton->paletteBitDepth = image.get_int("palette-bit-depth"); + } + if (image.get_typeof(VIPS_META_N_PAGES) == G_TYPE_INT) { + baton->pages = image.get_int(VIPS_META_N_PAGES); + } + if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) { + baton->pageHeight = image.get_int(VIPS_META_PAGE_HEIGHT); + } + if (image.get_typeof("loop") == G_TYPE_INT) { + baton->loop = image.get_int("loop"); + } + if (image.get_typeof("delay") == VIPS_TYPE_ARRAY_INT) { + baton->delay = image.get_array_int("delay"); + } + if (image.get_typeof("heif-primary") == G_TYPE_INT) { + baton->pagePrimary = image.get_int("heif-primary"); + } + if (image.get_typeof("heif-compression") == VIPS_TYPE_REF_STRING) { + baton->compression = image.get_string("heif-compression"); + } + if (image.get_typeof(VIPS_META_RESOLUTION_UNIT) == VIPS_TYPE_REF_STRING) { + baton->resolutionUnit = image.get_string(VIPS_META_RESOLUTION_UNIT); + } + if (image.get_typeof("magick-format") == VIPS_TYPE_REF_STRING) { + baton->formatMagick = image.get_string("magick-format"); + } + if (image.get_typeof("openslide.level-count") == VIPS_TYPE_REF_STRING) { + int const levels = std::stoi(image.get_string("openslide.level-count")); + for (int l = 0; l < levels; l++) { + std::string prefix = "openslide.level[" + std::to_string(l) + "]."; + int const width = std::stoi(image.get_string((prefix + "width").data())); + int const height = std::stoi(image.get_string((prefix + "height").data())); + baton->levels.push_back(std::pair(width, height)); + } + } + if (image.get_typeof(VIPS_META_N_SUBIFDS) == G_TYPE_INT) { + baton->subifds = image.get_int(VIPS_META_N_SUBIFDS); + } + baton->hasProfile = sharp::HasProfile(image); + if (image.get_typeof("background") == VIPS_TYPE_ARRAY_DOUBLE) { + baton->background = image.get_array_double("background"); + } + // Derived attributes + baton->hasAlpha = sharp::HasAlpha(image); + baton->orientation = sharp::ExifOrientation(image); + // EXIF + if (image.get_typeof(VIPS_META_EXIF_NAME) == VIPS_TYPE_BLOB) { + size_t exifLength; + void const *exif = image.get_blob(VIPS_META_EXIF_NAME, &exifLength); + baton->exif = static_cast(g_malloc(exifLength)); + memcpy(baton->exif, exif, exifLength); + baton->exifLength = exifLength; + } + // ICC profile + if (image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB) { + size_t iccLength; + void const *icc = image.get_blob(VIPS_META_ICC_NAME, &iccLength); + baton->icc = static_cast(g_malloc(iccLength)); + memcpy(baton->icc, icc, iccLength); + baton->iccLength = iccLength; + } + // IPTC + if (image.get_typeof(VIPS_META_IPTC_NAME) == VIPS_TYPE_BLOB) { + size_t iptcLength; + void const *iptc = image.get_blob(VIPS_META_IPTC_NAME, &iptcLength); + baton->iptc = static_cast(g_malloc(iptcLength)); + memcpy(baton->iptc, iptc, iptcLength); + baton->iptcLength = iptcLength; + } + // XMP + if (image.get_typeof(VIPS_META_XMP_NAME) == VIPS_TYPE_BLOB) { + size_t xmpLength; + void const *xmp = image.get_blob(VIPS_META_XMP_NAME, &xmpLength); + baton->xmp = static_cast(g_malloc(xmpLength)); + memcpy(baton->xmp, xmp, xmpLength); + baton->xmpLength = xmpLength; + } + // TIFFTAG_PHOTOSHOP + if (image.get_typeof(VIPS_META_PHOTOSHOP_NAME) == VIPS_TYPE_BLOB) { + size_t tifftagPhotoshopLength; + void const *tifftagPhotoshop = image.get_blob(VIPS_META_PHOTOSHOP_NAME, &tifftagPhotoshopLength); + baton->tifftagPhotoshop = static_cast(g_malloc(tifftagPhotoshopLength)); + memcpy(baton->tifftagPhotoshop, tifftagPhotoshop, tifftagPhotoshopLength); + baton->tifftagPhotoshopLength = tifftagPhotoshopLength; + } + // PNG comments + vips_image_map(image.get_image(), readPNGComment, &baton->comments); + } + + // Clean up + vips_error_clear(); + vips_thread_shutdown(); + } + + void OnOK() { + Napi::Env env = Env(); + Napi::HandleScope scope(env); + + // Handle warnings + std::string warning = sharp::VipsWarningPop(); + while (!warning.empty()) { + debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) }); + warning = sharp::VipsWarningPop(); + } + + if (baton->err.empty()) { + Napi::Object info = Napi::Object::New(env); + info.Set("format", baton->format); + if (baton->input->bufferLength > 0) { + info.Set("size", baton->input->bufferLength); + } + info.Set("width", baton->width); + info.Set("height", baton->height); + info.Set("space", baton->space); + info.Set("channels", baton->channels); + info.Set("depth", baton->depth); + if (baton->density > 0) { + info.Set("density", baton->density); + } + if (!baton->chromaSubsampling.empty()) { + info.Set("chromaSubsampling", baton->chromaSubsampling); + } + info.Set("isProgressive", baton->isProgressive); + if (baton->paletteBitDepth > 0) { + info.Set("paletteBitDepth", baton->paletteBitDepth); + } + if (baton->pages > 0) { + info.Set("pages", baton->pages); + } + if (baton->pageHeight > 0) { + info.Set("pageHeight", baton->pageHeight); + } + if (baton->loop >= 0) { + info.Set("loop", baton->loop); + } + if (!baton->delay.empty()) { + int i = 0; + Napi::Array delay = Napi::Array::New(env, static_cast(baton->delay.size())); + for (int const d : baton->delay) { + delay.Set(i++, d); + } + info.Set("delay", delay); + } + if (baton->pagePrimary > -1) { + info.Set("pagePrimary", baton->pagePrimary); + } + if (!baton->compression.empty()) { + info.Set("compression", baton->compression); + } + if (!baton->resolutionUnit.empty()) { + info.Set("resolutionUnit", baton->resolutionUnit == "in" ? "inch" : baton->resolutionUnit); + } + if (!baton->formatMagick.empty()) { + info.Set("formatMagick", baton->formatMagick); + } + if (!baton->levels.empty()) { + int i = 0; + Napi::Array levels = Napi::Array::New(env, static_cast(baton->levels.size())); + for (std::pair const &l : baton->levels) { + Napi::Object level = Napi::Object::New(env); + level.Set("width", l.first); + level.Set("height", l.second); + levels.Set(i++, level); + } + info.Set("levels", levels); + } + if (baton->subifds > 0) { + info.Set("subifds", baton->subifds); + } + if (!baton->background.empty()) { + if (baton->background.size() == 3) { + Napi::Object background = Napi::Object::New(env); + background.Set("r", baton->background[0]); + background.Set("g", baton->background[1]); + background.Set("b", baton->background[2]); + info.Set("background", background); + } else { + info.Set("background", baton->background[0]); + } + } + info.Set("hasProfile", baton->hasProfile); + info.Set("hasAlpha", baton->hasAlpha); + if (baton->orientation > 0) { + info.Set("orientation", baton->orientation); + } + if (baton->exifLength > 0) { + info.Set("exif", Napi::Buffer::NewOrCopy(env, baton->exif, baton->exifLength, sharp::FreeCallback)); + } + if (baton->iccLength > 0) { + info.Set("icc", Napi::Buffer::NewOrCopy(env, baton->icc, baton->iccLength, sharp::FreeCallback)); + } + if (baton->iptcLength > 0) { + info.Set("iptc", Napi::Buffer::NewOrCopy(env, baton->iptc, baton->iptcLength, sharp::FreeCallback)); + } + if (baton->xmpLength > 0) { + info.Set("xmp", Napi::Buffer::NewOrCopy(env, baton->xmp, baton->xmpLength, sharp::FreeCallback)); + } + if (baton->tifftagPhotoshopLength > 0) { + info.Set("tifftagPhotoshop", + Napi::Buffer::NewOrCopy(env, baton->tifftagPhotoshop, + baton->tifftagPhotoshopLength, sharp::FreeCallback)); + } + if (baton->comments.size() > 0) { + int i = 0; + Napi::Array comments = Napi::Array::New(env, baton->comments.size()); + for (auto &c : baton->comments) { + Napi::Object comment = Napi::Object::New(env); + comment.Set("keyword", c.first); + comment.Set("text", c.second); + comments.Set(i++, comment); + } + info.Set("comments", comments); + } + Callback().Call(Receiver().Value(), { env.Null(), info }); + } else { + Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() }); + } + + delete baton->input; + delete baton; + } + + private: + MetadataBaton* baton; + Napi::FunctionReference debuglog; +}; + +/* + metadata(options, callback) +*/ +Napi::Value metadata(const Napi::CallbackInfo& info) { + // V8 objects are converted to non-V8 types held in the baton struct + MetadataBaton *baton = new MetadataBaton; + Napi::Object options = info[size_t(0)].As(); + + // Input + baton->input = sharp::CreateInputDescriptor(options.Get("input").As()); + + // Function to notify of libvips warnings + Napi::Function debuglog = options.Get("debuglog").As(); + + // Join queue for worker thread + Napi::Function callback = info[size_t(1)].As(); + MetadataWorker *worker = new MetadataWorker(callback, baton, debuglog); + worker->Receiver().Set("options", options); + worker->Queue(); + + // Increment queued task counter + sharp::counterQueue++; + + return info.Env().Undefined(); +} + +const char *PNG_COMMENT_START = "png-comment-"; +const int PNG_COMMENT_START_LEN = strlen(PNG_COMMENT_START); + +static void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p) { + MetadataComments *comments = static_cast(p); + + if (vips_isprefix(PNG_COMMENT_START, field)) { + const char *keyword = strchr(field + PNG_COMMENT_START_LEN, '-'); + const char *str; + if (keyword != NULL && !vips_image_get_string(image, field, &str)) { + keyword++; // Skip the hyphen + comments->push_back(std::make_pair(keyword, str)); + } + } + + return NULL; +} diff --git a/node_modules/sharp/src/metadata.h b/node_modules/sharp/src/metadata.h new file mode 100644 index 0000000000000000000000000000000000000000..b31af869d9c68937aa9689cc8d6ff67a7d59c95e --- /dev/null +++ b/node_modules/sharp/src/metadata.h @@ -0,0 +1,85 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_METADATA_H_ +#define SRC_METADATA_H_ + +#include +#include + +#include "./common.h" + +typedef std::vector> MetadataComments; + +struct MetadataBaton { + // Input + sharp::InputDescriptor *input; + // Output + std::string format; + int width; + int height; + std::string space; + int channels; + std::string depth; + int density; + std::string chromaSubsampling; + bool isProgressive; + int paletteBitDepth; + int pages; + int pageHeight; + int loop; + std::vector delay; + int pagePrimary; + std::string compression; + std::string resolutionUnit; + std::string formatMagick; + std::vector> levels; + int subifds; + std::vector background; + bool hasProfile; + bool hasAlpha; + int orientation; + char *exif; + size_t exifLength; + char *icc; + size_t iccLength; + char *iptc; + size_t iptcLength; + char *xmp; + size_t xmpLength; + char *tifftagPhotoshop; + size_t tifftagPhotoshopLength; + MetadataComments comments; + std::string err; + + MetadataBaton(): + input(nullptr), + width(0), + height(0), + channels(0), + density(0), + isProgressive(false), + paletteBitDepth(0), + pages(0), + pageHeight(0), + loop(-1), + pagePrimary(-1), + subifds(0), + hasProfile(false), + hasAlpha(false), + orientation(0), + exif(nullptr), + exifLength(0), + icc(nullptr), + iccLength(0), + iptc(nullptr), + iptcLength(0), + xmp(nullptr), + xmpLength(0), + tifftagPhotoshop(nullptr), + tifftagPhotoshopLength(0) {} +}; + +Napi::Value metadata(const Napi::CallbackInfo& info); + +#endif // SRC_METADATA_H_ diff --git a/node_modules/sharp/src/operations.cc b/node_modules/sharp/src/operations.cc new file mode 100644 index 0000000000000000000000000000000000000000..775f6134e8e340de5cfcc317d67faa77bb5140c4 --- /dev/null +++ b/node_modules/sharp/src/operations.cc @@ -0,0 +1,475 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include +#include + +#include "common.h" +#include "operations.h" + +using vips::VImage; +using vips::VError; + +namespace sharp { + /* + * Tint an image using the provided RGB. + */ + VImage Tint(VImage image, std::vector const tint) { + std::vector const tintLab = (VImage::black(1, 1) + tint) + .colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)) + .getpoint(0, 0); + // LAB identity function + VImage identityLab = VImage::identity(VImage::option()->set("bands", 3)) + .colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)); + // Scale luminance range, 0.0 to 1.0 + VImage l = identityLab[0] / 100; + // Weighting functions + VImage weightL = 1.0 - 4.0 * ((l - 0.5) * (l - 0.5)); + VImage weightAB = (weightL * tintLab).extract_band(1, VImage::option()->set("n", 2)); + identityLab = identityLab[0].bandjoin(weightAB); + // Convert lookup table to sRGB + VImage lut = identityLab.colourspace(VIPS_INTERPRETATION_sRGB, + VImage::option()->set("source_space", VIPS_INTERPRETATION_LAB)); + // Original colourspace + VipsInterpretation typeBeforeTint = image.interpretation(); + if (typeBeforeTint == VIPS_INTERPRETATION_RGB) { + typeBeforeTint = VIPS_INTERPRETATION_sRGB; + } + // Apply lookup table + if (HasAlpha(image)) { + VImage alpha = image[image.bands() - 1]; + image = RemoveAlpha(image) + .colourspace(VIPS_INTERPRETATION_B_W) + .maplut(lut) + .colourspace(typeBeforeTint) + .bandjoin(alpha); + } else { + image = image + .colourspace(VIPS_INTERPRETATION_B_W) + .maplut(lut) + .colourspace(typeBeforeTint); + } + return image; + } + + /* + * Stretch luminance to cover full dynamic range. + */ + VImage Normalise(VImage image, int const lower, int const upper) { + // Get original colourspace + VipsInterpretation typeBeforeNormalize = image.interpretation(); + if (typeBeforeNormalize == VIPS_INTERPRETATION_RGB) { + typeBeforeNormalize = VIPS_INTERPRETATION_sRGB; + } + // Convert to LAB colourspace + VImage lab = image.colourspace(VIPS_INTERPRETATION_LAB); + // Extract luminance + VImage luminance = lab[0]; + + // Find luminance range + int const min = lower == 0 ? luminance.min() : luminance.percent(lower); + int const max = upper == 100 ? luminance.max() : luminance.percent(upper); + + if (std::abs(max - min) > 1) { + // Extract chroma + VImage chroma = lab.extract_band(1, VImage::option()->set("n", 2)); + // Calculate multiplication factor and addition + double f = 100.0 / (max - min); + double a = -(min * f); + // Scale luminance, join to chroma, convert back to original colourspace + VImage normalized = luminance.linear(f, a).bandjoin(chroma).colourspace(typeBeforeNormalize); + // Attach original alpha channel, if any + if (HasAlpha(image)) { + // Extract original alpha channel + VImage alpha = image[image.bands() - 1]; + // Join alpha channel to normalised image + return normalized.bandjoin(alpha); + } else { + return normalized; + } + } + return image; + } + + /* + * Contrast limiting adapative histogram equalization (CLAHE) + */ + VImage Clahe(VImage image, int const width, int const height, int const maxSlope) { + return image.hist_local(width, height, VImage::option()->set("max_slope", maxSlope)); + } + + /* + * Gamma encoding/decoding + */ + VImage Gamma(VImage image, double const exponent) { + if (HasAlpha(image)) { + // Separate alpha channel + VImage alpha = image[image.bands() - 1]; + return RemoveAlpha(image).gamma(VImage::option()->set("exponent", exponent)).bandjoin(alpha); + } else { + return image.gamma(VImage::option()->set("exponent", exponent)); + } + } + + /* + * Flatten image to remove alpha channel + */ + VImage Flatten(VImage image, std::vector flattenBackground) { + double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0; + std::vector background { + flattenBackground[0] * multiplier, + flattenBackground[1] * multiplier, + flattenBackground[2] * multiplier + }; + return image.flatten(VImage::option()->set("background", background)); + } + + /** + * Produce the "negative" of the image. + */ + VImage Negate(VImage image, bool const negateAlpha) { + if (HasAlpha(image) && !negateAlpha) { + // Separate alpha channel + VImage alpha = image[image.bands() - 1]; + return RemoveAlpha(image).invert().bandjoin(alpha); + } else { + return image.invert(); + } + } + + /* + * Gaussian blur. Use sigma of -1.0 for fast blur. + */ + VImage Blur(VImage image, double const sigma, VipsPrecision precision, double const minAmpl) { + if (sigma == -1.0) { + // Fast, mild blur - averages neighbouring pixels + VImage blur = VImage::new_matrixv(3, 3, + 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0); + blur.set("scale", 9.0); + return image.conv(blur); + } else { + // Slower, accurate Gaussian blur + return StaySequential(image).gaussblur(sigma, VImage::option() + ->set("precision", precision) + ->set("min_ampl", minAmpl)); + } + } + + /* + * Convolution with a kernel. + */ + VImage Convolve(VImage image, int const width, int const height, + double const scale, double const offset, + std::vector const &kernel_v + ) { + VImage kernel = VImage::new_from_memory( + static_cast(const_cast(kernel_v.data())), + width * height * sizeof(double), + width, + height, + 1, + VIPS_FORMAT_DOUBLE); + kernel.set("scale", scale); + kernel.set("offset", offset); + + return image.conv(kernel); + } + + /* + * Recomb with a Matrix of the given bands/channel size. + * Eg. RGB will be a 3x3 matrix. + */ + VImage Recomb(VImage image, std::vector const& matrix) { + double* m = const_cast(matrix.data()); + image = image.colourspace(VIPS_INTERPRETATION_sRGB); + if (matrix.size() == 9) { + return image + .recomb(image.bands() == 3 + ? VImage::new_matrix(3, 3, m, 9) + : VImage::new_matrixv(4, 4, + m[0], m[1], m[2], 0.0, + m[3], m[4], m[5], 0.0, + m[6], m[7], m[8], 0.0, + 0.0, 0.0, 0.0, 1.0)); + } else { + return image.recomb(VImage::new_matrix(4, 4, m, 16)); + } + } + + VImage Modulate(VImage image, double const brightness, double const saturation, + int const hue, double const lightness) { + VipsInterpretation colourspaceBeforeModulate = image.interpretation(); + if (HasAlpha(image)) { + // Separate alpha channel + VImage alpha = image[image.bands() - 1]; + return RemoveAlpha(image) + .colourspace(VIPS_INTERPRETATION_LCH) + .linear( + { brightness, saturation, 1}, + { lightness, 0.0, static_cast(hue) } + ) + .colourspace(colourspaceBeforeModulate) + .bandjoin(alpha); + } else { + return image + .colourspace(VIPS_INTERPRETATION_LCH) + .linear( + { brightness, saturation, 1 }, + { lightness, 0.0, static_cast(hue) } + ) + .colourspace(colourspaceBeforeModulate); + } + } + + /* + * Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen. + */ + VImage Sharpen(VImage image, double const sigma, double const m1, double const m2, + double const x1, double const y2, double const y3) { + if (sigma == -1.0) { + // Fast, mild sharpen + VImage sharpen = VImage::new_matrixv(3, 3, + -1.0, -1.0, -1.0, + -1.0, 32.0, -1.0, + -1.0, -1.0, -1.0); + sharpen.set("scale", 24.0); + return image.conv(sharpen); + } else { + // Slow, accurate sharpen in LAB colour space, with control over flat vs jagged areas + VipsInterpretation colourspaceBeforeSharpen = image.interpretation(); + if (colourspaceBeforeSharpen == VIPS_INTERPRETATION_RGB) { + colourspaceBeforeSharpen = VIPS_INTERPRETATION_sRGB; + } + return image + .sharpen(VImage::option() + ->set("sigma", sigma) + ->set("m1", m1) + ->set("m2", m2) + ->set("x1", x1) + ->set("y2", y2) + ->set("y3", y3)) + .colourspace(colourspaceBeforeSharpen); + } + } + + VImage Threshold(VImage image, double const threshold, bool const thresholdGrayscale) { + if (!thresholdGrayscale) { + return image >= threshold; + } + return image.colourspace(VIPS_INTERPRETATION_B_W) >= threshold; + } + + /* + Perform boolean/bitwise operation on image color channels - results in one channel image + */ + VImage Bandbool(VImage image, VipsOperationBoolean const boolean) { + image = image.bandbool(boolean); + return image.copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_B_W)); + } + + /* + Perform bitwise boolean operation between images + */ + VImage Boolean(VImage image, VImage imageR, VipsOperationBoolean const boolean) { + return image.boolean(imageR, boolean); + } + + /* + Trim an image + */ + VImage Trim(VImage image, std::vector background, double threshold, bool const lineArt) { + if (image.width() < 3 && image.height() < 3) { + throw VError("Image to trim must be at least 3x3 pixels"); + } + if (background.size() == 0) { + // Top-left pixel provides the default background colour if none is given + background = image.extract_area(0, 0, 1, 1)(0, 0); + } else if (sharp::Is16Bit(image.interpretation())) { + for (size_t i = 0; i < background.size(); i++) { + background[i] *= 256.0; + } + threshold *= 256.0; + } + std::vector backgroundAlpha({ background.back() }); + if (HasAlpha(image)) { + background.pop_back(); + } else { + background.resize(image.bands()); + } + int left, top, width, height; + left = image.find_trim(&top, &width, &height, VImage::option() + ->set("background", background) + ->set("line_art", lineArt) + ->set("threshold", threshold)); + if (HasAlpha(image)) { + // Search alpha channel (A) + int leftA, topA, widthA, heightA; + VImage alpha = image[image.bands() - 1]; + leftA = alpha.find_trim(&topA, &widthA, &heightA, VImage::option() + ->set("background", backgroundAlpha) + ->set("line_art", lineArt) + ->set("threshold", threshold)); + if (widthA > 0 && heightA > 0) { + if (width > 0 && height > 0) { + // Combined bounding box (B) + int const leftB = std::min(left, leftA); + int const topB = std::min(top, topA); + int const widthB = std::max(left + width, leftA + widthA) - leftB; + int const heightB = std::max(top + height, topA + heightA) - topB; + return image.extract_area(leftB, topB, widthB, heightB); + } else { + // Use alpha only + return image.extract_area(leftA, topA, widthA, heightA); + } + } + } + if (width > 0 && height > 0) { + return image.extract_area(left, top, width, height); + } + return image; + } + + /* + * Calculate (a * in + b) + */ + VImage Linear(VImage image, std::vector const a, std::vector const b) { + size_t const bands = static_cast(image.bands()); + if (a.size() > bands) { + throw VError("Band expansion using linear is unsupported"); + } + bool const uchar = !Is16Bit(image.interpretation()); + if (HasAlpha(image) && a.size() != bands && (a.size() == 1 || a.size() == bands - 1 || bands - 1 == 1)) { + // Separate alpha channel + VImage alpha = image[bands - 1]; + return RemoveAlpha(image).linear(a, b, VImage::option()->set("uchar", uchar)).bandjoin(alpha); + } else { + return image.linear(a, b, VImage::option()->set("uchar", uchar)); + } + } + + /* + * Unflatten + */ + VImage Unflatten(VImage image) { + if (HasAlpha(image)) { + VImage alpha = image[image.bands() - 1]; + VImage noAlpha = RemoveAlpha(image); + return noAlpha.bandjoin(alpha & (noAlpha.colourspace(VIPS_INTERPRETATION_B_W) < 255)); + } else { + return image.bandjoin(image.colourspace(VIPS_INTERPRETATION_B_W) < 255); + } + } + + /* + * Ensure the image is in a given colourspace + */ + VImage EnsureColourspace(VImage image, VipsInterpretation colourspace) { + if (colourspace != VIPS_INTERPRETATION_LAST && image.interpretation() != colourspace) { + image = image.colourspace(colourspace, + VImage::option()->set("source_space", image.interpretation())); + } + return image; + } + + /* + * Split and crop each frame, reassemble, and update pageHeight. + */ + VImage CropMultiPage(VImage image, int left, int top, int width, int height, + int nPages, int *pageHeight) { + if (top == 0 && height == *pageHeight) { + // Fast path; no need to adjust the height of the multi-page image + return image.extract_area(left, 0, width, image.height()); + } else { + std::vector pages; + pages.reserve(nPages); + + // Split the image into cropped frames + image = StaySequential(image); + for (int i = 0; i < nPages; i++) { + pages.push_back( + image.extract_area(left, *pageHeight * i + top, width, height)); + } + + // Reassemble the frames into a tall, thin image + VImage assembled = VImage::arrayjoin(pages, + VImage::option()->set("across", 1)); + + // Update the page height + *pageHeight = height; + + return assembled; + } + } + + /* + * Split into frames, embed each frame, reassemble, and update pageHeight. + */ + VImage EmbedMultiPage(VImage image, int left, int top, int width, int height, + VipsExtend extendWith, std::vector background, int nPages, int *pageHeight) { + if (top == 0 && height == *pageHeight) { + // Fast path; no need to adjust the height of the multi-page image + return image.embed(left, 0, width, image.height(), VImage::option() + ->set("extend", extendWith) + ->set("background", background)); + } else if (left == 0 && width == image.width()) { + // Fast path; no need to adjust the width of the multi-page image + std::vector pages; + pages.reserve(nPages); + + // Rearrange the tall image into a vertical grid + image = image.grid(*pageHeight, nPages, 1); + + // Do the embed on the wide image + image = image.embed(0, top, image.width(), height, VImage::option() + ->set("extend", extendWith) + ->set("background", background)); + + // Split the wide image into frames + for (int i = 0; i < nPages; i++) { + pages.push_back( + image.extract_area(width * i, 0, width, height)); + } + + // Reassemble the frames into a tall, thin image + VImage assembled = VImage::arrayjoin(pages, + VImage::option()->set("across", 1)); + + // Update the page height + *pageHeight = height; + + return assembled; + } else { + std::vector pages; + pages.reserve(nPages); + + // Split the image into frames + for (int i = 0; i < nPages; i++) { + pages.push_back( + image.extract_area(0, *pageHeight * i, image.width(), *pageHeight)); + } + + // Embed each frame in the target size + for (int i = 0; i < nPages; i++) { + pages[i] = pages[i].embed(left, top, width, height, VImage::option() + ->set("extend", extendWith) + ->set("background", background)); + } + + // Reassemble the frames into a tall, thin image + VImage assembled = VImage::arrayjoin(pages, + VImage::option()->set("across", 1)); + + // Update the page height + *pageHeight = height; + + return assembled; + } + } + +} // namespace sharp diff --git a/node_modules/sharp/src/operations.h b/node_modules/sharp/src/operations.h new file mode 100644 index 0000000000000000000000000000000000000000..b2881d65d683bef478e541f66ec87c485232e4b9 --- /dev/null +++ b/node_modules/sharp/src/operations.h @@ -0,0 +1,125 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_OPERATIONS_H_ +#define SRC_OPERATIONS_H_ + +#include +#include +#include +#include +#include + +using vips::VImage; + +namespace sharp { + + /* + * Tint an image using the provided RGB. + */ + VImage Tint(VImage image, std::vector const tint); + + /* + * Stretch luminance to cover full dynamic range. + */ + VImage Normalise(VImage image, int const lower, int const upper); + + /* + * Contrast limiting adapative histogram equalization (CLAHE) + */ + VImage Clahe(VImage image, int const width, int const height, int const maxSlope); + + /* + * Gamma encoding/decoding + */ + VImage Gamma(VImage image, double const exponent); + + /* + * Flatten image to remove alpha channel + */ + VImage Flatten(VImage image, std::vector flattenBackground); + + /* + * Produce the "negative" of the image. + */ + VImage Negate(VImage image, bool const negateAlpha); + + /* + * Gaussian blur. Use sigma of -1.0 for fast blur. + */ + VImage Blur(VImage image, double const sigma, VipsPrecision precision, double const minAmpl); + + /* + * Convolution with a kernel. + */ + VImage Convolve(VImage image, int const width, int const height, + double const scale, double const offset, std::vector const &kernel_v); + + /* + * Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen. + */ + VImage Sharpen(VImage image, double const sigma, double const m1, double const m2, + double const x1, double const y2, double const y3); + + /* + Threshold an image + */ + VImage Threshold(VImage image, double const threshold, bool const thresholdColor); + + /* + Perform boolean/bitwise operation on image color channels - results in one channel image + */ + VImage Bandbool(VImage image, VipsOperationBoolean const boolean); + + /* + Perform bitwise boolean operation between images + */ + VImage Boolean(VImage image, VImage imageR, VipsOperationBoolean const boolean); + + /* + Trim an image + */ + VImage Trim(VImage image, std::vector background, double threshold, bool const lineArt); + + /* + * Linear adjustment (a * in + b) + */ + VImage Linear(VImage image, std::vector const a, std::vector const b); + + /* + * Unflatten + */ + VImage Unflatten(VImage image); + + /* + * Recomb with a Matrix of the given bands/channel size. + * Eg. RGB will be a 3x3 matrix. + */ + VImage Recomb(VImage image, std::vector const &matrix); + + /* + * Modulate brightness, saturation, hue and lightness + */ + VImage Modulate(VImage image, double const brightness, double const saturation, + int const hue, double const lightness); + + /* + * Ensure the image is in a given colourspace + */ + VImage EnsureColourspace(VImage image, VipsInterpretation colourspace); + + /* + * Split and crop each frame, reassemble, and update pageHeight. + */ + VImage CropMultiPage(VImage image, int left, int top, int width, int height, + int nPages, int *pageHeight); + + /* + * Split into frames, embed each frame, reassemble, and update pageHeight. + */ + VImage EmbedMultiPage(VImage image, int left, int top, int width, int height, + VipsExtend extendWith, std::vector background, int nPages, int *pageHeight); + +} // namespace sharp + +#endif // SRC_OPERATIONS_H_ diff --git a/node_modules/sharp/src/pipeline.cc b/node_modules/sharp/src/pipeline.cc new file mode 100644 index 0000000000000000000000000000000000000000..ac5ead01e715af1ccc23646946e6ba02543c3a19 --- /dev/null +++ b/node_modules/sharp/src/pipeline.cc @@ -0,0 +1,1758 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "common.h" +#include "operations.h" +#include "pipeline.h" + +#ifdef _WIN32 +#define STAT64_STRUCT __stat64 +#define STAT64_FUNCTION _stat64 +#elif defined(_LARGEFILE64_SOURCE) +#define STAT64_STRUCT stat64 +#define STAT64_FUNCTION stat64 +#else +#define STAT64_STRUCT stat +#define STAT64_FUNCTION stat +#endif + +class PipelineWorker : public Napi::AsyncWorker { + public: + PipelineWorker(Napi::Function callback, PipelineBaton *baton, + Napi::Function debuglog, Napi::Function queueListener) : + Napi::AsyncWorker(callback), + baton(baton), + debuglog(Napi::Persistent(debuglog)), + queueListener(Napi::Persistent(queueListener)) {} + ~PipelineWorker() {} + + // libuv worker + void Execute() { + // Decrement queued task counter + sharp::counterQueue--; + // Increment processing task counter + sharp::counterProcess++; + + try { + // Open input + vips::VImage image; + sharp::ImageType inputImageType; + std::tie(image, inputImageType) = sharp::OpenInput(baton->input); + VipsAccess access = baton->input->access; + image = sharp::EnsureColourspace(image, baton->colourspacePipeline); + + int nPages = baton->input->pages; + if (nPages == -1) { + // Resolve the number of pages if we need to render until the end of the document + nPages = image.get_typeof(VIPS_META_N_PAGES) != 0 + ? image.get_int(VIPS_META_N_PAGES) - baton->input->page + : 1; + } + + // Get pre-resize page height + int pageHeight = sharp::GetPageHeight(image); + + // Calculate angle of rotation + VipsAngle rotation = VIPS_ANGLE_D0; + VipsAngle autoRotation = VIPS_ANGLE_D0; + bool autoFlip = false; + bool autoFlop = false; + + if (baton->useExifOrientation) { + // Rotate and flip image according to Exif orientation + std::tie(autoRotation, autoFlip, autoFlop) = CalculateExifRotationAndFlip(sharp::ExifOrientation(image)); + image = sharp::RemoveExifOrientation(image); + } else { + rotation = CalculateAngleRotation(baton->angle); + } + + // Rotate pre-extract + bool const shouldRotateBefore = baton->rotateBeforePreExtract && + (rotation != VIPS_ANGLE_D0 || autoRotation != VIPS_ANGLE_D0 || + autoFlip || baton->flip || autoFlop || baton->flop || + baton->rotationAngle != 0.0); + + if (shouldRotateBefore) { + image = sharp::StaySequential(image, + rotation != VIPS_ANGLE_D0 || + autoRotation != VIPS_ANGLE_D0 || + autoFlip || + baton->flip || + baton->rotationAngle != 0.0); + + if (autoRotation != VIPS_ANGLE_D0) { + if (autoRotation != VIPS_ANGLE_D180) { + MultiPageUnsupported(nPages, "Rotate"); + } + image = image.rot(autoRotation); + autoRotation = VIPS_ANGLE_D0; + } + if (autoFlip) { + image = image.flip(VIPS_DIRECTION_VERTICAL); + autoFlip = false; + } else if (baton->flip) { + image = image.flip(VIPS_DIRECTION_VERTICAL); + baton->flip = false; + } + if (autoFlop) { + image = image.flip(VIPS_DIRECTION_HORIZONTAL); + autoFlop = false; + } else if (baton->flop) { + image = image.flip(VIPS_DIRECTION_HORIZONTAL); + baton->flop = false; + } + if (rotation != VIPS_ANGLE_D0) { + if (rotation != VIPS_ANGLE_D180) { + MultiPageUnsupported(nPages, "Rotate"); + } + image = image.rot(rotation); + rotation = VIPS_ANGLE_D0; + } + if (baton->rotationAngle != 0.0) { + MultiPageUnsupported(nPages, "Rotate"); + std::vector background; + std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, false); + image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background)).copy_memory(); + } + } + + // Trim + if (baton->trimThreshold >= 0.0) { + MultiPageUnsupported(nPages, "Trim"); + image = sharp::StaySequential(image); + image = sharp::Trim(image, baton->trimBackground, baton->trimThreshold, baton->trimLineArt); + baton->trimOffsetLeft = image.xoffset(); + baton->trimOffsetTop = image.yoffset(); + } + + // Pre extraction + if (baton->topOffsetPre != -1) { + image = nPages > 1 + ? sharp::CropMultiPage(image, + baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre, nPages, &pageHeight) + : image.extract_area(baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre); + } + + // Get pre-resize image width and height + int inputWidth = image.width(); + int inputHeight = image.height(); + + // Is there just one page? Shrink to inputHeight instead + if (nPages == 1) { + pageHeight = inputHeight; + } + + // Scaling calculations + double hshrink; + double vshrink; + int targetResizeWidth = baton->width; + int targetResizeHeight = baton->height; + + // When auto-rotating by 90 or 270 degrees, swap the target width and + // height to ensure the behavior aligns with how it would have been if + // the rotation had taken place *before* resizing. + if (!baton->rotateBeforePreExtract && + (autoRotation == VIPS_ANGLE_D90 || autoRotation == VIPS_ANGLE_D270)) { + std::swap(targetResizeWidth, targetResizeHeight); + } + + // Shrink to pageHeight, so we work for multi-page images + std::tie(hshrink, vshrink) = sharp::ResolveShrink( + inputWidth, pageHeight, targetResizeWidth, targetResizeHeight, + baton->canvas, baton->withoutEnlargement, baton->withoutReduction); + + // The jpeg preload shrink. + int jpegShrinkOnLoad = 1; + + // WebP, PDF, SVG scale + double scale = 1.0; + + // Try to reload input using shrink-on-load for JPEG, WebP, SVG and PDF, when: + // - the width or height parameters are specified; + // - gamma correction doesn't need to be applied; + // - trimming or pre-resize extract isn't required; + // - input colourspace is not specified; + bool const shouldPreShrink = (targetResizeWidth > 0 || targetResizeHeight > 0) && + baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold < 0.0 && + baton->colourspacePipeline == VIPS_INTERPRETATION_LAST && !shouldRotateBefore; + + if (shouldPreShrink) { + // The common part of the shrink: the bit by which both axes must be shrunk + double shrink = std::min(hshrink, vshrink); + + if (inputImageType == sharp::ImageType::JPEG) { + // Leave at least a factor of two for the final resize step, when fastShrinkOnLoad: false + // for more consistent results and to avoid extra sharpness to the image + int factor = baton->fastShrinkOnLoad ? 1 : 2; + if (shrink >= 8 * factor) { + jpegShrinkOnLoad = 8; + } else if (shrink >= 4 * factor) { + jpegShrinkOnLoad = 4; + } else if (shrink >= 2 * factor) { + jpegShrinkOnLoad = 2; + } + // Lower shrink-on-load for known libjpeg rounding errors + if (jpegShrinkOnLoad > 1 && static_cast(shrink) == jpegShrinkOnLoad) { + jpegShrinkOnLoad /= 2; + } + } else if (inputImageType == sharp::ImageType::WEBP && baton->fastShrinkOnLoad && shrink > 1.0) { + // Avoid upscaling via webp + scale = 1.0 / shrink; + } else if (inputImageType == sharp::ImageType::SVG || + inputImageType == sharp::ImageType::PDF) { + scale = 1.0 / shrink; + } + } + + // Reload input using shrink-on-load, it'll be an integer shrink + // factor for jpegload*, a double scale factor for webpload*, + // pdfload* and svgload* + if (jpegShrinkOnLoad > 1) { + vips::VOption *option = VImage::option() + ->set("access", access) + ->set("shrink", jpegShrinkOnLoad) + ->set("unlimited", baton->input->unlimited) + ->set("fail_on", baton->input->failOn); + if (baton->input->buffer != nullptr) { + // Reload JPEG buffer + VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); + image = VImage::jpegload_buffer(blob, option); + vips_area_unref(reinterpret_cast(blob)); + } else { + // Reload JPEG file + image = VImage::jpegload(const_cast(baton->input->file.data()), option); + } + } else if (scale != 1.0) { + vips::VOption *option = VImage::option() + ->set("access", access) + ->set("scale", scale) + ->set("fail_on", baton->input->failOn); + if (inputImageType == sharp::ImageType::WEBP) { + option->set("n", baton->input->pages); + option->set("page", baton->input->page); + + if (baton->input->buffer != nullptr) { + // Reload WebP buffer + VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); + image = VImage::webpload_buffer(blob, option); + vips_area_unref(reinterpret_cast(blob)); + } else { + // Reload WebP file + image = VImage::webpload(const_cast(baton->input->file.data()), option); + } + } else if (inputImageType == sharp::ImageType::SVG) { + option->set("unlimited", baton->input->unlimited); + option->set("dpi", baton->input->density); + + if (baton->input->buffer != nullptr) { + // Reload SVG buffer + VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); + image = VImage::svgload_buffer(blob, option); + vips_area_unref(reinterpret_cast(blob)); + } else { + // Reload SVG file + image = VImage::svgload(const_cast(baton->input->file.data()), option); + } + sharp::SetDensity(image, baton->input->density); + if (image.width() > 32767 || image.height() > 32767) { + throw vips::VError("Input SVG image will exceed 32767x32767 pixel limit when scaled"); + } + } else if (inputImageType == sharp::ImageType::PDF) { + option->set("n", baton->input->pages); + option->set("page", baton->input->page); + option->set("dpi", baton->input->density); + + if (baton->input->buffer != nullptr) { + // Reload PDF buffer + VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); + image = VImage::pdfload_buffer(blob, option); + vips_area_unref(reinterpret_cast(blob)); + } else { + // Reload PDF file + image = VImage::pdfload(const_cast(baton->input->file.data()), option); + } + + sharp::SetDensity(image, baton->input->density); + } + } else { + if (inputImageType == sharp::ImageType::SVG && (image.width() > 32767 || image.height() > 32767)) { + throw vips::VError("Input SVG image exceeds 32767x32767 pixel limit"); + } + } + + // Any pre-shrinking may already have been done + inputWidth = image.width(); + inputHeight = image.height(); + + // After pre-shrink, but before the main shrink stage + // Reuse the initial pageHeight if we didn't pre-shrink + if (shouldPreShrink) { + pageHeight = sharp::GetPageHeight(image); + } + + // Shrink to pageHeight, so we work for multi-page images + std::tie(hshrink, vshrink) = sharp::ResolveShrink( + inputWidth, pageHeight, targetResizeWidth, targetResizeHeight, + baton->canvas, baton->withoutEnlargement, baton->withoutReduction); + + int targetHeight = static_cast(std::rint(static_cast(pageHeight) / vshrink)); + int targetPageHeight = targetHeight; + + // In toilet-roll mode, we must adjust vshrink so that we exactly hit + // pageHeight or we'll have pixels straddling pixel boundaries + if (inputHeight > pageHeight) { + targetHeight *= nPages; + vshrink = static_cast(inputHeight) / targetHeight; + } + + // Ensure we're using a device-independent colour space + std::pair inputProfile(nullptr, 0); + if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->withIccProfile.empty()) { + // Cache input profile for use with output + inputProfile = sharp::GetProfile(image); + baton->input->ignoreIcc = true; + } + char const *processingProfile = image.interpretation() == VIPS_INTERPRETATION_RGB16 ? "p3" : "srgb"; + if ( + sharp::HasProfile(image) && + image.interpretation() != VIPS_INTERPRETATION_LABS && + image.interpretation() != VIPS_INTERPRETATION_GREY16 && + baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK && + !baton->input->ignoreIcc + ) { + // Convert to sRGB/P3 using embedded profile + try { + image = image.icc_transform(processingProfile, VImage::option() + ->set("embedded", true) + ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8) + ->set("intent", VIPS_INTENT_PERCEPTUAL)); + } catch(...) { + sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, "Invalid embedded profile", nullptr); + } + } else if ( + image.interpretation() == VIPS_INTERPRETATION_CMYK && + baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK + ) { + image = image.icc_transform(processingProfile, VImage::option() + ->set("input_profile", "cmyk") + ->set("intent", VIPS_INTENT_PERCEPTUAL)); + } + + // Flatten image to remove alpha channel + if (baton->flatten && sharp::HasAlpha(image)) { + image = sharp::Flatten(image, baton->flattenBackground); + } + + // Gamma encoding (darken) + if (baton->gamma >= 1 && baton->gamma <= 3) { + image = sharp::Gamma(image, 1.0 / baton->gamma); + } + + // Convert to greyscale (linear, therefore after gamma encoding, if any) + if (baton->greyscale) { + image = image.colourspace(VIPS_INTERPRETATION_B_W); + } + + bool const shouldResize = hshrink != 1.0 || vshrink != 1.0; + bool const shouldBlur = baton->blurSigma != 0.0; + bool const shouldConv = baton->convKernelWidth * baton->convKernelHeight > 0; + bool const shouldSharpen = baton->sharpenSigma != 0.0; + bool const shouldComposite = !baton->composite.empty(); + + if (shouldComposite && !sharp::HasAlpha(image)) { + image = sharp::EnsureAlpha(image, 1); + } + + VipsBandFormat premultiplyFormat = image.format(); + bool const shouldPremultiplyAlpha = sharp::HasAlpha(image) && + (shouldResize || shouldBlur || shouldConv || shouldSharpen); + + if (shouldPremultiplyAlpha) { + image = image.premultiply().cast(premultiplyFormat); + } + + // Resize + if (shouldResize) { + image = image.resize(1.0 / hshrink, VImage::option() + ->set("vscale", 1.0 / vshrink) + ->set("kernel", baton->kernel)); + } + + image = sharp::StaySequential(image, + autoRotation != VIPS_ANGLE_D0 || + baton->flip || + autoFlip || + rotation != VIPS_ANGLE_D0); + // Auto-rotate post-extract + if (autoRotation != VIPS_ANGLE_D0) { + if (autoRotation != VIPS_ANGLE_D180) { + MultiPageUnsupported(nPages, "Rotate"); + } + image = image.rot(autoRotation); + } + // Mirror vertically (up-down) about the x-axis + if (baton->flip || autoFlip) { + image = image.flip(VIPS_DIRECTION_VERTICAL); + } + // Mirror horizontally (left-right) about the y-axis + if (baton->flop || autoFlop) { + image = image.flip(VIPS_DIRECTION_HORIZONTAL); + } + // Rotate post-extract 90-angle + if (rotation != VIPS_ANGLE_D0) { + if (rotation != VIPS_ANGLE_D180) { + MultiPageUnsupported(nPages, "Rotate"); + } + image = image.rot(rotation); + } + + // Join additional color channels to the image + if (!baton->joinChannelIn.empty()) { + VImage joinImage; + sharp::ImageType joinImageType = sharp::ImageType::UNKNOWN; + + for (unsigned int i = 0; i < baton->joinChannelIn.size(); i++) { + baton->joinChannelIn[i]->access = access; + std::tie(joinImage, joinImageType) = sharp::OpenInput(baton->joinChannelIn[i]); + joinImage = sharp::EnsureColourspace(joinImage, baton->colourspacePipeline); + image = image.bandjoin(joinImage); + } + image = image.copy(VImage::option()->set("interpretation", baton->colourspace)); + image = sharp::RemoveGifPalette(image); + } + + inputWidth = image.width(); + inputHeight = nPages > 1 ? targetPageHeight : image.height(); + + // Resolve dimensions + if (baton->width <= 0) { + baton->width = inputWidth; + } + if (baton->height <= 0) { + baton->height = inputHeight; + } + + // Crop/embed + if (inputWidth != baton->width || inputHeight != baton->height) { + if (baton->canvas == sharp::Canvas::EMBED) { + std::vector background; + std::tie(image, background) = sharp::ApplyAlpha(image, baton->resizeBackground, shouldPremultiplyAlpha); + + // Embed + int left; + int top; + std::tie(left, top) = sharp::CalculateEmbedPosition( + inputWidth, inputHeight, baton->width, baton->height, baton->position); + int width = std::max(inputWidth, baton->width); + int height = std::max(inputHeight, baton->height); + + image = nPages > 1 + ? sharp::EmbedMultiPage(image, + left, top, width, height, VIPS_EXTEND_BACKGROUND, background, nPages, &targetPageHeight) + : image.embed(left, top, width, height, VImage::option() + ->set("extend", VIPS_EXTEND_BACKGROUND) + ->set("background", background)); + } else if (baton->canvas == sharp::Canvas::CROP) { + if (baton->width > inputWidth) { + baton->width = inputWidth; + } + if (baton->height > inputHeight) { + baton->height = inputHeight; + } + + // Crop + if (baton->position < 9) { + // Gravity-based crop + int left; + int top; + + std::tie(left, top) = sharp::CalculateCrop( + inputWidth, inputHeight, baton->width, baton->height, baton->position); + int width = std::min(inputWidth, baton->width); + int height = std::min(inputHeight, baton->height); + + image = nPages > 1 + ? sharp::CropMultiPage(image, + left, top, width, height, nPages, &targetPageHeight) + : image.extract_area(left, top, width, height); + } else { + int attention_x; + int attention_y; + + // Attention-based or Entropy-based crop + MultiPageUnsupported(nPages, "Resize strategy"); + image = sharp::StaySequential(image); + image = image.smartcrop(baton->width, baton->height, VImage::option() + ->set("interesting", baton->position == 16 ? VIPS_INTERESTING_ENTROPY : VIPS_INTERESTING_ATTENTION) + ->set("premultiplied", shouldPremultiplyAlpha) + ->set("attention_x", &attention_x) + ->set("attention_y", &attention_y)); + baton->hasCropOffset = true; + baton->cropOffsetLeft = static_cast(image.xoffset()); + baton->cropOffsetTop = static_cast(image.yoffset()); + baton->hasAttentionCenter = true; + baton->attentionX = static_cast(attention_x * jpegShrinkOnLoad / scale); + baton->attentionY = static_cast(attention_y * jpegShrinkOnLoad / scale); + } + } + } + + // Rotate post-extract non-90 angle + if (!baton->rotateBeforePreExtract && baton->rotationAngle != 0.0) { + MultiPageUnsupported(nPages, "Rotate"); + image = sharp::StaySequential(image); + std::vector background; + std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, shouldPremultiplyAlpha); + image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background)); + } + + // Post extraction + if (baton->topOffsetPost != -1) { + if (nPages > 1) { + image = sharp::CropMultiPage(image, + baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost, + nPages, &targetPageHeight); + + // heightPost is used in the info object, so update to reflect the number of pages + baton->heightPost *= nPages; + } else { + image = image.extract_area( + baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost); + } + } + + // Affine transform + if (!baton->affineMatrix.empty()) { + MultiPageUnsupported(nPages, "Affine"); + image = sharp::StaySequential(image); + std::vector background; + std::tie(image, background) = sharp::ApplyAlpha(image, baton->affineBackground, shouldPremultiplyAlpha); + vips::VInterpolate interp = vips::VInterpolate::new_from_name( + const_cast(baton->affineInterpolator.data())); + image = image.affine(baton->affineMatrix, VImage::option()->set("background", background) + ->set("idx", baton->affineIdx) + ->set("idy", baton->affineIdy) + ->set("odx", baton->affineOdx) + ->set("ody", baton->affineOdy) + ->set("interpolate", interp)); + } + + // Extend edges + if (baton->extendTop > 0 || baton->extendBottom > 0 || baton->extendLeft > 0 || baton->extendRight > 0) { + // Embed + baton->width = image.width() + baton->extendLeft + baton->extendRight; + baton->height = (nPages > 1 ? targetPageHeight : image.height()) + baton->extendTop + baton->extendBottom; + + if (baton->extendWith == VIPS_EXTEND_BACKGROUND) { + std::vector background; + std::tie(image, background) = sharp::ApplyAlpha(image, baton->extendBackground, shouldPremultiplyAlpha); + + image = sharp::StaySequential(image, nPages > 1); + image = nPages > 1 + ? sharp::EmbedMultiPage(image, + baton->extendLeft, baton->extendTop, baton->width, baton->height, + baton->extendWith, background, nPages, &targetPageHeight) + : image.embed(baton->extendLeft, baton->extendTop, baton->width, baton->height, + VImage::option()->set("extend", baton->extendWith)->set("background", background)); + } else { + std::vector ignoredBackground(1); + image = sharp::StaySequential(image); + image = nPages > 1 + ? sharp::EmbedMultiPage(image, + baton->extendLeft, baton->extendTop, baton->width, baton->height, + baton->extendWith, ignoredBackground, nPages, &targetPageHeight) + : image.embed(baton->extendLeft, baton->extendTop, baton->width, baton->height, + VImage::option()->set("extend", baton->extendWith)); + } + } + // Median - must happen before blurring, due to the utility of blurring after thresholding + if (baton->medianSize > 0) { + image = image.median(baton->medianSize); + } + + // Threshold - must happen before blurring, due to the utility of blurring after thresholding + // Threshold - must happen before unflatten to enable non-white unflattening + if (baton->threshold != 0) { + image = sharp::Threshold(image, baton->threshold, baton->thresholdGrayscale); + } + + // Blur + if (shouldBlur) { + image = sharp::Blur(image, baton->blurSigma, baton->precision, baton->minAmpl); + } + + // Unflatten the image + if (baton->unflatten) { + image = sharp::Unflatten(image); + } + + // Convolve + if (shouldConv) { + image = sharp::Convolve(image, + baton->convKernelWidth, baton->convKernelHeight, + baton->convKernelScale, baton->convKernelOffset, + baton->convKernel); + } + + // Recomb + if (!baton->recombMatrix.empty()) { + image = sharp::Recomb(image, baton->recombMatrix); + } + + // Modulate + if (baton->brightness != 1.0 || baton->saturation != 1.0 || baton->hue != 0.0 || baton->lightness != 0.0) { + image = sharp::Modulate(image, baton->brightness, baton->saturation, baton->hue, baton->lightness); + } + + // Sharpen + if (shouldSharpen) { + image = sharp::Sharpen(image, baton->sharpenSigma, baton->sharpenM1, baton->sharpenM2, + baton->sharpenX1, baton->sharpenY2, baton->sharpenY3); + } + + // Reverse premultiplication after all transformations + if (shouldPremultiplyAlpha) { + image = image.unpremultiply().cast(premultiplyFormat); + } + baton->premultiplied = shouldPremultiplyAlpha; + + // Composite + if (shouldComposite) { + std::vector images = { image }; + std::vector modes, xs, ys; + for (Composite *composite : baton->composite) { + VImage compositeImage; + sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN; + composite->input->access = access; + std::tie(compositeImage, compositeImageType) = sharp::OpenInput(composite->input); + compositeImage = sharp::EnsureColourspace(compositeImage, baton->colourspacePipeline); + // Verify within current dimensions + if (compositeImage.width() > image.width() || compositeImage.height() > image.height()) { + throw vips::VError("Image to composite must have same dimensions or smaller"); + } + // Check if overlay is tiled + if (composite->tile) { + int across = 0; + int down = 0; + // Use gravity in overlay + if (compositeImage.width() <= image.width()) { + across = static_cast(ceil(static_cast(image.width()) / compositeImage.width())); + // Ensure odd number of tiles across when gravity is centre, north or south + if (composite->gravity == 0 || composite->gravity == 1 || composite->gravity == 3) { + across |= 1; + } + } + if (compositeImage.height() <= image.height()) { + down = static_cast(ceil(static_cast(image.height()) / compositeImage.height())); + // Ensure odd number of tiles down when gravity is centre, east or west + if (composite->gravity == 0 || composite->gravity == 2 || composite->gravity == 4) { + down |= 1; + } + } + if (across != 0 || down != 0) { + int left; + int top; + compositeImage = sharp::StaySequential(compositeImage).replicate(across, down); + if (composite->hasOffset) { + std::tie(left, top) = sharp::CalculateCrop( + compositeImage.width(), compositeImage.height(), image.width(), image.height(), + composite->left, composite->top); + } else { + std::tie(left, top) = sharp::CalculateCrop( + compositeImage.width(), compositeImage.height(), image.width(), image.height(), composite->gravity); + } + compositeImage = compositeImage.extract_area(left, top, image.width(), image.height()); + } + // gravity was used for extract_area, set it back to its default value of 0 + composite->gravity = 0; + } + // Ensure image to composite is sRGB with unpremultiplied alpha + compositeImage = compositeImage.colourspace(VIPS_INTERPRETATION_sRGB); + if (!sharp::HasAlpha(compositeImage)) { + compositeImage = sharp::EnsureAlpha(compositeImage, 1); + } + if (composite->premultiplied) compositeImage = compositeImage.unpremultiply(); + // Calculate position + int left; + int top; + if (composite->hasOffset) { + // Composite image at given offsets + if (composite->tile) { + std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(), + compositeImage.width(), compositeImage.height(), composite->left, composite->top); + } else { + left = composite->left; + top = composite->top; + } + } else { + // Composite image with given gravity + std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(), + compositeImage.width(), compositeImage.height(), composite->gravity); + } + images.push_back(compositeImage); + modes.push_back(composite->mode); + xs.push_back(left); + ys.push_back(top); + } + image = VImage::composite(images, modes, VImage::option()->set("x", xs)->set("y", ys)); + image = sharp::RemoveGifPalette(image); + } + + // Gamma decoding (brighten) + if (baton->gammaOut >= 1 && baton->gammaOut <= 3) { + image = sharp::Gamma(image, baton->gammaOut); + } + + // Linear adjustment (a * in + b) + if (!baton->linearA.empty()) { + image = sharp::Linear(image, baton->linearA, baton->linearB); + } + + // Apply normalisation - stretch luminance to cover full dynamic range + if (baton->normalise) { + image = sharp::StaySequential(image); + image = sharp::Normalise(image, baton->normaliseLower, baton->normaliseUpper); + } + + // Apply contrast limiting adaptive histogram equalization (CLAHE) + if (baton->claheWidth != 0 && baton->claheHeight != 0) { + image = sharp::StaySequential(image); + image = sharp::Clahe(image, baton->claheWidth, baton->claheHeight, baton->claheMaxSlope); + } + + // Apply bitwise boolean operation between images + if (baton->boolean != nullptr) { + VImage booleanImage; + sharp::ImageType booleanImageType = sharp::ImageType::UNKNOWN; + baton->boolean->access = access; + std::tie(booleanImage, booleanImageType) = sharp::OpenInput(baton->boolean); + booleanImage = sharp::EnsureColourspace(booleanImage, baton->colourspacePipeline); + image = sharp::Boolean(image, booleanImage, baton->booleanOp); + image = sharp::RemoveGifPalette(image); + } + + // Apply per-channel Bandbool bitwise operations after all other operations + if (baton->bandBoolOp >= VIPS_OPERATION_BOOLEAN_AND && baton->bandBoolOp < VIPS_OPERATION_BOOLEAN_LAST) { + image = sharp::Bandbool(image, baton->bandBoolOp); + } + + // Tint the image + if (baton->tint[0] >= 0.0) { + image = sharp::Tint(image, baton->tint); + } + + // Remove alpha channel, if any + if (baton->removeAlpha) { + image = sharp::RemoveAlpha(image); + } + + // Ensure alpha channel, if missing + if (baton->ensureAlpha != -1) { + image = sharp::EnsureAlpha(image, baton->ensureAlpha); + } + + // Convert image to sRGB, if not already + if (sharp::Is16Bit(image.interpretation())) { + image = image.cast(VIPS_FORMAT_USHORT); + } + if (image.interpretation() != baton->colourspace) { + // Convert colourspace, pass the current known interpretation so libvips doesn't have to guess + image = image.colourspace(baton->colourspace, VImage::option()->set("source_space", image.interpretation())); + // Transform colours from embedded profile to output profile + if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK && + baton->withIccProfile.empty() && sharp::HasProfile(image)) { + image = image.icc_transform(processingProfile, VImage::option() + ->set("embedded", true) + ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8) + ->set("intent", VIPS_INTENT_PERCEPTUAL)); + } + } + + // Extract channel + if (baton->extractChannel > -1) { + if (baton->extractChannel >= image.bands()) { + if (baton->extractChannel == 3 && sharp::HasAlpha(image)) { + baton->extractChannel = image.bands() - 1; + } else { + (baton->err) + .append("Cannot extract channel ").append(std::to_string(baton->extractChannel)) + .append(" from image with channels 0-").append(std::to_string(image.bands() - 1)); + return Error(); + } + } + VipsInterpretation colourspace = sharp::Is16Bit(image.interpretation()) + ? VIPS_INTERPRETATION_GREY16 + : VIPS_INTERPRETATION_B_W; + image = image + .extract_band(baton->extractChannel) + .copy(VImage::option()->set("interpretation", colourspace)); + } + + // Apply output ICC profile + if (!baton->withIccProfile.empty()) { + try { + image = image.icc_transform(const_cast(baton->withIccProfile.data()), VImage::option() + ->set("input_profile", processingProfile) + ->set("embedded", true) + ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8) + ->set("intent", VIPS_INTENT_PERCEPTUAL)); + } catch(...) { + sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, "Invalid profile", nullptr); + } + } else if (baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) { + image = sharp::SetProfile(image, inputProfile); + } + + // Negate the colours in the image + if (baton->negate) { + image = sharp::Negate(image, baton->negateAlpha); + } + + // Override EXIF Orientation tag + if (baton->withMetadataOrientation != -1) { + image = sharp::SetExifOrientation(image, baton->withMetadataOrientation); + } + // Override pixel density + if (baton->withMetadataDensity > 0) { + image = sharp::SetDensity(image, baton->withMetadataDensity); + } + // EXIF key/value pairs + if (baton->keepMetadata & VIPS_FOREIGN_KEEP_EXIF) { + image = image.copy(); + if (!baton->withExifMerge) { + image = sharp::RemoveExif(image); + } + for (const auto& s : baton->withExif) { + image.set(s.first.data(), s.second.data()); + } + } + + // Number of channels used in output image + baton->channels = image.bands(); + baton->width = image.width(); + baton->height = image.height(); + + image = sharp::SetAnimationProperties( + image, nPages, targetPageHeight, baton->delay, baton->loop); + + if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) { + baton->pageHeightOut = image.get_int(VIPS_META_PAGE_HEIGHT); + baton->pagesOut = image.get_int(VIPS_META_N_PAGES); + } + + // Output + sharp::SetTimeout(image, baton->timeoutSeconds); + if (baton->fileOut.empty()) { + // Buffer output + if (baton->formatOut == "jpeg" || (baton->formatOut == "input" && inputImageType == sharp::ImageType::JPEG)) { + // Write JPEG to buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); + VipsArea *area = reinterpret_cast(image.jpegsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->jpegQuality) + ->set("interlace", baton->jpegProgressive) + ->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF + : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("trellis_quant", baton->jpegTrellisQuantisation) + ->set("quant_table", baton->jpegQuantisationTable) + ->set("overshoot_deringing", baton->jpegOvershootDeringing) + ->set("optimize_scans", baton->jpegOptimiseScans) + ->set("optimize_coding", baton->jpegOptimiseCoding))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "jpeg"; + if (baton->colourspace == VIPS_INTERPRETATION_CMYK) { + baton->channels = std::min(baton->channels, 4); + } else { + baton->channels = std::min(baton->channels, 3); + } + } else if (baton->formatOut == "jp2" || (baton->formatOut == "input" + && inputImageType == sharp::ImageType::JP2)) { + // Write JP2 to Buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JP2); + VipsArea *area = reinterpret_cast(image.jp2ksave_buffer(VImage::option() + ->set("Q", baton->jp2Quality) + ->set("lossless", baton->jp2Lossless) + ->set("subsample_mode", baton->jp2ChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("tile_height", baton->jp2TileHeight) + ->set("tile_width", baton->jp2TileWidth))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "jp2"; + } else if (baton->formatOut == "png" || (baton->formatOut == "input" && + (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::SVG))) { + // Write PNG to buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG); + VipsArea *area = reinterpret_cast(image.pngsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("interlace", baton->pngProgressive) + ->set("compression", baton->pngCompressionLevel) + ->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE) + ->set("palette", baton->pngPalette) + ->set("Q", baton->pngQuality) + ->set("effort", baton->pngEffort) + ->set("bitdepth", sharp::Is16Bit(image.interpretation()) ? 16 : baton->pngBitdepth) + ->set("dither", baton->pngDither))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "png"; + } else if (baton->formatOut == "webp" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::WEBP)) { + // Write WEBP to buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP); + VipsArea *area = reinterpret_cast(image.webpsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->webpQuality) + ->set("lossless", baton->webpLossless) + ->set("near_lossless", baton->webpNearLossless) + ->set("smart_subsample", baton->webpSmartSubsample) + ->set("preset", baton->webpPreset) + ->set("effort", baton->webpEffort) + ->set("min_size", baton->webpMinSize) + ->set("mixed", baton->webpMixed) + ->set("alpha_q", baton->webpAlphaQuality))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "webp"; + } else if (baton->formatOut == "gif" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::GIF)) { + // Write GIF to buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF); + VipsArea *area = reinterpret_cast(image.gifsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("bitdepth", baton->gifBitdepth) + ->set("effort", baton->gifEffort) + ->set("reuse", baton->gifReuse) + ->set("interlace", baton->gifProgressive) + ->set("interframe_maxerror", baton->gifInterFrameMaxError) + ->set("interpalette_maxerror", baton->gifInterPaletteMaxError) + ->set("dither", baton->gifDither))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "gif"; + } else if (baton->formatOut == "tiff" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::TIFF)) { + // Write TIFF to buffer + if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) { + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); + baton->channels = std::min(baton->channels, 3); + } + // Cast pixel values to float, if required + if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) { + image = image.cast(VIPS_FORMAT_FLOAT); + } + VipsArea *area = reinterpret_cast(image.tiffsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->tiffQuality) + ->set("bitdepth", baton->tiffBitdepth) + ->set("compression", baton->tiffCompression) + ->set("miniswhite", baton->tiffMiniswhite) + ->set("predictor", baton->tiffPredictor) + ->set("pyramid", baton->tiffPyramid) + ->set("tile", baton->tiffTile) + ->set("tile_height", baton->tiffTileHeight) + ->set("tile_width", baton->tiffTileWidth) + ->set("xres", baton->tiffXres) + ->set("yres", baton->tiffYres) + ->set("resunit", baton->tiffResolutionUnit))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "tiff"; + } else if (baton->formatOut == "heif" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::HEIF)) { + // Write HEIF to buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF); + image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR); + VipsArea *area = reinterpret_cast(image.heifsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->heifQuality) + ->set("compression", baton->heifCompression) + ->set("effort", baton->heifEffort) + ->set("bitdepth", baton->heifBitdepth) + ->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("lossless", baton->heifLossless))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "heif"; + } else if (baton->formatOut == "dz") { + // Write DZ to buffer + baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP; + if (!sharp::HasAlpha(image)) { + baton->tileBackground.pop_back(); + } + image = sharp::StaySequential(image, baton->tileAngle != 0); + vips::VOption *options = BuildOptionsDZ(baton); + VipsArea *area = reinterpret_cast(image.dzsave_buffer(options)); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "dz"; + } else if (baton->formatOut == "jxl" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::JXL)) { + // Write JXL to buffer + image = sharp::RemoveAnimationProperties(image); + VipsArea *area = reinterpret_cast(image.jxlsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("distance", baton->jxlDistance) + ->set("tier", baton->jxlDecodingTier) + ->set("effort", baton->jxlEffort) + ->set("lossless", baton->jxlLossless))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "jxl"; + } else if (baton->formatOut == "raw" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::RAW)) { + // Write raw, uncompressed image data to buffer + if (baton->greyscale || image.interpretation() == VIPS_INTERPRETATION_B_W) { + // Extract first band for greyscale image + image = image[0]; + baton->channels = 1; + } + if (image.format() != baton->rawDepth) { + // Cast pixels to requested format + image = image.cast(baton->rawDepth); + } + // Get raw image data + baton->bufferOut = static_cast(image.write_to_memory(&baton->bufferOutLength)); + if (baton->bufferOut == nullptr) { + (baton->err).append("Could not allocate enough memory for raw output"); + return Error(); + } + baton->formatOut = "raw"; + } else { + // Unsupported output format + (baton->err).append("Unsupported output format "); + if (baton->formatOut == "input") { + (baton->err).append(ImageTypeId(inputImageType)); + } else { + (baton->err).append(baton->formatOut); + } + return Error(); + } + } else { + // File output + bool const isJpeg = sharp::IsJpeg(baton->fileOut); + bool const isPng = sharp::IsPng(baton->fileOut); + bool const isWebp = sharp::IsWebp(baton->fileOut); + bool const isGif = sharp::IsGif(baton->fileOut); + bool const isTiff = sharp::IsTiff(baton->fileOut); + bool const isJp2 = sharp::IsJp2(baton->fileOut); + bool const isHeif = sharp::IsHeif(baton->fileOut); + bool const isJxl = sharp::IsJxl(baton->fileOut); + bool const isDz = sharp::IsDz(baton->fileOut); + bool const isDzZip = sharp::IsDzZip(baton->fileOut); + bool const isV = sharp::IsV(baton->fileOut); + bool const mightMatchInput = baton->formatOut == "input"; + bool const willMatchInput = mightMatchInput && + !(isJpeg || isPng || isWebp || isGif || isTiff || isJp2 || isHeif || isDz || isDzZip || isV); + + if (baton->formatOut == "jpeg" || (mightMatchInput && isJpeg) || + (willMatchInput && inputImageType == sharp::ImageType::JPEG)) { + // Write JPEG to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); + image.jpegsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->jpegQuality) + ->set("interlace", baton->jpegProgressive) + ->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF + : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("trellis_quant", baton->jpegTrellisQuantisation) + ->set("quant_table", baton->jpegQuantisationTable) + ->set("overshoot_deringing", baton->jpegOvershootDeringing) + ->set("optimize_scans", baton->jpegOptimiseScans) + ->set("optimize_coding", baton->jpegOptimiseCoding)); + baton->formatOut = "jpeg"; + baton->channels = std::min(baton->channels, 3); + } else if (baton->formatOut == "jp2" || (mightMatchInput && isJp2) || + (willMatchInput && (inputImageType == sharp::ImageType::JP2))) { + // Write JP2 to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JP2); + image.jp2ksave(const_cast(baton->fileOut.data()), VImage::option() + ->set("Q", baton->jp2Quality) + ->set("lossless", baton->jp2Lossless) + ->set("subsample_mode", baton->jp2ChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("tile_height", baton->jp2TileHeight) + ->set("tile_width", baton->jp2TileWidth)); + baton->formatOut = "jp2"; + } else if (baton->formatOut == "png" || (mightMatchInput && isPng) || (willMatchInput && + (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::SVG))) { + // Write PNG to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG); + image.pngsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("interlace", baton->pngProgressive) + ->set("compression", baton->pngCompressionLevel) + ->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE) + ->set("palette", baton->pngPalette) + ->set("Q", baton->pngQuality) + ->set("bitdepth", sharp::Is16Bit(image.interpretation()) ? 16 : baton->pngBitdepth) + ->set("effort", baton->pngEffort) + ->set("dither", baton->pngDither)); + baton->formatOut = "png"; + } else if (baton->formatOut == "webp" || (mightMatchInput && isWebp) || + (willMatchInput && inputImageType == sharp::ImageType::WEBP)) { + // Write WEBP to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP); + image.webpsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->webpQuality) + ->set("lossless", baton->webpLossless) + ->set("near_lossless", baton->webpNearLossless) + ->set("smart_subsample", baton->webpSmartSubsample) + ->set("preset", baton->webpPreset) + ->set("effort", baton->webpEffort) + ->set("min_size", baton->webpMinSize) + ->set("mixed", baton->webpMixed) + ->set("alpha_q", baton->webpAlphaQuality)); + baton->formatOut = "webp"; + } else if (baton->formatOut == "gif" || (mightMatchInput && isGif) || + (willMatchInput && inputImageType == sharp::ImageType::GIF)) { + // Write GIF to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF); + image.gifsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("bitdepth", baton->gifBitdepth) + ->set("effort", baton->gifEffort) + ->set("reuse", baton->gifReuse) + ->set("interlace", baton->gifProgressive) + ->set("dither", baton->gifDither)); + baton->formatOut = "gif"; + } else if (baton->formatOut == "tiff" || (mightMatchInput && isTiff) || + (willMatchInput && inputImageType == sharp::ImageType::TIFF)) { + // Write TIFF to file + if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) { + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); + baton->channels = std::min(baton->channels, 3); + } + // Cast pixel values to float, if required + if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) { + image = image.cast(VIPS_FORMAT_FLOAT); + } + image.tiffsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->tiffQuality) + ->set("bitdepth", baton->tiffBitdepth) + ->set("compression", baton->tiffCompression) + ->set("miniswhite", baton->tiffMiniswhite) + ->set("predictor", baton->tiffPredictor) + ->set("pyramid", baton->tiffPyramid) + ->set("tile", baton->tiffTile) + ->set("tile_height", baton->tiffTileHeight) + ->set("tile_width", baton->tiffTileWidth) + ->set("xres", baton->tiffXres) + ->set("yres", baton->tiffYres) + ->set("resunit", baton->tiffResolutionUnit)); + baton->formatOut = "tiff"; + } else if (baton->formatOut == "heif" || (mightMatchInput && isHeif) || + (willMatchInput && inputImageType == sharp::ImageType::HEIF)) { + // Write HEIF to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF); + image = sharp::RemoveAnimationProperties(image).cast(VIPS_FORMAT_UCHAR); + image.heifsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->heifQuality) + ->set("compression", baton->heifCompression) + ->set("effort", baton->heifEffort) + ->set("bitdepth", baton->heifBitdepth) + ->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("lossless", baton->heifLossless)); + baton->formatOut = "heif"; + } else if (baton->formatOut == "jxl" || (mightMatchInput && isJxl) || + (willMatchInput && inputImageType == sharp::ImageType::JXL)) { + // Write JXL to file + image = sharp::RemoveAnimationProperties(image); + image.jxlsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("distance", baton->jxlDistance) + ->set("tier", baton->jxlDecodingTier) + ->set("effort", baton->jxlEffort) + ->set("lossless", baton->jxlLossless)); + baton->formatOut = "jxl"; + } else if (baton->formatOut == "dz" || isDz || isDzZip) { + // Write DZ to file + if (isDzZip) { + baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP; + } + if (!sharp::HasAlpha(image)) { + baton->tileBackground.pop_back(); + } + image = sharp::StaySequential(image, baton->tileAngle != 0); + vips::VOption *options = BuildOptionsDZ(baton); + image.dzsave(const_cast(baton->fileOut.data()), options); + baton->formatOut = "dz"; + } else if (baton->formatOut == "v" || (mightMatchInput && isV) || + (willMatchInput && inputImageType == sharp::ImageType::VIPS)) { + // Write V to file + image.vipssave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata)); + baton->formatOut = "v"; + } else { + // Unsupported output format + (baton->err).append("Unsupported output format " + baton->fileOut); + return Error(); + } + } + } catch (vips::VError const &err) { + char const *what = err.what(); + if (what && what[0]) { + (baton->err).append(what); + } else { + (baton->err).append("Unknown error"); + } + } + // Clean up libvips' per-request data and threads + vips_error_clear(); + vips_thread_shutdown(); + } + + void OnOK() { + Napi::Env env = Env(); + Napi::HandleScope scope(env); + + // Handle warnings + std::string warning = sharp::VipsWarningPop(); + while (!warning.empty()) { + debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) }); + warning = sharp::VipsWarningPop(); + } + + if (baton->err.empty()) { + int width = baton->width; + int height = baton->height; + if (baton->topOffsetPre != -1 && (baton->width == -1 || baton->height == -1)) { + width = baton->widthPre; + height = baton->heightPre; + } + if (baton->topOffsetPost != -1) { + width = baton->widthPost; + height = baton->heightPost; + } + // Info Object + Napi::Object info = Napi::Object::New(env); + info.Set("format", baton->formatOut); + info.Set("width", static_cast(width)); + info.Set("height", static_cast(height)); + info.Set("channels", static_cast(baton->channels)); + if (baton->formatOut == "raw") { + info.Set("depth", vips_enum_nick(VIPS_TYPE_BAND_FORMAT, baton->rawDepth)); + } + info.Set("premultiplied", baton->premultiplied); + if (baton->hasCropOffset) { + info.Set("cropOffsetLeft", static_cast(baton->cropOffsetLeft)); + info.Set("cropOffsetTop", static_cast(baton->cropOffsetTop)); + } + if (baton->hasAttentionCenter) { + info.Set("attentionX", static_cast(baton->attentionX)); + info.Set("attentionY", static_cast(baton->attentionY)); + } + if (baton->trimThreshold >= 0.0) { + info.Set("trimOffsetLeft", static_cast(baton->trimOffsetLeft)); + info.Set("trimOffsetTop", static_cast(baton->trimOffsetTop)); + } + if (baton->input->textAutofitDpi) { + info.Set("textAutofitDpi", static_cast(baton->input->textAutofitDpi)); + } + if (baton->pageHeightOut) { + info.Set("pageHeight", static_cast(baton->pageHeightOut)); + info.Set("pages", static_cast(baton->pagesOut)); + } + + if (baton->bufferOutLength > 0) { + // Add buffer size to info + info.Set("size", static_cast(baton->bufferOutLength)); + // Pass ownership of output data to Buffer instance + Napi::Buffer data = Napi::Buffer::NewOrCopy(env, static_cast(baton->bufferOut), + baton->bufferOutLength, sharp::FreeCallback); + Callback().Call(Receiver().Value(), { env.Null(), data, info }); + } else { + // Add file size to info + struct STAT64_STRUCT st; + if (STAT64_FUNCTION(baton->fileOut.data(), &st) == 0) { + info.Set("size", static_cast(st.st_size)); + } + Callback().Call(Receiver().Value(), { env.Null(), info }); + } + } else { + Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() }); + } + + // Delete baton + delete baton->input; + delete baton->boolean; + for (Composite *composite : baton->composite) { + delete composite->input; + delete composite; + } + for (sharp::InputDescriptor *input : baton->joinChannelIn) { + delete input; + } + delete baton; + + // Decrement processing task counter + sharp::counterProcess--; + Napi::Number queueLength = Napi::Number::New(env, static_cast(sharp::counterQueue)); + queueListener.Call(Receiver().Value(), { queueLength }); + } + + private: + PipelineBaton *baton; + Napi::FunctionReference debuglog; + Napi::FunctionReference queueListener; + + void MultiPageUnsupported(int const pages, std::string op) { + if (pages > 1) { + throw vips::VError(op + " is not supported for multi-page images"); + } + } + + /* + Calculate the angle of rotation and need-to-flip for the given Exif orientation + By default, returns zero, i.e. no rotation. + */ + std::tuple + CalculateExifRotationAndFlip(int const exifOrientation) { + VipsAngle rotate = VIPS_ANGLE_D0; + bool flip = false; + bool flop = false; + switch (exifOrientation) { + case 6: rotate = VIPS_ANGLE_D90; break; + case 3: rotate = VIPS_ANGLE_D180; break; + case 8: rotate = VIPS_ANGLE_D270; break; + case 2: flop = true; break; // flop 1 + case 7: flip = true; rotate = VIPS_ANGLE_D90; break; // flip 6 + case 4: flop = true; rotate = VIPS_ANGLE_D180; break; // flop 3 + case 5: flip = true; rotate = VIPS_ANGLE_D270; break; // flip 8 + } + return std::make_tuple(rotate, flip, flop); + } + + /* + Calculate the rotation for the given angle. + Supports any positive or negative angle that is a multiple of 90. + */ + VipsAngle + CalculateAngleRotation(int angle) { + angle = angle % 360; + if (angle < 0) + angle = 360 + angle; + switch (angle) { + case 90: return VIPS_ANGLE_D90; + case 180: return VIPS_ANGLE_D180; + case 270: return VIPS_ANGLE_D270; + } + return VIPS_ANGLE_D0; + } + + /* + Assemble the suffix argument to dzsave, which is the format (by extname) + alongside comma-separated arguments to the corresponding `formatsave` vips + action. + */ + std::string + AssembleSuffixString(std::string extname, std::vector> options) { + std::string argument; + for (auto const &option : options) { + if (!argument.empty()) { + argument += ","; + } + argument += option.first + "=" + option.second; + } + return extname + "[" + argument + "]"; + } + + /* + Build VOption for dzsave + */ + vips::VOption* + BuildOptionsDZ(PipelineBaton *baton) { + // Forward format options through suffix + std::string suffix; + if (baton->tileFormat == "png") { + std::vector> options { + {"interlace", baton->pngProgressive ? "true" : "false"}, + {"compression", std::to_string(baton->pngCompressionLevel)}, + {"filter", baton->pngAdaptiveFiltering ? "all" : "none"} + }; + suffix = AssembleSuffixString(".png", options); + } else if (baton->tileFormat == "webp") { + std::vector> options { + {"Q", std::to_string(baton->webpQuality)}, + {"alpha_q", std::to_string(baton->webpAlphaQuality)}, + {"lossless", baton->webpLossless ? "true" : "false"}, + {"near_lossless", baton->webpNearLossless ? "true" : "false"}, + {"smart_subsample", baton->webpSmartSubsample ? "true" : "false"}, + {"preset", vips_enum_nick(VIPS_TYPE_FOREIGN_WEBP_PRESET, baton->webpPreset)}, + {"min_size", baton->webpMinSize ? "true" : "false"}, + {"mixed", baton->webpMixed ? "true" : "false"}, + {"effort", std::to_string(baton->webpEffort)} + }; + suffix = AssembleSuffixString(".webp", options); + } else { + std::vector> options { + {"Q", std::to_string(baton->jpegQuality)}, + {"interlace", baton->jpegProgressive ? "true" : "false"}, + {"subsample_mode", baton->jpegChromaSubsampling == "4:4:4" ? "off" : "on"}, + {"trellis_quant", baton->jpegTrellisQuantisation ? "true" : "false"}, + {"quant_table", std::to_string(baton->jpegQuantisationTable)}, + {"overshoot_deringing", baton->jpegOvershootDeringing ? "true": "false"}, + {"optimize_scans", baton->jpegOptimiseScans ? "true": "false"}, + {"optimize_coding", baton->jpegOptimiseCoding ? "true": "false"} + }; + std::string extname = baton->tileLayout == VIPS_FOREIGN_DZ_LAYOUT_DZ ? ".jpeg" : ".jpg"; + suffix = AssembleSuffixString(extname, options); + } + vips::VOption *options = VImage::option() + ->set("keep", baton->keepMetadata) + ->set("tile_size", baton->tileSize) + ->set("overlap", baton->tileOverlap) + ->set("container", baton->tileContainer) + ->set("layout", baton->tileLayout) + ->set("suffix", const_cast(suffix.data())) + ->set("angle", CalculateAngleRotation(baton->tileAngle)) + ->set("background", baton->tileBackground) + ->set("centre", baton->tileCentre) + ->set("id", const_cast(baton->tileId.data())) + ->set("skip_blanks", baton->tileSkipBlanks); + if (baton->tileDepth < VIPS_FOREIGN_DZ_DEPTH_LAST) { + options->set("depth", baton->tileDepth); + } + if (!baton->tileBasename.empty()) { + options->set("basename", const_cast(baton->tileBasename.data())); + } + return options; + } + + /* + Clear all thread-local data. + */ + void Error() { + // Clean up libvips' per-request data and threads + vips_error_clear(); + vips_thread_shutdown(); + } +}; + +/* + pipeline(options, output, callback) +*/ +Napi::Value pipeline(const Napi::CallbackInfo& info) { + // V8 objects are converted to non-V8 types held in the baton struct + PipelineBaton *baton = new PipelineBaton; + Napi::Object options = info[size_t(0)].As(); + + // Input + baton->input = sharp::CreateInputDescriptor(options.Get("input").As()); + // Extract image options + baton->topOffsetPre = sharp::AttrAsInt32(options, "topOffsetPre"); + baton->leftOffsetPre = sharp::AttrAsInt32(options, "leftOffsetPre"); + baton->widthPre = sharp::AttrAsInt32(options, "widthPre"); + baton->heightPre = sharp::AttrAsInt32(options, "heightPre"); + baton->topOffsetPost = sharp::AttrAsInt32(options, "topOffsetPost"); + baton->leftOffsetPost = sharp::AttrAsInt32(options, "leftOffsetPost"); + baton->widthPost = sharp::AttrAsInt32(options, "widthPost"); + baton->heightPost = sharp::AttrAsInt32(options, "heightPost"); + // Output image dimensions + baton->width = sharp::AttrAsInt32(options, "width"); + baton->height = sharp::AttrAsInt32(options, "height"); + // Canvas option + std::string canvas = sharp::AttrAsStr(options, "canvas"); + if (canvas == "crop") { + baton->canvas = sharp::Canvas::CROP; + } else if (canvas == "embed") { + baton->canvas = sharp::Canvas::EMBED; + } else if (canvas == "max") { + baton->canvas = sharp::Canvas::MAX; + } else if (canvas == "min") { + baton->canvas = sharp::Canvas::MIN; + } else if (canvas == "ignore_aspect") { + baton->canvas = sharp::Canvas::IGNORE_ASPECT; + } + // Composite + Napi::Array compositeArray = options.Get("composite").As(); + for (unsigned int i = 0; i < compositeArray.Length(); i++) { + Napi::Object compositeObject = compositeArray.Get(i).As(); + Composite *composite = new Composite; + composite->input = sharp::CreateInputDescriptor(compositeObject.Get("input").As()); + composite->mode = sharp::AttrAsEnum(compositeObject, "blend", VIPS_TYPE_BLEND_MODE); + composite->gravity = sharp::AttrAsUint32(compositeObject, "gravity"); + composite->left = sharp::AttrAsInt32(compositeObject, "left"); + composite->top = sharp::AttrAsInt32(compositeObject, "top"); + composite->hasOffset = sharp::AttrAsBool(compositeObject, "hasOffset"); + composite->tile = sharp::AttrAsBool(compositeObject, "tile"); + composite->premultiplied = sharp::AttrAsBool(compositeObject, "premultiplied"); + baton->composite.push_back(composite); + } + // Resize options + baton->withoutEnlargement = sharp::AttrAsBool(options, "withoutEnlargement"); + baton->withoutReduction = sharp::AttrAsBool(options, "withoutReduction"); + baton->position = sharp::AttrAsInt32(options, "position"); + baton->resizeBackground = sharp::AttrAsVectorOfDouble(options, "resizeBackground"); + baton->kernel = sharp::AttrAsEnum(options, "kernel", VIPS_TYPE_KERNEL); + baton->fastShrinkOnLoad = sharp::AttrAsBool(options, "fastShrinkOnLoad"); + // Join Channel Options + if (options.Has("joinChannelIn")) { + Napi::Array joinChannelArray = options.Get("joinChannelIn").As(); + for (unsigned int i = 0; i < joinChannelArray.Length(); i++) { + baton->joinChannelIn.push_back( + sharp::CreateInputDescriptor(joinChannelArray.Get(i).As())); + } + } + // Operators + baton->flatten = sharp::AttrAsBool(options, "flatten"); + baton->flattenBackground = sharp::AttrAsVectorOfDouble(options, "flattenBackground"); + baton->unflatten = sharp::AttrAsBool(options, "unflatten"); + baton->negate = sharp::AttrAsBool(options, "negate"); + baton->negateAlpha = sharp::AttrAsBool(options, "negateAlpha"); + baton->blurSigma = sharp::AttrAsDouble(options, "blurSigma"); + baton->precision = sharp::AttrAsEnum(options, "precision", VIPS_TYPE_PRECISION); + baton->minAmpl = sharp::AttrAsDouble(options, "minAmpl"); + baton->brightness = sharp::AttrAsDouble(options, "brightness"); + baton->saturation = sharp::AttrAsDouble(options, "saturation"); + baton->hue = sharp::AttrAsInt32(options, "hue"); + baton->lightness = sharp::AttrAsDouble(options, "lightness"); + baton->medianSize = sharp::AttrAsUint32(options, "medianSize"); + baton->sharpenSigma = sharp::AttrAsDouble(options, "sharpenSigma"); + baton->sharpenM1 = sharp::AttrAsDouble(options, "sharpenM1"); + baton->sharpenM2 = sharp::AttrAsDouble(options, "sharpenM2"); + baton->sharpenX1 = sharp::AttrAsDouble(options, "sharpenX1"); + baton->sharpenY2 = sharp::AttrAsDouble(options, "sharpenY2"); + baton->sharpenY3 = sharp::AttrAsDouble(options, "sharpenY3"); + baton->threshold = sharp::AttrAsInt32(options, "threshold"); + baton->thresholdGrayscale = sharp::AttrAsBool(options, "thresholdGrayscale"); + baton->trimBackground = sharp::AttrAsVectorOfDouble(options, "trimBackground"); + baton->trimThreshold = sharp::AttrAsDouble(options, "trimThreshold"); + baton->trimLineArt = sharp::AttrAsBool(options, "trimLineArt"); + baton->gamma = sharp::AttrAsDouble(options, "gamma"); + baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut"); + baton->linearA = sharp::AttrAsVectorOfDouble(options, "linearA"); + baton->linearB = sharp::AttrAsVectorOfDouble(options, "linearB"); + baton->greyscale = sharp::AttrAsBool(options, "greyscale"); + baton->normalise = sharp::AttrAsBool(options, "normalise"); + baton->normaliseLower = sharp::AttrAsUint32(options, "normaliseLower"); + baton->normaliseUpper = sharp::AttrAsUint32(options, "normaliseUpper"); + baton->tint = sharp::AttrAsVectorOfDouble(options, "tint"); + baton->claheWidth = sharp::AttrAsUint32(options, "claheWidth"); + baton->claheHeight = sharp::AttrAsUint32(options, "claheHeight"); + baton->claheMaxSlope = sharp::AttrAsUint32(options, "claheMaxSlope"); + baton->useExifOrientation = sharp::AttrAsBool(options, "useExifOrientation"); + baton->angle = sharp::AttrAsInt32(options, "angle"); + baton->rotationAngle = sharp::AttrAsDouble(options, "rotationAngle"); + baton->rotationBackground = sharp::AttrAsVectorOfDouble(options, "rotationBackground"); + baton->rotateBeforePreExtract = sharp::AttrAsBool(options, "rotateBeforePreExtract"); + baton->flip = sharp::AttrAsBool(options, "flip"); + baton->flop = sharp::AttrAsBool(options, "flop"); + baton->extendTop = sharp::AttrAsInt32(options, "extendTop"); + baton->extendBottom = sharp::AttrAsInt32(options, "extendBottom"); + baton->extendLeft = sharp::AttrAsInt32(options, "extendLeft"); + baton->extendRight = sharp::AttrAsInt32(options, "extendRight"); + baton->extendBackground = sharp::AttrAsVectorOfDouble(options, "extendBackground"); + baton->extendWith = sharp::AttrAsEnum(options, "extendWith", VIPS_TYPE_EXTEND); + baton->extractChannel = sharp::AttrAsInt32(options, "extractChannel"); + baton->affineMatrix = sharp::AttrAsVectorOfDouble(options, "affineMatrix"); + baton->affineBackground = sharp::AttrAsVectorOfDouble(options, "affineBackground"); + baton->affineIdx = sharp::AttrAsDouble(options, "affineIdx"); + baton->affineIdy = sharp::AttrAsDouble(options, "affineIdy"); + baton->affineOdx = sharp::AttrAsDouble(options, "affineOdx"); + baton->affineOdy = sharp::AttrAsDouble(options, "affineOdy"); + baton->affineInterpolator = sharp::AttrAsStr(options, "affineInterpolator"); + baton->removeAlpha = sharp::AttrAsBool(options, "removeAlpha"); + baton->ensureAlpha = sharp::AttrAsDouble(options, "ensureAlpha"); + if (options.Has("boolean")) { + baton->boolean = sharp::CreateInputDescriptor(options.Get("boolean").As()); + baton->booleanOp = sharp::AttrAsEnum(options, "booleanOp", VIPS_TYPE_OPERATION_BOOLEAN); + } + if (options.Has("bandBoolOp")) { + baton->bandBoolOp = sharp::AttrAsEnum(options, "bandBoolOp", VIPS_TYPE_OPERATION_BOOLEAN); + } + if (options.Has("convKernel")) { + Napi::Object kernel = options.Get("convKernel").As(); + baton->convKernelWidth = sharp::AttrAsUint32(kernel, "width"); + baton->convKernelHeight = sharp::AttrAsUint32(kernel, "height"); + baton->convKernelScale = sharp::AttrAsDouble(kernel, "scale"); + baton->convKernelOffset = sharp::AttrAsDouble(kernel, "offset"); + size_t const kernelSize = static_cast(baton->convKernelWidth * baton->convKernelHeight); + baton->convKernel.resize(kernelSize); + Napi::Array kdata = kernel.Get("kernel").As(); + for (unsigned int i = 0; i < kernelSize; i++) { + baton->convKernel[i] = sharp::AttrAsDouble(kdata, i); + } + } + if (options.Has("recombMatrix")) { + Napi::Array recombMatrix = options.Get("recombMatrix").As(); + unsigned int matrixElements = recombMatrix.Length(); + baton->recombMatrix.resize(matrixElements); + for (unsigned int i = 0; i < matrixElements; i++) { + baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i); + } + } + baton->colourspacePipeline = sharp::AttrAsEnum( + options, "colourspacePipeline", VIPS_TYPE_INTERPRETATION); + if (baton->colourspacePipeline == VIPS_INTERPRETATION_ERROR) { + baton->colourspacePipeline = VIPS_INTERPRETATION_LAST; + } + baton->colourspace = sharp::AttrAsEnum(options, "colourspace", VIPS_TYPE_INTERPRETATION); + if (baton->colourspace == VIPS_INTERPRETATION_ERROR) { + baton->colourspace = VIPS_INTERPRETATION_sRGB; + } + // Output + baton->formatOut = sharp::AttrAsStr(options, "formatOut"); + baton->fileOut = sharp::AttrAsStr(options, "fileOut"); + baton->keepMetadata = sharp::AttrAsUint32(options, "keepMetadata"); + baton->withMetadataOrientation = sharp::AttrAsUint32(options, "withMetadataOrientation"); + baton->withMetadataDensity = sharp::AttrAsDouble(options, "withMetadataDensity"); + baton->withIccProfile = sharp::AttrAsStr(options, "withIccProfile"); + Napi::Object withExif = options.Get("withExif").As(); + Napi::Array withExifKeys = withExif.GetPropertyNames(); + for (unsigned int i = 0; i < withExifKeys.Length(); i++) { + std::string k = sharp::AttrAsStr(withExifKeys, i); + if (withExif.HasOwnProperty(k)) { + baton->withExif.insert(std::make_pair(k, sharp::AttrAsStr(withExif, k))); + } + } + baton->withExifMerge = sharp::AttrAsBool(options, "withExifMerge"); + baton->timeoutSeconds = sharp::AttrAsUint32(options, "timeoutSeconds"); + // Format-specific + baton->jpegQuality = sharp::AttrAsUint32(options, "jpegQuality"); + baton->jpegProgressive = sharp::AttrAsBool(options, "jpegProgressive"); + baton->jpegChromaSubsampling = sharp::AttrAsStr(options, "jpegChromaSubsampling"); + baton->jpegTrellisQuantisation = sharp::AttrAsBool(options, "jpegTrellisQuantisation"); + baton->jpegQuantisationTable = sharp::AttrAsUint32(options, "jpegQuantisationTable"); + baton->jpegOvershootDeringing = sharp::AttrAsBool(options, "jpegOvershootDeringing"); + baton->jpegOptimiseScans = sharp::AttrAsBool(options, "jpegOptimiseScans"); + baton->jpegOptimiseCoding = sharp::AttrAsBool(options, "jpegOptimiseCoding"); + baton->pngProgressive = sharp::AttrAsBool(options, "pngProgressive"); + baton->pngCompressionLevel = sharp::AttrAsUint32(options, "pngCompressionLevel"); + baton->pngAdaptiveFiltering = sharp::AttrAsBool(options, "pngAdaptiveFiltering"); + baton->pngPalette = sharp::AttrAsBool(options, "pngPalette"); + baton->pngQuality = sharp::AttrAsUint32(options, "pngQuality"); + baton->pngEffort = sharp::AttrAsUint32(options, "pngEffort"); + baton->pngBitdepth = sharp::AttrAsUint32(options, "pngBitdepth"); + baton->pngDither = sharp::AttrAsDouble(options, "pngDither"); + baton->jp2Quality = sharp::AttrAsUint32(options, "jp2Quality"); + baton->jp2Lossless = sharp::AttrAsBool(options, "jp2Lossless"); + baton->jp2TileHeight = sharp::AttrAsUint32(options, "jp2TileHeight"); + baton->jp2TileWidth = sharp::AttrAsUint32(options, "jp2TileWidth"); + baton->jp2ChromaSubsampling = sharp::AttrAsStr(options, "jp2ChromaSubsampling"); + baton->webpQuality = sharp::AttrAsUint32(options, "webpQuality"); + baton->webpAlphaQuality = sharp::AttrAsUint32(options, "webpAlphaQuality"); + baton->webpLossless = sharp::AttrAsBool(options, "webpLossless"); + baton->webpNearLossless = sharp::AttrAsBool(options, "webpNearLossless"); + baton->webpSmartSubsample = sharp::AttrAsBool(options, "webpSmartSubsample"); + baton->webpPreset = sharp::AttrAsEnum(options, "webpPreset", VIPS_TYPE_FOREIGN_WEBP_PRESET); + baton->webpEffort = sharp::AttrAsUint32(options, "webpEffort"); + baton->webpMinSize = sharp::AttrAsBool(options, "webpMinSize"); + baton->webpMixed = sharp::AttrAsBool(options, "webpMixed"); + baton->gifBitdepth = sharp::AttrAsUint32(options, "gifBitdepth"); + baton->gifEffort = sharp::AttrAsUint32(options, "gifEffort"); + baton->gifDither = sharp::AttrAsDouble(options, "gifDither"); + baton->gifInterFrameMaxError = sharp::AttrAsDouble(options, "gifInterFrameMaxError"); + baton->gifInterPaletteMaxError = sharp::AttrAsDouble(options, "gifInterPaletteMaxError"); + baton->gifReuse = sharp::AttrAsBool(options, "gifReuse"); + baton->gifProgressive = sharp::AttrAsBool(options, "gifProgressive"); + baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality"); + baton->tiffPyramid = sharp::AttrAsBool(options, "tiffPyramid"); + baton->tiffMiniswhite = sharp::AttrAsBool(options, "tiffMiniswhite"); + baton->tiffBitdepth = sharp::AttrAsUint32(options, "tiffBitdepth"); + baton->tiffTile = sharp::AttrAsBool(options, "tiffTile"); + baton->tiffTileWidth = sharp::AttrAsUint32(options, "tiffTileWidth"); + baton->tiffTileHeight = sharp::AttrAsUint32(options, "tiffTileHeight"); + baton->tiffXres = sharp::AttrAsDouble(options, "tiffXres"); + baton->tiffYres = sharp::AttrAsDouble(options, "tiffYres"); + if (baton->tiffXres == 1.0 && baton->tiffYres == 1.0 && baton->withMetadataDensity > 0) { + baton->tiffXres = baton->tiffYres = baton->withMetadataDensity / 25.4; + } + baton->tiffCompression = sharp::AttrAsEnum( + options, "tiffCompression", VIPS_TYPE_FOREIGN_TIFF_COMPRESSION); + baton->tiffPredictor = sharp::AttrAsEnum( + options, "tiffPredictor", VIPS_TYPE_FOREIGN_TIFF_PREDICTOR); + baton->tiffResolutionUnit = sharp::AttrAsEnum( + options, "tiffResolutionUnit", VIPS_TYPE_FOREIGN_TIFF_RESUNIT); + baton->heifQuality = sharp::AttrAsUint32(options, "heifQuality"); + baton->heifLossless = sharp::AttrAsBool(options, "heifLossless"); + baton->heifCompression = sharp::AttrAsEnum( + options, "heifCompression", VIPS_TYPE_FOREIGN_HEIF_COMPRESSION); + baton->heifEffort = sharp::AttrAsUint32(options, "heifEffort"); + baton->heifChromaSubsampling = sharp::AttrAsStr(options, "heifChromaSubsampling"); + baton->heifBitdepth = sharp::AttrAsUint32(options, "heifBitdepth"); + baton->jxlDistance = sharp::AttrAsDouble(options, "jxlDistance"); + baton->jxlDecodingTier = sharp::AttrAsUint32(options, "jxlDecodingTier"); + baton->jxlEffort = sharp::AttrAsUint32(options, "jxlEffort"); + baton->jxlLossless = sharp::AttrAsBool(options, "jxlLossless"); + baton->rawDepth = sharp::AttrAsEnum(options, "rawDepth", VIPS_TYPE_BAND_FORMAT); + // Animated output properties + if (sharp::HasAttr(options, "loop")) { + baton->loop = sharp::AttrAsUint32(options, "loop"); + } + if (sharp::HasAttr(options, "delay")) { + baton->delay = sharp::AttrAsInt32Vector(options, "delay"); + } + baton->tileSize = sharp::AttrAsUint32(options, "tileSize"); + baton->tileOverlap = sharp::AttrAsUint32(options, "tileOverlap"); + baton->tileAngle = sharp::AttrAsInt32(options, "tileAngle"); + baton->tileBackground = sharp::AttrAsVectorOfDouble(options, "tileBackground"); + baton->tileSkipBlanks = sharp::AttrAsInt32(options, "tileSkipBlanks"); + baton->tileContainer = sharp::AttrAsEnum( + options, "tileContainer", VIPS_TYPE_FOREIGN_DZ_CONTAINER); + baton->tileLayout = sharp::AttrAsEnum(options, "tileLayout", VIPS_TYPE_FOREIGN_DZ_LAYOUT); + baton->tileFormat = sharp::AttrAsStr(options, "tileFormat"); + baton->tileDepth = sharp::AttrAsEnum(options, "tileDepth", VIPS_TYPE_FOREIGN_DZ_DEPTH); + baton->tileCentre = sharp::AttrAsBool(options, "tileCentre"); + baton->tileId = sharp::AttrAsStr(options, "tileId"); + baton->tileBasename = sharp::AttrAsStr(options, "tileBasename"); + + // Function to notify of libvips warnings + Napi::Function debuglog = options.Get("debuglog").As(); + + // Function to notify of queue length changes + Napi::Function queueListener = options.Get("queueListener").As(); + + // Join queue for worker thread + Napi::Function callback = info[size_t(1)].As(); + PipelineWorker *worker = new PipelineWorker(callback, baton, debuglog, queueListener); + worker->Receiver().Set("options", options); + worker->Queue(); + + // Increment queued task counter + Napi::Number queueLength = Napi::Number::New(info.Env(), static_cast(++sharp::counterQueue)); + queueListener.Call(info.This(), { queueLength }); + + return info.Env().Undefined(); +} diff --git a/node_modules/sharp/src/pipeline.h b/node_modules/sharp/src/pipeline.h new file mode 100644 index 0000000000000000000000000000000000000000..777a4c543bfebbae58a3e53ca4dc56636ffe9243 --- /dev/null +++ b/node_modules/sharp/src/pipeline.h @@ -0,0 +1,393 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_PIPELINE_H_ +#define SRC_PIPELINE_H_ + +#include +#include +#include +#include + +#include +#include + +#include "./common.h" + +Napi::Value pipeline(const Napi::CallbackInfo& info); + +struct Composite { + sharp::InputDescriptor *input; + VipsBlendMode mode; + int gravity; + int left; + int top; + bool hasOffset; + bool tile; + bool premultiplied; + + Composite(): + input(nullptr), + mode(VIPS_BLEND_MODE_OVER), + gravity(0), + left(0), + top(0), + hasOffset(false), + tile(false), + premultiplied(false) {} +}; + +struct PipelineBaton { + sharp::InputDescriptor *input; + std::string formatOut; + std::string fileOut; + void *bufferOut; + size_t bufferOutLength; + int pageHeightOut; + int pagesOut; + std::vector composite; + std::vector joinChannelIn; + int topOffsetPre; + int leftOffsetPre; + int widthPre; + int heightPre; + int topOffsetPost; + int leftOffsetPost; + int widthPost; + int heightPost; + int width; + int height; + int channels; + VipsKernel kernel; + sharp::Canvas canvas; + int position; + std::vector resizeBackground; + bool hasCropOffset; + int cropOffsetLeft; + int cropOffsetTop; + bool hasAttentionCenter; + int attentionX; + int attentionY; + bool premultiplied; + bool tileCentre; + bool fastShrinkOnLoad; + std::vector tint; + bool flatten; + std::vector flattenBackground; + bool unflatten; + bool negate; + bool negateAlpha; + double blurSigma; + VipsPrecision precision; + double minAmpl; + double brightness; + double saturation; + int hue; + double lightness; + int medianSize; + double sharpenSigma; + double sharpenM1; + double sharpenM2; + double sharpenX1; + double sharpenY2; + double sharpenY3; + int threshold; + bool thresholdGrayscale; + std::vector trimBackground; + double trimThreshold; + bool trimLineArt; + int trimOffsetLeft; + int trimOffsetTop; + std::vector linearA; + std::vector linearB; + double gamma; + double gammaOut; + bool greyscale; + bool normalise; + int normaliseLower; + int normaliseUpper; + int claheWidth; + int claheHeight; + int claheMaxSlope; + bool useExifOrientation; + int angle; + double rotationAngle; + std::vector rotationBackground; + bool rotateBeforePreExtract; + bool flip; + bool flop; + int extendTop; + int extendBottom; + int extendLeft; + int extendRight; + std::vector extendBackground; + VipsExtend extendWith; + bool withoutEnlargement; + bool withoutReduction; + std::vector affineMatrix; + std::vector affineBackground; + double affineIdx; + double affineIdy; + double affineOdx; + double affineOdy; + std::string affineInterpolator; + int jpegQuality; + bool jpegProgressive; + std::string jpegChromaSubsampling; + bool jpegTrellisQuantisation; + int jpegQuantisationTable; + bool jpegOvershootDeringing; + bool jpegOptimiseScans; + bool jpegOptimiseCoding; + bool pngProgressive; + int pngCompressionLevel; + bool pngAdaptiveFiltering; + bool pngPalette; + int pngQuality; + int pngEffort; + int pngBitdepth; + double pngDither; + int jp2Quality; + bool jp2Lossless; + int jp2TileHeight; + int jp2TileWidth; + std::string jp2ChromaSubsampling; + int webpQuality; + int webpAlphaQuality; + bool webpNearLossless; + bool webpLossless; + bool webpSmartSubsample; + VipsForeignWebpPreset webpPreset; + int webpEffort; + bool webpMinSize; + bool webpMixed; + int gifBitdepth; + int gifEffort; + double gifDither; + double gifInterFrameMaxError; + double gifInterPaletteMaxError; + bool gifReuse; + bool gifProgressive; + int tiffQuality; + VipsForeignTiffCompression tiffCompression; + VipsForeignTiffPredictor tiffPredictor; + bool tiffPyramid; + int tiffBitdepth; + bool tiffMiniswhite; + bool tiffTile; + int tiffTileHeight; + int tiffTileWidth; + double tiffXres; + double tiffYres; + VipsForeignTiffResunit tiffResolutionUnit; + int heifQuality; + VipsForeignHeifCompression heifCompression; + int heifEffort; + std::string heifChromaSubsampling; + bool heifLossless; + int heifBitdepth; + double jxlDistance; + int jxlDecodingTier; + int jxlEffort; + bool jxlLossless; + VipsBandFormat rawDepth; + std::string err; + int keepMetadata; + int withMetadataOrientation; + double withMetadataDensity; + std::string withIccProfile; + std::unordered_map withExif; + bool withExifMerge; + int timeoutSeconds; + std::vector convKernel; + int convKernelWidth; + int convKernelHeight; + double convKernelScale; + double convKernelOffset; + sharp::InputDescriptor *boolean; + VipsOperationBoolean booleanOp; + VipsOperationBoolean bandBoolOp; + int extractChannel; + bool removeAlpha; + double ensureAlpha; + VipsInterpretation colourspacePipeline; + VipsInterpretation colourspace; + std::vector delay; + int loop; + int tileSize; + int tileOverlap; + VipsForeignDzContainer tileContainer; + VipsForeignDzLayout tileLayout; + std::string tileFormat; + int tileAngle; + std::vector tileBackground; + int tileSkipBlanks; + VipsForeignDzDepth tileDepth; + std::string tileId; + std::string tileBasename; + std::vector recombMatrix; + + PipelineBaton(): + input(nullptr), + bufferOutLength(0), + pageHeightOut(0), + pagesOut(0), + topOffsetPre(-1), + topOffsetPost(-1), + channels(0), + kernel(VIPS_KERNEL_LANCZOS3), + canvas(sharp::Canvas::CROP), + position(0), + resizeBackground{ 0.0, 0.0, 0.0, 255.0 }, + hasCropOffset(false), + cropOffsetLeft(0), + cropOffsetTop(0), + hasAttentionCenter(false), + attentionX(0), + attentionY(0), + premultiplied(false), + tint{ -1.0, 0.0, 0.0, 0.0 }, + flatten(false), + flattenBackground{ 0.0, 0.0, 0.0 }, + unflatten(false), + negate(false), + negateAlpha(true), + blurSigma(0.0), + brightness(1.0), + saturation(1.0), + hue(0), + lightness(0), + medianSize(0), + sharpenSigma(0.0), + sharpenM1(1.0), + sharpenM2(2.0), + sharpenX1(2.0), + sharpenY2(10.0), + sharpenY3(20.0), + threshold(0), + thresholdGrayscale(true), + trimBackground{}, + trimThreshold(-1.0), + trimLineArt(false), + trimOffsetLeft(0), + trimOffsetTop(0), + linearA{}, + linearB{}, + gamma(0.0), + greyscale(false), + normalise(false), + normaliseLower(1), + normaliseUpper(99), + claheWidth(0), + claheHeight(0), + claheMaxSlope(3), + useExifOrientation(false), + angle(0), + rotationAngle(0.0), + rotationBackground{ 0.0, 0.0, 0.0, 255.0 }, + flip(false), + flop(false), + extendTop(0), + extendBottom(0), + extendLeft(0), + extendRight(0), + extendBackground{ 0.0, 0.0, 0.0, 255.0 }, + extendWith(VIPS_EXTEND_BACKGROUND), + withoutEnlargement(false), + withoutReduction(false), + affineMatrix{ 1.0, 0.0, 0.0, 1.0 }, + affineBackground{ 0.0, 0.0, 0.0, 255.0 }, + affineIdx(0), + affineIdy(0), + affineOdx(0), + affineOdy(0), + affineInterpolator("bicubic"), + jpegQuality(80), + jpegProgressive(false), + jpegChromaSubsampling("4:2:0"), + jpegTrellisQuantisation(false), + jpegQuantisationTable(0), + jpegOvershootDeringing(false), + jpegOptimiseScans(false), + jpegOptimiseCoding(true), + pngProgressive(false), + pngCompressionLevel(6), + pngAdaptiveFiltering(false), + pngPalette(false), + pngQuality(100), + pngEffort(7), + pngBitdepth(8), + pngDither(1.0), + jp2Quality(80), + jp2Lossless(false), + jp2TileHeight(512), + jp2TileWidth(512), + jp2ChromaSubsampling("4:4:4"), + webpQuality(80), + webpAlphaQuality(100), + webpNearLossless(false), + webpLossless(false), + webpSmartSubsample(false), + webpPreset(VIPS_FOREIGN_WEBP_PRESET_DEFAULT), + webpEffort(4), + webpMinSize(false), + webpMixed(false), + gifBitdepth(8), + gifEffort(7), + gifDither(1.0), + gifInterFrameMaxError(0.0), + gifInterPaletteMaxError(3.0), + gifReuse(true), + gifProgressive(false), + tiffQuality(80), + tiffCompression(VIPS_FOREIGN_TIFF_COMPRESSION_JPEG), + tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL), + tiffPyramid(false), + tiffBitdepth(8), + tiffMiniswhite(false), + tiffTile(false), + tiffTileHeight(256), + tiffTileWidth(256), + tiffXres(1.0), + tiffYres(1.0), + tiffResolutionUnit(VIPS_FOREIGN_TIFF_RESUNIT_INCH), + heifQuality(50), + heifCompression(VIPS_FOREIGN_HEIF_COMPRESSION_AV1), + heifEffort(4), + heifChromaSubsampling("4:4:4"), + heifLossless(false), + heifBitdepth(8), + jxlDistance(1.0), + jxlDecodingTier(0), + jxlEffort(7), + jxlLossless(false), + rawDepth(VIPS_FORMAT_UCHAR), + keepMetadata(0), + withMetadataOrientation(-1), + withMetadataDensity(0.0), + withExifMerge(true), + timeoutSeconds(0), + convKernelWidth(0), + convKernelHeight(0), + convKernelScale(0.0), + convKernelOffset(0.0), + boolean(nullptr), + booleanOp(VIPS_OPERATION_BOOLEAN_LAST), + bandBoolOp(VIPS_OPERATION_BOOLEAN_LAST), + extractChannel(-1), + removeAlpha(false), + ensureAlpha(-1.0), + colourspacePipeline(VIPS_INTERPRETATION_LAST), + colourspace(VIPS_INTERPRETATION_LAST), + loop(-1), + tileSize(256), + tileOverlap(0), + tileContainer(VIPS_FOREIGN_DZ_CONTAINER_FS), + tileLayout(VIPS_FOREIGN_DZ_LAYOUT_DZ), + tileAngle(0), + tileBackground{ 255.0, 255.0, 255.0, 255.0 }, + tileSkipBlanks(-1), + tileDepth(VIPS_FOREIGN_DZ_DEPTH_LAST) {} +}; + +#endif // SRC_PIPELINE_H_ diff --git a/node_modules/sharp/src/sharp.cc b/node_modules/sharp/src/sharp.cc new file mode 100644 index 0000000000000000000000000000000000000000..e017b2f35a755b79fccd881e97b89d0448583281 --- /dev/null +++ b/node_modules/sharp/src/sharp.cc @@ -0,0 +1,40 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include // NOLINT(build/c++11) + +#include +#include + +#include "common.h" +#include "metadata.h" +#include "pipeline.h" +#include "utilities.h" +#include "stats.h" + +Napi::Object init(Napi::Env env, Napi::Object exports) { + static std::once_flag sharp_vips_init_once; + std::call_once(sharp_vips_init_once, []() { + vips_init("sharp"); + }); + + g_log_set_handler("VIPS", static_cast(G_LOG_LEVEL_WARNING), + static_cast(sharp::VipsWarningCallback), nullptr); + + // Methods available to JavaScript + exports.Set("metadata", Napi::Function::New(env, metadata)); + exports.Set("pipeline", Napi::Function::New(env, pipeline)); + exports.Set("cache", Napi::Function::New(env, cache)); + exports.Set("concurrency", Napi::Function::New(env, concurrency)); + exports.Set("counters", Napi::Function::New(env, counters)); + exports.Set("simd", Napi::Function::New(env, simd)); + exports.Set("libvipsVersion", Napi::Function::New(env, libvipsVersion)); + exports.Set("format", Napi::Function::New(env, format)); + exports.Set("block", Napi::Function::New(env, block)); + exports.Set("_maxColourDistance", Napi::Function::New(env, _maxColourDistance)); + exports.Set("_isUsingJemalloc", Napi::Function::New(env, _isUsingJemalloc)); + exports.Set("stats", Napi::Function::New(env, stats)); + return exports; +} + +NODE_API_MODULE(sharp, init) diff --git a/node_modules/sharp/src/stats.cc b/node_modules/sharp/src/stats.cc new file mode 100644 index 0000000000000000000000000000000000000000..b06d3bb55fcaa0e585ea7e82134b60c77357807d --- /dev/null +++ b/node_modules/sharp/src/stats.cc @@ -0,0 +1,183 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include + +#include +#include + +#include "common.h" +#include "stats.h" + +class StatsWorker : public Napi::AsyncWorker { + public: + StatsWorker(Napi::Function callback, StatsBaton *baton, Napi::Function debuglog) : + Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {} + ~StatsWorker() {} + + const int STAT_MIN_INDEX = 0; + const int STAT_MAX_INDEX = 1; + const int STAT_SUM_INDEX = 2; + const int STAT_SQ_SUM_INDEX = 3; + const int STAT_MEAN_INDEX = 4; + const int STAT_STDEV_INDEX = 5; + const int STAT_MINX_INDEX = 6; + const int STAT_MINY_INDEX = 7; + const int STAT_MAXX_INDEX = 8; + const int STAT_MAXY_INDEX = 9; + + void Execute() { + // Decrement queued task counter + sharp::counterQueue--; + + vips::VImage image; + sharp::ImageType imageType = sharp::ImageType::UNKNOWN; + try { + std::tie(image, imageType) = OpenInput(baton->input); + } catch (vips::VError const &err) { + (baton->err).append(err.what()); + } + if (imageType != sharp::ImageType::UNKNOWN) { + try { + vips::VImage stats = image.stats(); + int const bands = image.bands(); + for (int b = 1; b <= bands; b++) { + ChannelStats cStats( + static_cast(stats.getpoint(STAT_MIN_INDEX, b).front()), + static_cast(stats.getpoint(STAT_MAX_INDEX, b).front()), + stats.getpoint(STAT_SUM_INDEX, b).front(), + stats.getpoint(STAT_SQ_SUM_INDEX, b).front(), + stats.getpoint(STAT_MEAN_INDEX, b).front(), + stats.getpoint(STAT_STDEV_INDEX, b).front(), + static_cast(stats.getpoint(STAT_MINX_INDEX, b).front()), + static_cast(stats.getpoint(STAT_MINY_INDEX, b).front()), + static_cast(stats.getpoint(STAT_MAXX_INDEX, b).front()), + static_cast(stats.getpoint(STAT_MAXY_INDEX, b).front())); + baton->channelStats.push_back(cStats); + } + // Image is not opaque when alpha layer is present and contains a non-mamixa value + if (sharp::HasAlpha(image)) { + double const minAlpha = static_cast(stats.getpoint(STAT_MIN_INDEX, bands).front()); + if (minAlpha != sharp::MaximumImageAlpha(image.interpretation())) { + baton->isOpaque = false; + } + } + // Convert to greyscale + vips::VImage greyscale = image.colourspace(VIPS_INTERPRETATION_B_W)[0]; + // Estimate entropy via histogram of greyscale value frequency + baton->entropy = std::abs(greyscale.hist_find().hist_entropy()); + // Estimate sharpness via standard deviation of greyscale laplacian + if (image.width() > 1 || image.height() > 1) { + VImage laplacian = VImage::new_matrixv(3, 3, + 0.0, 1.0, 0.0, + 1.0, -4.0, 1.0, + 0.0, 1.0, 0.0); + laplacian.set("scale", 9.0); + baton->sharpness = greyscale.conv(laplacian).deviate(); + } + // Most dominant sRGB colour via 4096-bin 3D histogram + vips::VImage hist = sharp::RemoveAlpha(image) + .colourspace(VIPS_INTERPRETATION_sRGB) + .hist_find_ndim(VImage::option()->set("bins", 16)); + std::complex maxpos = hist.maxpos(); + int const dx = static_cast(std::real(maxpos)); + int const dy = static_cast(std::imag(maxpos)); + std::vector pel = hist(dx, dy); + int const dz = std::distance(pel.begin(), std::find(pel.begin(), pel.end(), hist.max())); + baton->dominantRed = dx * 16 + 8; + baton->dominantGreen = dy * 16 + 8; + baton->dominantBlue = dz * 16 + 8; + } catch (vips::VError const &err) { + (baton->err).append(err.what()); + } + } + + // Clean up + vips_error_clear(); + vips_thread_shutdown(); + } + + void OnOK() { + Napi::Env env = Env(); + Napi::HandleScope scope(env); + + // Handle warnings + std::string warning = sharp::VipsWarningPop(); + while (!warning.empty()) { + debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) }); + warning = sharp::VipsWarningPop(); + } + + if (baton->err.empty()) { + // Stats Object + Napi::Object info = Napi::Object::New(env); + Napi::Array channels = Napi::Array::New(env); + + std::vector::iterator it; + int i = 0; + for (it = baton->channelStats.begin(); it < baton->channelStats.end(); it++, i++) { + Napi::Object channelStat = Napi::Object::New(env); + channelStat.Set("min", it->min); + channelStat.Set("max", it->max); + channelStat.Set("sum", it->sum); + channelStat.Set("squaresSum", it->squaresSum); + channelStat.Set("mean", it->mean); + channelStat.Set("stdev", it->stdev); + channelStat.Set("minX", it->minX); + channelStat.Set("minY", it->minY); + channelStat.Set("maxX", it->maxX); + channelStat.Set("maxY", it->maxY); + channels.Set(i, channelStat); + } + + info.Set("channels", channels); + info.Set("isOpaque", baton->isOpaque); + info.Set("entropy", baton->entropy); + info.Set("sharpness", baton->sharpness); + Napi::Object dominant = Napi::Object::New(env); + dominant.Set("r", baton->dominantRed); + dominant.Set("g", baton->dominantGreen); + dominant.Set("b", baton->dominantBlue); + info.Set("dominant", dominant); + Callback().Call(Receiver().Value(), { env.Null(), info }); + } else { + Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() }); + } + + delete baton->input; + delete baton; + } + + private: + StatsBaton* baton; + Napi::FunctionReference debuglog; +}; + +/* + stats(options, callback) +*/ +Napi::Value stats(const Napi::CallbackInfo& info) { + // V8 objects are converted to non-V8 types held in the baton struct + StatsBaton *baton = new StatsBaton; + Napi::Object options = info[size_t(0)].As(); + + // Input + baton->input = sharp::CreateInputDescriptor(options.Get("input").As()); + baton->input->access = VIPS_ACCESS_RANDOM; + + // Function to notify of libvips warnings + Napi::Function debuglog = options.Get("debuglog").As(); + + // Join queue for worker thread + Napi::Function callback = info[size_t(1)].As(); + StatsWorker *worker = new StatsWorker(callback, baton, debuglog); + worker->Receiver().Set("options", options); + worker->Queue(); + + // Increment queued task counter + sharp::counterQueue++; + + return info.Env().Undefined(); +} diff --git a/node_modules/sharp/src/stats.h b/node_modules/sharp/src/stats.h new file mode 100644 index 0000000000000000000000000000000000000000..c80e65fa88b8102758bc3566a40e89c6326f4109 --- /dev/null +++ b/node_modules/sharp/src/stats.h @@ -0,0 +1,59 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_STATS_H_ +#define SRC_STATS_H_ + +#include +#include + +#include "./common.h" + +struct ChannelStats { + // stats per channel + int min; + int max; + double sum; + double squaresSum; + double mean; + double stdev; + int minX; + int minY; + int maxX; + int maxY; + + ChannelStats(int minVal, int maxVal, double sumVal, double squaresSumVal, + double meanVal, double stdevVal, int minXVal, int minYVal, int maxXVal, int maxYVal): + min(minVal), max(maxVal), sum(sumVal), squaresSum(squaresSumVal), + mean(meanVal), stdev(stdevVal), minX(minXVal), minY(minYVal), maxX(maxXVal), maxY(maxYVal) {} +}; + +struct StatsBaton { + // Input + sharp::InputDescriptor *input; + + // Output + std::vector channelStats; + bool isOpaque; + double entropy; + double sharpness; + int dominantRed; + int dominantGreen; + int dominantBlue; + + std::string err; + + StatsBaton(): + input(nullptr), + isOpaque(true), + entropy(0.0), + sharpness(0.0), + dominantRed(0), + dominantGreen(0), + dominantBlue(0) + {} +}; + +Napi::Value stats(const Napi::CallbackInfo& info); + +#endif // SRC_STATS_H_ diff --git a/node_modules/sharp/src/utilities.cc b/node_modules/sharp/src/utilities.cc new file mode 100644 index 0000000000000000000000000000000000000000..070374048dd49ed36a5ecedd843a3ee9c6658249 --- /dev/null +++ b/node_modules/sharp/src/utilities.cc @@ -0,0 +1,269 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include + +#include +#include +#include + +#include "common.h" +#include "operations.h" +#include "utilities.h" + +/* + Get and set cache limits +*/ +Napi::Value cache(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + + // Set memory limit + if (info[size_t(0)].IsNumber()) { + vips_cache_set_max_mem(info[size_t(0)].As().Int32Value() * 1048576); + } + // Set file limit + if (info[size_t(1)].IsNumber()) { + vips_cache_set_max_files(info[size_t(1)].As().Int32Value()); + } + // Set items limit + if (info[size_t(2)].IsNumber()) { + vips_cache_set_max(info[size_t(2)].As().Int32Value()); + } + + // Get memory stats + Napi::Object memory = Napi::Object::New(env); + memory.Set("current", round(vips_tracked_get_mem() / 1048576)); + memory.Set("high", round(vips_tracked_get_mem_highwater() / 1048576)); + memory.Set("max", round(vips_cache_get_max_mem() / 1048576)); + // Get file stats + Napi::Object files = Napi::Object::New(env); + files.Set("current", vips_tracked_get_files()); + files.Set("max", vips_cache_get_max_files()); + + // Get item stats + Napi::Object items = Napi::Object::New(env); + items.Set("current", vips_cache_get_size()); + items.Set("max", vips_cache_get_max()); + + Napi::Object cache = Napi::Object::New(env); + cache.Set("memory", memory); + cache.Set("files", files); + cache.Set("items", items); + return cache; +} + +/* + Get and set size of thread pool +*/ +Napi::Value concurrency(const Napi::CallbackInfo& info) { + // Set concurrency + if (info[size_t(0)].IsNumber()) { + vips_concurrency_set(info[size_t(0)].As().Int32Value()); + } + // Get concurrency + return Napi::Number::New(info.Env(), vips_concurrency_get()); +} + +/* + Get internal counters (queued tasks, processing tasks) +*/ +Napi::Value counters(const Napi::CallbackInfo& info) { + Napi::Object counters = Napi::Object::New(info.Env()); + counters.Set("queue", static_cast(sharp::counterQueue)); + counters.Set("process", static_cast(sharp::counterProcess)); + return counters; +} + +/* + Get and set use of SIMD vector unit instructions +*/ +Napi::Value simd(const Napi::CallbackInfo& info) { + // Set state + if (info[size_t(0)].IsBoolean()) { + vips_vector_set_enabled(info[size_t(0)].As().Value()); + } + // Get state + return Napi::Boolean::New(info.Env(), vips_vector_isenabled()); +} + +/* + Get libvips version +*/ +Napi::Value libvipsVersion(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + Napi::Object version = Napi::Object::New(env); + + char semver[9]; + std::snprintf(semver, sizeof(semver), "%d.%d.%d", vips_version(0), vips_version(1), vips_version(2)); + version.Set("semver", Napi::String::New(env, semver)); +#ifdef SHARP_USE_GLOBAL_LIBVIPS + version.Set("isGlobal", Napi::Boolean::New(env, true)); +#else + version.Set("isGlobal", Napi::Boolean::New(env, false)); +#endif +#ifdef __EMSCRIPTEN__ + version.Set("isWasm", Napi::Boolean::New(env, true)); +#else + version.Set("isWasm", Napi::Boolean::New(env, false)); +#endif + return version; +} + +/* + Get available input/output file/buffer/stream formats +*/ +Napi::Value format(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + Napi::Object format = Napi::Object::New(env); + for (std::string const f : { + "jpeg", "png", "webp", "tiff", "magick", "openslide", "dz", + "ppm", "fits", "gif", "svg", "heif", "pdf", "vips", "jp2k", "jxl" + }) { + // Input + const VipsObjectClass *oc = vips_class_find("VipsOperation", (f + "load").c_str()); + Napi::Boolean hasInputFile = Napi::Boolean::New(env, oc); + Napi::Boolean hasInputBuffer = + Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "load_buffer").c_str())); + Napi::Object input = Napi::Object::New(env); + input.Set("file", hasInputFile); + input.Set("buffer", hasInputBuffer); + input.Set("stream", hasInputBuffer); + if (hasInputFile) { + const VipsForeignClass *fc = VIPS_FOREIGN_CLASS(oc); + if (fc->suffs) { + Napi::Array fileSuffix = Napi::Array::New(env); + const char **suffix = fc->suffs; + for (int i = 0; *suffix; i++, suffix++) { + fileSuffix.Set(i, Napi::String::New(env, *suffix)); + } + input.Set("fileSuffix", fileSuffix); + } + } + // Output + Napi::Boolean hasOutputFile = + Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "save").c_str())); + Napi::Boolean hasOutputBuffer = + Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "save_buffer").c_str())); + Napi::Object output = Napi::Object::New(env); + output.Set("file", hasOutputFile); + output.Set("buffer", hasOutputBuffer); + output.Set("stream", hasOutputBuffer); + // Other attributes + Napi::Object container = Napi::Object::New(env); + container.Set("id", f); + container.Set("input", input); + container.Set("output", output); + // Add to set of formats + format.Set(f, container); + } + + // Raw, uncompressed data + Napi::Boolean supported = Napi::Boolean::New(env, true); + Napi::Boolean unsupported = Napi::Boolean::New(env, false); + Napi::Object rawInput = Napi::Object::New(env); + rawInput.Set("file", unsupported); + rawInput.Set("buffer", supported); + rawInput.Set("stream", supported); + Napi::Object rawOutput = Napi::Object::New(env); + rawOutput.Set("file", unsupported); + rawOutput.Set("buffer", supported); + rawOutput.Set("stream", supported); + Napi::Object raw = Napi::Object::New(env); + raw.Set("id", "raw"); + raw.Set("input", rawInput); + raw.Set("output", rawOutput); + format.Set("raw", raw); + + return format; +} + +/* + (Un)block libvips operations at runtime. +*/ +void block(const Napi::CallbackInfo& info) { + Napi::Array ops = info[size_t(0)].As(); + bool const state = info[size_t(1)].As().Value(); + for (unsigned int i = 0; i < ops.Length(); i++) { + vips_operation_block_set(ops.Get(i).As().Utf8Value().c_str(), state); + } +} + +/* + Synchronous, internal-only method used by some of the functional tests. + Calculates the maximum colour distance using the DE2000 algorithm + between two images of the same dimensions and number of channels. +*/ +Napi::Value _maxColourDistance(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + + // Open input files + VImage image1; + sharp::ImageType imageType1 = sharp::DetermineImageType(info[size_t(0)].As().Utf8Value().data()); + if (imageType1 != sharp::ImageType::UNKNOWN) { + try { + image1 = VImage::new_from_file(info[size_t(0)].As().Utf8Value().c_str()); + } catch (...) { + throw Napi::Error::New(env, "Input file 1 has corrupt header"); + } + } else { + throw Napi::Error::New(env, "Input file 1 is of an unsupported image format"); + } + VImage image2; + sharp::ImageType imageType2 = sharp::DetermineImageType(info[size_t(1)].As().Utf8Value().data()); + if (imageType2 != sharp::ImageType::UNKNOWN) { + try { + image2 = VImage::new_from_file(info[size_t(1)].As().Utf8Value().c_str()); + } catch (...) { + throw Napi::Error::New(env, "Input file 2 has corrupt header"); + } + } else { + throw Napi::Error::New(env, "Input file 2 is of an unsupported image format"); + } + // Ensure same number of channels + if (image1.bands() != image2.bands()) { + throw Napi::Error::New(env, "mismatchedBands"); + } + // Ensure same dimensions + if (image1.width() != image2.width() || image1.height() != image2.height()) { + throw Napi::Error::New(env, "mismatchedDimensions"); + } + + double maxColourDistance; + try { + // Premultiply and remove alpha + if (sharp::HasAlpha(image1)) { + image1 = image1.premultiply().extract_band(1, VImage::option()->set("n", image1.bands() - 1)); + } + if (sharp::HasAlpha(image2)) { + image2 = image2.premultiply().extract_band(1, VImage::option()->set("n", image2.bands() - 1)); + } + // Calculate colour distance + maxColourDistance = image1.dE00(image2).max(); + } catch (vips::VError const &err) { + throw Napi::Error::New(env, err.what()); + } + + // Clean up libvips' per-request data and threads + vips_error_clear(); + vips_thread_shutdown(); + + return Napi::Number::New(env, maxColourDistance); +} + +#if defined(__GNUC__) +// mallctl will be resolved by the runtime linker when jemalloc is being used +extern "C" { + int mallctl(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen) __attribute__((weak)); +} +Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + return Napi::Boolean::New(env, mallctl != nullptr); +} +#else +Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + return Napi::Boolean::New(env, false); +} +#endif diff --git a/node_modules/sharp/src/utilities.h b/node_modules/sharp/src/utilities.h new file mode 100644 index 0000000000000000000000000000000000000000..0f499ad397e12fdaae12c08bcbfd44163b8f6d63 --- /dev/null +++ b/node_modules/sharp/src/utilities.h @@ -0,0 +1,19 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_UTILITIES_H_ +#define SRC_UTILITIES_H_ + +#include + +Napi::Value cache(const Napi::CallbackInfo& info); +Napi::Value concurrency(const Napi::CallbackInfo& info); +Napi::Value counters(const Napi::CallbackInfo& info); +Napi::Value simd(const Napi::CallbackInfo& info); +Napi::Value libvipsVersion(const Napi::CallbackInfo& info); +Napi::Value format(const Napi::CallbackInfo& info); +void block(const Napi::CallbackInfo& info); +Napi::Value _maxColourDistance(const Napi::CallbackInfo& info); +Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info); + +#endif // SRC_UTILITIES_H_ diff --git a/node_modules/shebang-command/index.js b/node_modules/shebang-command/index.js new file mode 100644 index 0000000000000000000000000000000000000000..f35db30851c777b62df472eae9fb8e1e658b2095 --- /dev/null +++ b/node_modules/shebang-command/index.js @@ -0,0 +1,19 @@ +'use strict'; +const shebangRegex = require('shebang-regex'); + +module.exports = (string = '') => { + const match = string.match(shebangRegex); + + if (!match) { + return null; + } + + const [path, argument] = match[0].replace(/#! ?/, '').split(' '); + const binary = path.split('/').pop(); + + if (binary === 'env') { + return argument; + } + + return argument ? `${binary} ${argument}` : binary; +}; diff --git a/node_modules/shebang-command/license b/node_modules/shebang-command/license new file mode 100644 index 0000000000000000000000000000000000000000..db6bc32cc7c44e86102035b2fb75ba8d05123f3f --- /dev/null +++ b/node_modules/shebang-command/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Kevin Mårtensson (github.com/kevva) + +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. diff --git a/node_modules/shebang-command/package.json b/node_modules/shebang-command/package.json new file mode 100644 index 0000000000000000000000000000000000000000..18e3c04638cb6825284a0e0fa6ff81997db8fc42 --- /dev/null +++ b/node_modules/shebang-command/package.json @@ -0,0 +1,34 @@ +{ + "name": "shebang-command", + "version": "2.0.0", + "description": "Get the command from a shebang", + "license": "MIT", + "repository": "kevva/shebang-command", + "author": { + "name": "Kevin Mårtensson", + "email": "kevinmartensson@gmail.com", + "url": "github.com/kevva" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "cmd", + "command", + "parse", + "shebang" + ], + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "devDependencies": { + "ava": "^2.3.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/shebang-command/readme.md b/node_modules/shebang-command/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..84feb442d746f32b40f258c7efd7aad92cb23a15 --- /dev/null +++ b/node_modules/shebang-command/readme.md @@ -0,0 +1,34 @@ +# shebang-command [![Build Status](https://travis-ci.org/kevva/shebang-command.svg?branch=master)](https://travis-ci.org/kevva/shebang-command) + +> Get the command from a shebang + + +## Install + +``` +$ npm install shebang-command +``` + + +## Usage + +```js +const shebangCommand = require('shebang-command'); + +shebangCommand('#!/usr/bin/env node'); +//=> 'node' + +shebangCommand('#!/bin/bash'); +//=> 'bash' +``` + + +## API + +### shebangCommand(string) + +#### string + +Type: `string` + +String containing a shebang. diff --git a/node_modules/shebang-regex/index.d.ts b/node_modules/shebang-regex/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..61d034b31eb8fc9baf1eda2bfbf804cb0a47ec1f --- /dev/null +++ b/node_modules/shebang-regex/index.d.ts @@ -0,0 +1,22 @@ +/** +Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line. + +@example +``` +import shebangRegex = require('shebang-regex'); + +const string = '#!/usr/bin/env node\nconsole.log("unicorns");'; + +shebangRegex.test(string); +//=> true + +shebangRegex.exec(string)[0]; +//=> '#!/usr/bin/env node' + +shebangRegex.exec(string)[1]; +//=> '/usr/bin/env node' +``` +*/ +declare const shebangRegex: RegExp; + +export = shebangRegex; diff --git a/node_modules/shebang-regex/index.js b/node_modules/shebang-regex/index.js new file mode 100644 index 0000000000000000000000000000000000000000..63fc4a0b678909ba66c6dac127a64b0836bbd67d --- /dev/null +++ b/node_modules/shebang-regex/index.js @@ -0,0 +1,2 @@ +'use strict'; +module.exports = /^#!(.*)/; diff --git a/node_modules/shebang-regex/license b/node_modules/shebang-regex/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/node_modules/shebang-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/shebang-regex/package.json b/node_modules/shebang-regex/package.json new file mode 100644 index 0000000000000000000000000000000000000000..00ab30feeefe8968eda2be6808633384dc74cc46 --- /dev/null +++ b/node_modules/shebang-regex/package.json @@ -0,0 +1,35 @@ +{ + "name": "shebang-regex", + "version": "3.0.0", + "description": "Regular expression for matching a shebang line", + "license": "MIT", + "repository": "sindresorhus/shebang-regex", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "regex", + "regexp", + "shebang", + "match", + "test", + "line" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/shebang-regex/readme.md b/node_modules/shebang-regex/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..5ecf863aa35ab36852cfe6be6d78ccc9be546113 --- /dev/null +++ b/node_modules/shebang-regex/readme.md @@ -0,0 +1,33 @@ +# shebang-regex [![Build Status](https://travis-ci.org/sindresorhus/shebang-regex.svg?branch=master)](https://travis-ci.org/sindresorhus/shebang-regex) + +> Regular expression for matching a [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) line + + +## Install + +``` +$ npm install shebang-regex +``` + + +## Usage + +```js +const shebangRegex = require('shebang-regex'); + +const string = '#!/usr/bin/env node\nconsole.log("unicorns");'; + +shebangRegex.test(string); +//=> true + +shebangRegex.exec(string)[0]; +//=> '#!/usr/bin/env node' + +shebangRegex.exec(string)[1]; +//=> '/usr/bin/env node' +``` + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/shell-quote/.eslintrc b/node_modules/shell-quote/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..9569d518cba617a7f224a7196993bbf3eceb792e --- /dev/null +++ b/node_modules/shell-quote/.eslintrc @@ -0,0 +1,30 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "array-bracket-newline": 0, + "complexity": 0, + "eqeqeq": 1, + "func-style": [2, "declaration"], + "max-depth": 0, + "max-lines-per-function": 0, + "max-statements": 0, + "multiline-comment-style": 0, + "no-negated-condition": 1, + "no-param-reassign": 1, + "no-lonely-if": 1, + "no-shadow": 1, + "no-template-curly-in-string": 0, + }, + + "overrides": [ + { + "files": "example/**", + "rules": { + "no-console": 0, + }, + }, + ], +} diff --git a/node_modules/shell-quote/.github/FUNDING.yml b/node_modules/shell-quote/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..0b6b6b4d55a3876505ae27838dccf6f7f11a0a7b --- /dev/null +++ b/node_modules/shell-quote/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/shell-quote +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/shell-quote/.nycrc b/node_modules/shell-quote/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..55c3d29367a4216abea3dc5eaa48b59826da355b --- /dev/null +++ b/node_modules/shell-quote/.nycrc @@ -0,0 +1,14 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "example", + "test" + ] +} diff --git a/node_modules/shell-quote/LICENSE b/node_modules/shell-quote/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3d59c73309d3312d7acbce16b11b1664f8118712 --- /dev/null +++ b/node_modules/shell-quote/LICENSE @@ -0,0 +1,24 @@ +The MIT License + +Copyright (c) 2013 James Halliday (mail@substack.net) + +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. \ No newline at end of file diff --git a/node_modules/shell-quote/README.md b/node_modules/shell-quote/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f8db0c8cf5abb3e8d6edb7e165942d6396eb9c3a --- /dev/null +++ b/node_modules/shell-quote/README.md @@ -0,0 +1,168 @@ +# shell-quote [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Parse and quote shell commands. + +# example + +## quote + +``` js +var quote = require('shell-quote/quote'); +var s = quote([ 'a', 'b c d', '$f', '"g"' ]); +console.log(s); +``` + +output + +``` +a 'b c d' \$f '"g"' +``` + +## parse + +``` js +var parse = require('shell-quote/parse'); +var xs = parse('a "b c" \\$def \'it\\\'s great\''); +console.dir(xs); +``` + +output + +``` +[ 'a', 'b c', '\\$def', 'it\'s great' ] +``` + +## parse with an environment variable + +``` js +var parse = require('shell-quote/parse'); +var xs = parse('beep --boop="$PWD"', { PWD: '/home/robot' }); +console.dir(xs); +``` + +output + +``` +[ 'beep', '--boop=/home/robot' ] +``` + +## parse with custom escape character + +``` js +var parse = require('shell-quote/parse'); +var xs = parse('beep ^--boop="$PWD"', { PWD: '/home/robot' }, { escape: '^' }); +console.dir(xs); +``` + +output + +``` +[ 'beep --boop=/home/robot' ] +``` + +## parsing shell operators + +``` js +var parse = require('shell-quote/parse'); +var xs = parse('beep || boop > /byte'); +console.dir(xs); +``` + +output: + +``` +[ 'beep', { op: '||' }, 'boop', { op: '>' }, '/byte' ] +``` + +## parsing shell comment + +``` js +var parse = require('shell-quote/parse'); +var xs = parse('beep > boop # > kaboom'); +console.dir(xs); +``` + +output: + +``` +[ 'beep', { op: '>' }, 'boop', { comment: '> kaboom' } ] +``` + +# methods + +``` js +var quote = require('shell-quote/quote'); +var parse = require('shell-quote/parse'); +``` + +## quote(args) + +Return a quoted string for the array `args` suitable for using in shell +commands. + +Each entry of `args` may be a string, or one of the object shapes that +`parse` emits: `{ op }` (where `op` is one of the control operators +`||`, `&&`, `;;`, `|&`, `<(`, `<<<`, `>>`, `>&`, `<&`, `&`, `;`, `(`, +`)`, `|`, `<`, `>`), `{ op: 'glob', pattern }`, or `{ comment }`. Any +other object shape, an unrecognized `op`, or a `pattern`/`comment` +containing line terminators throws a `TypeError`. + +## parse(cmd, env={}) + +Return an array of arguments from the quoted string `cmd`. + +Interpolate embedded bash-style `$VARNAME` and `${VARNAME}` variables with +the `env` object which like bash will replace undefined variables with `""`. + +`env` is usually an object but it can also be a function to perform lookups. +When `env(key)` returns a string, its result will be output just like `env[key]` +would. When `env(key)` returns an object, it will be inserted into the result +array like the operator objects. + +When a bash operator is encountered, the element in the array with be an object +with an `"op"` key set to the operator string. For example: + +``` +'beep || boop > /byte' +``` + +parses as: + +``` +[ 'beep', { op: '||' }, 'boop', { op: '>' }, '/byte' ] +``` + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install shell-quote +``` + +# license + +MIT + +[package-url]: https://npmjs.org/package/shell-quote +[npm-version-svg]: https://versionbadg.es/ljharb/shell-quote.svg +[deps-svg]: https://david-dm.org/ljharb/shell-quote.svg +[deps-url]: https://david-dm.org/ljharb/shell-quote +[dev-deps-svg]: https://david-dm.org/ljharb/shell-quote/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/shell-quote#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/shell-quote.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/shell-quote.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/shell-quote.svg +[downloads-url]: https://npm-stat.com/charts.html?package=shell-quote +[codecov-image]: https://codecov.io/gh/ljharb/shell-quote/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/shell-quote/ +[actions-image]: https://img.shields.io/github/check-runs/ljharb/shell-quote/main +[actions-url]: https://github.com/ljharb/shell-quote/actions diff --git a/node_modules/shell-quote/index.js b/node_modules/shell-quote/index.js new file mode 100644 index 0000000000000000000000000000000000000000..28fb42d258b775513b1ab63f76c88874ee9b490b --- /dev/null +++ b/node_modules/shell-quote/index.js @@ -0,0 +1,4 @@ +'use strict'; + +exports.quote = require('./quote'); +exports.parse = require('./parse'); diff --git a/node_modules/shell-quote/package.json b/node_modules/shell-quote/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2bc486dda82ec0adb1a3d8cf23ec8b12d2b448b9 --- /dev/null +++ b/node_modules/shell-quote/package.json @@ -0,0 +1,71 @@ +{ + "name": "shell-quote", + "description": "quote and parse shell commands", + "version": "1.8.4", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "bugs": "https://github.com/ljharb/shell-quote/issues", + "devDependencies": { + "@ljharb/eslint-config": "^22.2.3", + "auto-changelog": "^2.5.1", + "eslint": "^8.57.1", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "jackspeak": "=2.1.1", + "npmignore": "^0.3.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0" + }, + "homepage": "https://github.com/ljharb/shell-quote", + "keywords": [ + "command", + "parse", + "quote", + "shell" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "http://github.com/ljharb/shell-quote.git" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint --ext=js,mjs .", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true, + "startingVersion": "1.7.4" + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "example", + "CHANGELOG.md" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/shell-quote/parse.js b/node_modules/shell-quote/parse.js new file mode 100644 index 0000000000000000000000000000000000000000..71d2eea42fef36b9a89834db5bb50db66e664282 --- /dev/null +++ b/node_modules/shell-quote/parse.js @@ -0,0 +1,226 @@ +'use strict'; + +// '<(' is process substitution operator and +// can be parsed the same as control operator +var CONTROL = '(?:' + [ + '\\|\\|', + '\\&\\&', + ';;', + '\\|\\&', + '\\<\\(', + '\\<\\<\\<', + '>>', + '>\\&', + '<\\&', + '[&;()|<>]' +].join('|') + ')'; +var controlRE = new RegExp('^' + CONTROL + '$'); +var META = '|&;()<> \\t'; +var SINGLE_QUOTE = '"((\\\\"|[^"])*?)"'; +var DOUBLE_QUOTE = '\'((\\\\\'|[^\'])*?)\''; +var hash = /^#$/; + +var SQ = "'"; +var DQ = '"'; +var DS = '$'; + +var TOKEN = ''; +var mult = 0x100000000; // Math.pow(16, 8); +for (var i = 0; i < 4; i++) { + TOKEN += (mult * Math.random()).toString(16); +} +var startsWithToken = new RegExp('^' + TOKEN); + +function matchAll(s, r) { + var origIndex = r.lastIndex; + + var matches = []; + var matchObj; + + while ((matchObj = r.exec(s))) { + matches.push(matchObj); + if (r.lastIndex === matchObj.index) { + r.lastIndex += 1; + } + } + + r.lastIndex = origIndex; + + return matches; +} + +function getVar(env, pre, key) { + var r = typeof env === 'function' ? env(key) : env[key]; + if (typeof r === 'undefined' && key != '') { + r = ''; + } else if (typeof r === 'undefined') { + r = '$'; + } + + if (typeof r === 'object') { + return pre + TOKEN + JSON.stringify(r) + TOKEN; + } + return pre + r; +} + +function parseInternal(string, env, opts) { + if (!opts) { + opts = {}; + } + var BS = opts.escape || '\\'; + var BAREWORD = '(\\' + BS + '[\'"' + META + ']|[^\\s\'"' + META + '])+'; + + var chunker = new RegExp([ + '(' + CONTROL + ')', // control chars + '(' + BAREWORD + '|' + SINGLE_QUOTE + '|' + DOUBLE_QUOTE + ')+' + ].join('|'), 'g'); + + var matches = matchAll(string, chunker); + + if (matches.length === 0) { + return []; + } + if (!env) { + env = {}; + } + + var commented = false; + + return matches.map(function (match) { + var s = match[0]; + if (!s || commented) { + return void undefined; + } + if (controlRE.test(s)) { + return { op: s }; + } + + // Hand-written scanner/parser for Bash quoting rules: + // + // 1. inside single quotes, all characters are printed literally. + // 2. inside double quotes, all characters are printed literally + // except variables prefixed by '$' and backslashes followed by + // either a double quote or another backslash. + // 3. outside of any quotes, backslashes are treated as escape + // characters and not printed (unless they are themselves escaped) + // 4. quote context can switch mid-token if there is no whitespace + // between the two quote contexts (e.g. all'one'"token" parses as + // "allonetoken") + var quote = false; + var esc = false; + var out = ''; + var isGlob = false; + var i; + + function parseEnvVar() { + i += 1; + var varend; + var varname; + var char = s.charAt(i); + + if (char === '{') { + i += 1; + if (s.charAt(i) === '}') { + throw new Error('Bad substitution: ' + s.slice(i - 2, i + 1)); + } + varend = s.indexOf('}', i); + if (varend < 0) { + throw new Error('Bad substitution: ' + s.slice(i)); + } + varname = s.slice(i, varend); + i = varend; + } else if ((/[*@#?$!_-]/).test(char)) { + varname = char; + i += 1; + } else { + var slicedFromI = s.slice(i); + varend = slicedFromI.match(/[^\w\d_]/); + if (!varend) { + varname = slicedFromI; + i = s.length; + } else { + varname = slicedFromI.slice(0, varend.index); + i += varend.index - 1; + } + } + return getVar(env, '', varname); + } + + for (i = 0; i < s.length; i++) { + var c = s.charAt(i); + isGlob = isGlob || (!quote && (c === '*' || c === '?')); + if (esc) { + out += c; + esc = false; + } else if (quote) { + if (c === quote) { + quote = false; + } else if (quote == SQ) { + out += c; + } else { // Double quote + if (c === BS) { + i += 1; + c = s.charAt(i); + if (c === DQ || c === BS || c === DS) { + out += c; + } else { + out += BS + c; + } + } else if (c === DS) { + out += parseEnvVar(); + } else { + out += c; + } + } + } else if (c === DQ || c === SQ) { + quote = c; + } else if (controlRE.test(c)) { + return { op: s }; + } else if (hash.test(c)) { + commented = true; + var commentObj = { comment: string.slice(match.index + i + 1) }; + if (out.length) { + return [out, commentObj]; + } + return [commentObj]; + } else if (c === BS) { + esc = true; + } else if (c === DS) { + out += parseEnvVar(); + } else { + out += c; + } + } + + if (isGlob) { + return { op: 'glob', pattern: out }; + } + + return out; + }).reduce(function (prev, arg) { // finalize parsed arguments + // TODO: replace this whole reduce with a concat + return typeof arg === 'undefined' ? prev : prev.concat(arg); + }, []); +} + +module.exports = function parse(s, env, opts) { + var mapped = parseInternal(s, env, opts); + if (typeof env !== 'function') { + return mapped; + } + return mapped.reduce(function (acc, s) { + if (typeof s === 'object') { + return acc.concat(s); + } + var xs = s.split(RegExp('(' + TOKEN + '.*?' + TOKEN + ')', 'g')); + if (xs.length === 1) { + return acc.concat(xs[0]); + } + return acc.concat(xs.filter(Boolean).map(function (x) { + if (startsWithToken.test(x)) { + return JSON.parse(x.split(TOKEN)[1]); + } + return x; + })); + }, []); +}; diff --git a/node_modules/shell-quote/quote.js b/node_modules/shell-quote/quote.js new file mode 100644 index 0000000000000000000000000000000000000000..1262eb2640c4b6fdce9f85a04fd329f9ab94aa33 --- /dev/null +++ b/node_modules/shell-quote/quote.js @@ -0,0 +1,61 @@ +'use strict'; + +var OPS = [ + '||', + '&&', + ';;', + '|&', + '<(', + '<<<', + '>>', + '>&', + '<&', + '&', + ';', + '(', + ')', + '|', + '<', + '>' +]; +var LINE_TERMINATORS = /[\n\r\u2028\u2029]/; +var GLOB_SHELL_SPECIAL = /[\s#!"$&'():;<=>@\\^`|]/g; + +module.exports = function quote(xs) { + return xs.map(function (s) { + if (s === '') { + return '\'\''; + } + if (s && typeof s === 'object') { + if (s.op === 'glob') { + if (typeof s.pattern !== 'string') { + throw new TypeError('glob token requires a string `pattern`'); + } + if (LINE_TERMINATORS.test(s.pattern)) { + throw new TypeError('glob `pattern` must not contain line terminators'); + } + return s.pattern.replace(GLOB_SHELL_SPECIAL, '\\$&'); + } + if (typeof s.op === 'string') { + if (OPS.indexOf(s.op) < 0) { + throw new TypeError('invalid `op` value: ' + JSON.stringify(s.op)); + } + return s.op.replace(/[\s\S]/g, '\\$&'); + } + if (typeof s.comment === 'string') { + if (LINE_TERMINATORS.test(s.comment)) { + throw new TypeError('`comment` must not contain line terminators'); + } + return '#' + s.comment; + } + throw new TypeError('unrecognized object token shape'); + } + if ((/["\s\\]/).test(s) && !(/'/).test(s)) { + return "'" + s.replace(/(['])/g, '\\$1') + "'"; + } + if ((/["'\s]/).test(s)) { + return '"' + s.replace(/(["\\$`!])/g, '\\$1') + '"'; + } + return String(s).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g, '$1\\$2'); + }).join(' '); +}; diff --git a/node_modules/shell-quote/security.md b/node_modules/shell-quote/security.md new file mode 100644 index 0000000000000000000000000000000000000000..dc864139dbe30438445c31287a815d7168c690a8 --- /dev/null +++ b/node_modules/shell-quote/security.md @@ -0,0 +1,11 @@ +# Security Policy + +## Supported Versions + +Only the latest major version is supported at any given time. + +## Reporting a Vulnerability + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. diff --git a/node_modules/shell-quote/test/comment.js b/node_modules/shell-quote/test/comment.js new file mode 100644 index 0000000000000000000000000000000000000000..fb15d5cb989f62b6df85284000ce4c146e8fbcb2 --- /dev/null +++ b/node_modules/shell-quote/test/comment.js @@ -0,0 +1,16 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../').parse; + +test('comment', function (t) { + t.same(parse('beep#boop'), ['beep', { comment: 'boop' }]); + t.same(parse('beep #boop'), ['beep', { comment: 'boop' }]); + t.same(parse('beep # boop'), ['beep', { comment: ' boop' }]); + t.same(parse('beep # > boop'), ['beep', { comment: ' > boop' }]); + t.same(parse('beep # "> boop"'), ['beep', { comment: ' "> boop"' }]); + t.same(parse('beep "#"'), ['beep', '#']); + t.same(parse('beep #"#"#'), ['beep', { comment: '"#"#' }]); + t.same(parse('beep > boop # > foo'), ['beep', { op: '>' }, 'boop', { comment: ' > foo' }]); + t.end(); +}); diff --git a/node_modules/shell-quote/test/env.js b/node_modules/shell-quote/test/env.js new file mode 100644 index 0000000000000000000000000000000000000000..4cc0a515cfafdb40c8c24ad6bbf568cb5d4b72a5 --- /dev/null +++ b/node_modules/shell-quote/test/env.js @@ -0,0 +1,52 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../').parse; + +test('expand environment variables', function (t) { + t.same(parse('a $XYZ c', { XYZ: 'b' }), ['a', 'b', 'c']); + t.same(parse('a${XYZ}c', { XYZ: 'b' }), ['abc']); + t.same(parse('a${XYZ}c $XYZ', { XYZ: 'b' }), ['abc', 'b']); + t.same(parse('"-$X-$Y-"', { X: 'a', Y: 'b' }), ['-a-b-']); + t.same(parse("'-$X-$Y-'", { X: 'a', Y: 'b' }), ['-$X-$Y-']); + t.same(parse('qrs"$zzz"wxy', { zzz: 'tuv' }), ['qrstuvwxy']); + t.same(parse("qrs'$zzz'wxy", { zzz: 'tuv' }), ['qrs$zzzwxy']); + t.same(parse('qrs${zzz}wxy'), ['qrswxy']); + t.same(parse('qrs$wxy $'), ['qrs', '$']); + t.same(parse('grep "xy$"'), ['grep', 'xy$']); + t.same(parse('ab$x', { x: 'c' }), ['abc']); + t.same(parse('ab\\$x', { x: 'c' }), ['ab$x']); + t.same(parse('ab${x}def', { x: 'c' }), ['abcdef']); + t.same(parse('ab\\${x}def', { x: 'c' }), ['ab${x}def']); + t.same(parse('"ab\\${x}def"', { x: 'c' }), ['ab${x}def']); + + t.end(); +}); + +test('expand environment variables within here-strings', function (t) { + t.same(parse('a <<< $x', { x: 'Joe' }), ['a', { op: '<<<' }, 'Joe']); + t.same(parse('a <<< ${x}', { x: 'Joe' }), ['a', { op: '<<<' }, 'Joe']); + t.same(parse('a <<< "$x"', { x: 'Joe' }), ['a', { op: '<<<' }, 'Joe']); + t.same(parse('a <<< "${x}"', { x: 'Joe' }), ['a', { op: '<<<' }, 'Joe']); + + t.end(); +}); + +test('environment variables with metacharacters', function (t) { + t.same(parse('a $XYZ c', { XYZ: '"b"' }), ['a', '"b"', 'c']); + t.same(parse('a $XYZ c', { XYZ: '$X', X: 5 }), ['a', '$X', 'c']); + t.same(parse('a"$XYZ"c', { XYZ: "'xyz'" }), ["a'xyz'c"]); + + t.end(); +}); + +test('special shell parameters', function (t) { + var chars = '*@#?-$!0_'.split(''); + t.plan(chars.length); + + chars.forEach(function (c) { + var env = {}; + env[c] = 'xxx'; + t.same(parse('a $' + c + ' c', env), ['a', 'xxx', 'c']); + }); +}); diff --git a/node_modules/shell-quote/test/env_fn.js b/node_modules/shell-quote/test/env_fn.js new file mode 100644 index 0000000000000000000000000000000000000000..968e9120ca348f23b22465fddcbc40012fac5e22 --- /dev/null +++ b/node_modules/shell-quote/test/env_fn.js @@ -0,0 +1,21 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../').parse; + +function getEnv() { + return 'xxx'; +} + +function getEnvObj() { + return { op: '@@' }; +} + +test('functional env expansion', function (t) { + t.plan(4); + + t.same(parse('a $XYZ c', getEnv), ['a', 'xxx', 'c']); + t.same(parse('a $XYZ c', getEnvObj), ['a', { op: '@@' }, 'c']); + t.same(parse('a${XYZ}c', getEnvObj), ['a', { op: '@@' }, 'c']); + t.same(parse('"a $XYZ c"', getEnvObj), ['a ', { op: '@@' }, ' c']); +}); diff --git a/node_modules/shell-quote/test/op.js b/node_modules/shell-quote/test/op.js new file mode 100644 index 0000000000000000000000000000000000000000..38d37576547aeae963868a050e8658724ca94463 --- /dev/null +++ b/node_modules/shell-quote/test/op.js @@ -0,0 +1,102 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../').parse; + +test('single operators', function (t) { + t.same(parse('beep | boop'), ['beep', { op: '|' }, 'boop']); + t.same(parse('beep|boop'), ['beep', { op: '|' }, 'boop']); + t.same(parse('beep \\| boop'), ['beep', '|', 'boop']); + t.same(parse('beep "|boop"'), ['beep', '|boop']); + + t.same(parse('echo zing &'), ['echo', 'zing', { op: '&' }]); + t.same(parse('echo zing&'), ['echo', 'zing', { op: '&' }]); + t.same(parse('echo zing\\&'), ['echo', 'zing&']); + t.same(parse('echo "zing\\&"'), ['echo', 'zing\\&']); + + t.same(parse('beep;boop'), ['beep', { op: ';' }, 'boop']); + t.same(parse('(beep;boop)'), [ + { op: '(' }, 'beep', { op: ';' }, 'boop', { op: ')' } + ]); + + t.same(parse('beep>boop'), ['beep', { op: '>' }, 'boop']); + t.same(parse('beep 2>boop'), ['beep', '2', { op: '>' }, 'boop']); + t.same(parse('beep>blip'), + ['beep', { op: ';;' }, 'boop', { op: '|&' }, 'byte', { op: '>>' }, 'blip'] + ); + + t.same(parse('beep 2>&1'), ['beep', '2', { op: '>&' }, '1']); + + t.same( + parse('beep<(boop)'), + ['beep', { op: '<(' }, 'boop', { op: ')' }] + ); + t.same( + parse('beep<<(boop)'), + ['beep', { op: '<' }, { op: '<(' }, 'boop', { op: ')' }] + ); + + t.end(); +}); + +test('duplicating input file descriptors', function (t) { + // duplicating stdout to file descriptor 3 + t.same(parse('beep 3<&1'), ['beep', '3', { op: '<&' }, '1']); + + // duplicating stdout to file descriptor 0, i.e. stdin + t.same(parse('beep <&1'), ['beep', { op: '<&' }, '1']); + + // closes stdin + t.same(parse('beep <&-'), ['beep', { op: '<&' }, '-']); + + t.end(); +}); + +test('here strings', function (t) { + t.same(parse('cat <<< "hello world"'), ['cat', { op: '<<<' }, 'hello world']); + t.same(parse('cat <<< hello'), ['cat', { op: '<<<' }, 'hello']); + t.same(parse('cat<<<;{}']), '\\>\\<\\;\\{\\}'); + t.equal(quote(['a', 1, true, false]), 'a 1 true false'); + t.equal(quote(['a', 1, null, undefined]), 'a 1 null undefined'); + t.equal(quote(['a\\x']), "'a\\x'"); + t.equal(quote(['a"b']), '\'a"b\''); + t.equal(quote(['"a"b"']), '\'"a"b"\''); + t.equal(quote(['a\\"b']), '\'a\\"b\''); + t.equal(quote(['a\\b']), '\'a\\b\''); + t.end(); +}); + +test('quote ops', function (t) { + t.equal(quote(['a', { op: '|' }, 'b']), 'a \\| b'); + t.equal( + quote(['a', { op: '&&' }, 'b', { op: ';' }, 'c']), + 'a \\&\\& b \\; c' + ); + t.end(); +}); + +test('quote windows paths', { skip: 'breaking change, disabled until 2.x' }, function (t) { + var path = 'C:\\projects\\node-shell-quote\\index.js'; + + t.equal(quote([path, 'b', 'c d']), 'C:\\projects\\node-shell-quote\\index.js b \'c d\''); + + t.end(); +}); + +test("chars for windows paths don't break out", function (t) { + var x = '`:\\a\\b'; + t.equal(quote([x]), "'`:\\a\\b'"); + t.end(); +}); + +test('empty strings', function (t) { + t.equal(quote(['-x', '', 'y']), '-x \'\' y'); + + t.end(); +}); + +test('quote ops: allowlist', function (t) { + var ops = ['||', '&&', ';;', '|&', '<(', '<<<', '>>', '>&', '<&', '&', ';', '(', ')', '|', '<', '>']; + for (var i = 0; i < ops.length; i++) { + var op = ops[i]; + var expected = ''; + for (var j = 0; j < op.length; j++) { expected += '\\' + op.charAt(j); } + t.equal(quote([{ op: op }]), expected, 'op ' + op); + } + t.end(); +}); + +test('quote ops: rejects line terminators (GHSA-w7jw-789q-3m8p)', function (t) { + t['throws'](function () { quote([{ op: ';\nid' }]); }, TypeError, 'newline in op'); + t['throws'](function () { quote([{ op: ';\rid' }]); }, TypeError, 'carriage return in op'); + t['throws'](function () { quote([{ op: ';\u2028id' }]); }, TypeError, 'U+2028 in op'); + t['throws'](function () { quote([{ op: ';\u2029id' }]); }, TypeError, 'U+2029 in op'); + t.end(); +}); + +test('quote ops: rejects non-allowlisted values', function (t) { + t['throws'](function () { quote([{ op: '' }]); }, TypeError, 'empty op'); + t['throws'](function () { quote([{ op: 'foo' }]); }, TypeError, 'arbitrary string'); + t['throws'](function () { quote([{ op: '|||' }]); }, TypeError, 'near-miss'); + t['throws'](function () { quote([{ op: 42 }]); }, TypeError, 'non-string op'); + t.end(); +}); + +test('quote glob pattern', function (t) { + t.equal(quote([{ op: 'glob', pattern: 'test/*.test.js' }]), 'test/*.test.js'); + t.equal(quote([{ op: 'glob', pattern: '?ab' }]), '?ab'); + t.equal(quote([{ op: 'glob', pattern: '[ab]c' }]), '[ab]c'); + t.equal(quote([{ op: 'glob', pattern: '{a,b}' }]), '{a,b}'); + t.equal(quote([{ op: 'glob', pattern: 'my dir/*.txt' }]), 'my\\ dir/*.txt'); + t.equal(quote([{ op: 'glob', pattern: 'a$b' }]), 'a\\$b'); + t['throws'](function () { quote([{ op: 'glob' }]); }, TypeError, 'missing pattern'); + t['throws'](function () { quote([{ op: 'glob', pattern: 'a\nb' }]); }, TypeError, 'newline in pattern'); + t['throws'](function () { quote([{ op: 'glob', pattern: 'a\u2028b' }]); }, TypeError, 'U+2028 in pattern'); + t.end(); +}); + +test('quote comment', function (t) { + t.equal(quote(['echo', 'hi', { comment: ' a comment' }]), 'echo hi # a comment'); + t.equal(quote([{ comment: '' }]), '#'); + t['throws'](function () { quote([{ comment: 'a\nb' }]); }, TypeError, 'newline in comment'); + t['throws'](function () { quote([{ comment: 'a\rb' }]); }, TypeError, 'CR in comment'); + t['throws'](function () { quote([{ comment: 'a\u2028b' }]); }, TypeError, 'U+2028 in comment'); + t.end(); +}); + +test('quote rejects unrecognized object shapes', function (t) { + t['throws'](function () { quote([{}]); }, TypeError, 'empty object'); + t['throws'](function () { quote([{ foo: 'bar' }]); }, TypeError, 'unknown key'); + t['throws'](function () { quote([{ op: null }]); }, TypeError, 'null op'); + t.end(); +}); diff --git a/node_modules/shell-quote/test/set.js b/node_modules/shell-quote/test/set.js new file mode 100644 index 0000000000000000000000000000000000000000..9694538ad82c5da95c85fbae8a8a68cd06c94a8c --- /dev/null +++ b/node_modules/shell-quote/test/set.js @@ -0,0 +1,31 @@ +'use strict'; + +var test = require('tape'); +var parse = require('../').parse; + +test('set env vars', function (t) { + t.same( + parse('ABC=444 x y z'), + ['ABC=444', 'x', 'y', 'z'] + ); + t.same( + parse('ABC=3\\ 4\\ 5 x y z'), + ['ABC=3 4 5', 'x', 'y', 'z'] + ); + t.same( + parse('X="7 8 9" printx'), + ['X=7 8 9', 'printx'] + ); + t.same( + parse('X="7 8 9"; printx'), + ['X=7 8 9', { op: ';' }, 'printx'] + ); + t.same( + parse('X="7 8 9"; printx', function () { + t.fail('should not have matched any keys'); + }), + ['X=7 8 9', { op: ';' }, 'printx'] + ); + + t.end(); +}); diff --git a/node_modules/side-channel-list/.editorconfig b/node_modules/side-channel-list/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..72e0ebaa7f319d2bde03e55c8e58748245095f06 --- /dev/null +++ b/node_modules/side-channel-list/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel-list/.eslintrc b/node_modules/side-channel-list/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..93978e7d5b3d62d16972e7951ff9f683c7a006e4 --- /dev/null +++ b/node_modules/side-channel-list/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel-list/.github/FUNDING.yml b/node_modules/side-channel-list/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..eaff73503c08b845400cd863481308e197f74fe6 --- /dev/null +++ b/node_modules/side-channel-list/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel-list +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel-list/.nycrc b/node_modules/side-channel-list/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/node_modules/side-channel-list/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel-list/CHANGELOG.md b/node_modules/side-channel-list/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..e68bcb9b7df414d2ec12c6a1a690aa8832e59792 --- /dev/null +++ b/node_modules/side-channel-list/CHANGELOG.md @@ -0,0 +1,36 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/side-channel-list.git +/compare/v1.0.0...v1.0.1) - 2026-04-08 + +### Fixed + +- [Fix] `delete`: do not reset the list when deleting the head node of a multi-node list [`#3`](https://github.com/ljharb/side-channel-list.git +/issues/3) + +### Commits + +- [actions] update workflows [`9e79e6b`](https://github.com/ljharb/side-channel-list.git +/commit/9e79e6bf845532fafbf03b547429fe4f737214a3) +- [Deps] update `@arethetypeswrong/cli`, `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/tape`, `eslint`, `npmignore` [`babf3ca`](https://github.com/ljharb/side-channel-list.git +/commit/babf3ca4849d2fd893a470a6b82c62a80ccc9307) +- [Deps] update `object-inspect` [`9f0f4b8`](https://github.com/ljharb/side-channel-list.git +/commit/9f0f4b88ff2aa8b7b7c9e589ac1513f133d64b9f) + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`5d6baee`](https://github.com/ljharb/side-channel-list.git +/commit/5d6baee5c9054a1238007f5a1dfc109a7a816251) +- Initial commit [`3ae784c`](https://github.com/ljharb/side-channel-list.git +/commit/3ae784c63a47895fbaeed2a91ab54a8029a7a100) +- npm init [`07055a4`](https://github.com/ljharb/side-channel-list.git +/commit/07055a4d139895565b199dba5fe2479c1a1b9e28) +- Only apps should have lockfiles [`9573058`](https://github.com/ljharb/side-channel-list.git +/commit/9573058a47494e2d68f8c6c77b5d7fbe441949c1) diff --git a/node_modules/side-channel-list/LICENSE b/node_modules/side-channel-list/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f82f38963b0d282b529f64def2bcd40be3a9a947 --- /dev/null +++ b/node_modules/side-channel-list/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +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. diff --git a/node_modules/side-channel-list/README.md b/node_modules/side-channel-list/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d9c7a1373440a10641c8a48daf6707b3b3e132b0 --- /dev/null +++ b/node_modules/side-channel-list/README.md @@ -0,0 +1,62 @@ +# side-channel-list [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel, using a linked list. + +Warning: this implementation will leak memory until you `delete` the `key`. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-list +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelList = require('side-channel-list'); + +const channel = getSideChannelList(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-list +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-list.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-list.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-list +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-list/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-list#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-list.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-list.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-list.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-list +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-list/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-list/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-list +[actions-url]: https://github.com/ljharb/side-channel-list/actions diff --git a/node_modules/side-channel-list/index.d.ts b/node_modules/side-channel-list/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9cabc843d734f3dfef592abddf5c66b225472d2 --- /dev/null +++ b/node_modules/side-channel-list/index.d.ts @@ -0,0 +1,13 @@ +declare namespace getSideChannelList { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + }; +} + +declare function getSideChannelList(): getSideChannelList.Channel; + +export = getSideChannelList; diff --git a/node_modules/side-channel-list/index.js b/node_modules/side-channel-list/index.js new file mode 100644 index 0000000000000000000000000000000000000000..44602294fdf7bc7086a8521dc44d54844d696cdb --- /dev/null +++ b/node_modules/side-channel-list/index.js @@ -0,0 +1,111 @@ +'use strict'; + +var inspect = require('object-inspect'); + +var $TypeError = require('es-errors/type'); + +/* +* This function traverses the list returning the node corresponding to the given key. +* +* That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. +* By doing so, all the recently used nodes can be accessed relatively quickly. +*/ +/** @type {import('./list.d.ts').listGetNode} */ +// eslint-disable-next-line consistent-return +var listGetNode = function (list, key, isDelete) { + /** @type {typeof list | NonNullable<(typeof list)['next']>} */ + var prev = list; + /** @type {(typeof list)['next']} */ + var curr; + // eslint-disable-next-line eqeqeq + for (; (curr = prev.next) != null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + if (!isDelete) { + // eslint-disable-next-line no-extra-parens + curr.next = /** @type {NonNullable} */ (list.next); + list.next = curr; // eslint-disable-line no-param-reassign + } + return curr; + } + } +}; + +/** @type {import('./list.d.ts').listGet} */ +var listGet = function (objects, key) { + if (!objects) { + return void undefined; + } + var node = listGetNode(objects, key); + return node && node.value; +}; +/** @type {import('./list.d.ts').listSet} */ +var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = /** @type {import('./list.d.ts').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens + key: key, + next: objects.next, + value: value + }); + } +}; +/** @type {import('./list.d.ts').listHas} */ +var listHas = function (objects, key) { + if (!objects) { + return false; + } + return !!listGetNode(objects, key); +}; +/** @type {import('./list.d.ts').listDelete} */ +// eslint-disable-next-line consistent-return +var listDelete = function (objects, key) { + if (objects) { + return listGetNode(objects, key, true); + } +}; + +/** @type {import('.')} */ +module.exports = function getSideChannelList() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {import('./list.d.ts').RootNode | undefined} */ var $o; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + var deletedNode = listDelete($o, key); + if (deletedNode && $o && !$o.next) { + $o = void undefined; + } + return !!deletedNode; + }, + get: function (key) { + return listGet($o, key); + }, + has: function (key) { + return listHas($o, key); + }, + set: function (key, value) { + if (!$o) { + // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head + $o = { + next: void undefined + }; + } + // eslint-disable-next-line no-extra-parens + listSet(/** @type {NonNullable} */ ($o), key, value); + } + }; + return channel; +}; diff --git a/node_modules/side-channel-list/list.d.ts b/node_modules/side-channel-list/list.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c759e2532dc7274c4ddd71b3f96d06a1390eaa8 --- /dev/null +++ b/node_modules/side-channel-list/list.d.ts @@ -0,0 +1,14 @@ +type ListNode = { + key: K; + next: undefined | ListNode; + value: T; +}; +type RootNode = { + next: undefined | ListNode; +}; + +export function listGetNode(list: RootNode, key: ListNode['key'], isDelete?: boolean): ListNode | undefined; +export function listGet(objects: undefined | RootNode, key: ListNode['key']): T | undefined; +export function listSet(objects: RootNode, key: ListNode['key'], value: T): void; +export function listHas(objects: undefined | RootNode, key: ListNode['key']): boolean; +export function listDelete(objects: undefined | RootNode, key: ListNode['key']): ListNode | undefined; diff --git a/node_modules/side-channel-list/package.json b/node_modules/side-channel-list/package.json new file mode 100644 index 0000000000000000000000000000000000000000..bc4c08ca01c1b763d44103526bd08f26e8c9c820 --- /dev/null +++ b/node_modules/side-channel-list/package.json @@ -0,0 +1,77 @@ +{ + "name": "side-channel-list", + "version": "1.0.1", + "description": "Store information about any JS value in a side channel, using a linked list", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-list.git" + }, + "keywords": [], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-list/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-list#readme", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.18.2", + "@ljharb/eslint-config": "^22.2.2", + "@ljharb/tsconfig": "^0.3.2", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "^8.57.1", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-list/test/index.js b/node_modules/side-channel-list/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d1b915dd169f02132d8e73eaf807f0cb4e2aaec1 --- /dev/null +++ b/node_modules/side-channel-list/test/index.js @@ -0,0 +1,154 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelList = require('../'); + +test('getSideChannelList', function (t) { + t.test('export', function (st) { + st.equal(typeof getSideChannelList, 'function', 'is a function'); + + st.equal(getSideChannelList.length, 0, 'takes no arguments'); + + var channel = getSideChannelList(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannelList(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannelList(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannelList(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannelList(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannelList(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.test('delete: first node in a multi-node list', function (st) { + var channel = getSideChannelList(); + + channel.set('a', 1); + channel.set('b', 2); + + st.equal(channel['delete']('b'), true, 'deleting first data node yields true'); + + st.equal(channel.has('a'), true, 'second node is still present after deleting first'); + st.equal(channel.get('a'), 1, 'second node value is intact after deleting first'); + st.equal(channel.has('b'), false, 'deleted node is gone'); + + st.end(); + }); + + t.test('delete: last remaining node empties the list', function (st) { + var channel = getSideChannelList(); + + channel.set('a', 1); + channel.set('b', 2); + + st.equal(channel['delete']('b'), true, 'delete first node'); + st.equal(channel['delete']('a'), true, 'delete second (last) node'); + + st.equal(channel.has('a'), false, 'a is gone'); + st.equal(channel.has('b'), false, 'b is gone'); + st.equal(channel.get('a'), undefined, 'get a yields undefined'); + + channel.set('c', 3); + st.equal(channel.get('c'), 3, 'can set new values after emptying'); + + st.end(); + }); + + t.test('delete: middle node in a multi-node list', function (st) { + var channel = getSideChannelList(); + + channel.set('a', 1); + channel.set('b', 2); + channel.set('c', 3); + + st.equal(channel['delete']('b'), true, 'deleting middle node yields true'); + + st.equal(channel.get('a'), 1, 'first node still intact'); + st.equal(channel.has('b'), false, 'middle node is gone'); + st.equal(channel.get('c'), 3, 'last node still intact'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/side-channel-list/tsconfig.json b/node_modules/side-channel-list/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d9a6668c3ae6be748c78fbd5694053706b3d6942 --- /dev/null +++ b/node_modules/side-channel-list/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel-map/.editorconfig b/node_modules/side-channel-map/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..72e0ebaa7f319d2bde03e55c8e58748245095f06 --- /dev/null +++ b/node_modules/side-channel-map/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel-map/.eslintrc b/node_modules/side-channel-map/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..93978e7d5b3d62d16972e7951ff9f683c7a006e4 --- /dev/null +++ b/node_modules/side-channel-map/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel-map/.github/FUNDING.yml b/node_modules/side-channel-map/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..f2891bd6278901f51a71a134b8b3734c49fe11de --- /dev/null +++ b/node_modules/side-channel-map/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel-map +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel-map/.nycrc b/node_modules/side-channel-map/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/node_modules/side-channel-map/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel-map/CHANGELOG.md b/node_modules/side-channel-map/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..b6ccea906b109d2fbdeab5033ef37fcf3c677451 --- /dev/null +++ b/node_modules/side-channel-map/CHANGELOG.md @@ -0,0 +1,22 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.1](https://github.com/ljharb/side-channel-map/compare/v1.0.0...v1.0.1) - 2024-12-10 + +### Commits + +- [Deps] update `call-bound` [`6d05aaa`](https://github.com/ljharb/side-channel-map/commit/6d05aaa4ce5f2be4e7825df433d650696f0ba40f) +- [types] fix generics ordering [`11c0184`](https://github.com/ljharb/side-channel-map/commit/11c0184132ac11fdc16857e12682e148e5e9ee74) + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`ad877b4`](https://github.com/ljharb/side-channel-map/commit/ad877b42926d46d63fff76a2bd01d2b4a01959a9) +- Initial commit [`28f8879`](https://github.com/ljharb/side-channel-map/commit/28f8879c512abe8fcf9b6a4dc7754a0287e5eba4) +- npm init [`2c9604e`](https://github.com/ljharb/side-channel-map/commit/2c9604e5aa40223e425ea7cea78f8a07697504bd) +- Only apps should have lockfiles [`5e7ba9c`](https://github.com/ljharb/side-channel-map/commit/5e7ba9cffe3ef42095815adc8ac1255b49bbadf5) diff --git a/node_modules/side-channel-map/LICENSE b/node_modules/side-channel-map/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f82f38963b0d282b529f64def2bcd40be3a9a947 --- /dev/null +++ b/node_modules/side-channel-map/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Jordan Harband + +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. diff --git a/node_modules/side-channel-map/README.md b/node_modules/side-channel-map/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8fa6f77f07d10658117ff4f4ed4af647e3bd7c40 --- /dev/null +++ b/node_modules/side-channel-map/README.md @@ -0,0 +1,62 @@ +# side-channel-map [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel, using a Map. + +Warning: if the `key` is an object, this implementation will leak memory until you `delete` it. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-map +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelMap = require('side-channel-map'); + +const channel = getSideChannelMap(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-map +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-map.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-map.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-map +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-map/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-map#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-map.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-map.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-map.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-map +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-map/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-map/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-map +[actions-url]: https://github.com/ljharb/side-channel-map/actions diff --git a/node_modules/side-channel-map/index.d.ts b/node_modules/side-channel-map/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..de33e899e66db27eac77bb85d1b8afe183272e85 --- /dev/null +++ b/node_modules/side-channel-map/index.d.ts @@ -0,0 +1,15 @@ +declare namespace getSideChannelMap { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + }; +} + +declare function getSideChannelMap(): getSideChannelMap.Channel; + +declare const x: false | typeof getSideChannelMap; + +export = x; diff --git a/node_modules/side-channel-map/index.js b/node_modules/side-channel-map/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e111100bfd6cc8b296a20276d8238e3a910f676d --- /dev/null +++ b/node_modules/side-channel-map/index.js @@ -0,0 +1,68 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bound'); +var inspect = require('object-inspect'); + +var $TypeError = require('es-errors/type'); +var $Map = GetIntrinsic('%Map%', true); + +/** @type {(thisArg: Map, key: K) => V} */ +var $mapGet = callBound('Map.prototype.get', true); +/** @type {(thisArg: Map, key: K, value: V) => void} */ +var $mapSet = callBound('Map.prototype.set', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapHas = callBound('Map.prototype.has', true); +/** @type {(thisArg: Map, key: K) => boolean} */ +var $mapDelete = callBound('Map.prototype.delete', true); +/** @type {(thisArg: Map) => number} */ +var $mapSize = callBound('Map.prototype.size', true); + +/** @type {import('.')} */ +module.exports = !!$Map && /** @type {Exclude} */ function getSideChannelMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {Map | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($m) { + var result = $mapDelete($m, key); + if ($mapSize($m) === 0) { + $m = void undefined; + } + return result; + } + return false; + }, + get: function (key) { // eslint-disable-line consistent-return + if ($m) { + return $mapGet($m, key); + } + }, + has: function (key) { + if ($m) { + return $mapHas($m, key); + } + return false; + }, + set: function (key, value) { + if (!$m) { + // @ts-expect-error TS can't handle narrowing a variable inside a closure + $m = new $Map(); + } + $mapSet($m, key, value); + } + }; + + // @ts-expect-error TODO: figure out why TS is erroring here + return channel; +}; diff --git a/node_modules/side-channel-map/package.json b/node_modules/side-channel-map/package.json new file mode 100644 index 0000000000000000000000000000000000000000..18e80805905c32cf286aa286e1a0c8f8248ec574 --- /dev/null +++ b/node_modules/side-channel-map/package.json @@ -0,0 +1,80 @@ +{ + "name": "side-channel-map", + "version": "1.0.1", + "description": "Store information about any JS value in a side channel, using a Map", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "evalmd README.md && eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-map.git" + }, + "keywords": [], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-map/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-map#readme", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/get-intrinsic": "^1.2.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-map/test/index.js b/node_modules/side-channel-map/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..17433239ee490b8f734c5c60198eae699e201c65 --- /dev/null +++ b/node_modules/side-channel-map/test/index.js @@ -0,0 +1,114 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelMap = require('../'); + +test('getSideChannelMap', { skip: typeof Map !== 'function' }, function (t) { + var getSideChannel = getSideChannelMap || function () { + throw new EvalError('should never happen'); + }; + + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); + +test('getSideChannelMap, no Maps', { skip: typeof Map === 'function' }, function (t) { + t.equal(getSideChannelMap, false, 'is false'); + + t.end(); +}); diff --git a/node_modules/side-channel-map/tsconfig.json b/node_modules/side-channel-map/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d9a6668c3ae6be748c78fbd5694053706b3d6942 --- /dev/null +++ b/node_modules/side-channel-map/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel-weakmap/.editorconfig b/node_modules/side-channel-weakmap/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..72e0ebaa7f319d2bde03e55c8e58748245095f06 --- /dev/null +++ b/node_modules/side-channel-weakmap/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel-weakmap/.eslintrc b/node_modules/side-channel-weakmap/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..9b13ad8ba555410581c1b389ca2cdfbd9d91310d --- /dev/null +++ b/node_modules/side-channel-weakmap/.eslintrc @@ -0,0 +1,12 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel-weakmap/.github/FUNDING.yml b/node_modules/side-channel-weakmap/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..2ae71cdb9425d0394e2ee363df151086c081c4c9 --- /dev/null +++ b/node_modules/side-channel-weakmap/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel-weakmap +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel-weakmap/.nycrc b/node_modules/side-channel-weakmap/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/node_modules/side-channel-weakmap/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel-weakmap/CHANGELOG.md b/node_modules/side-channel-weakmap/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..aba7ab0412975a41899d61be28ff104c1db3fbf8 --- /dev/null +++ b/node_modules/side-channel-weakmap/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/ljharb/side-channel-weakmap/compare/v1.0.1...v1.0.2) - 2024-12-10 + +### Commits + +- [types] fix generics ordering [`1b62e94`](https://github.com/ljharb/side-channel-weakmap/commit/1b62e94a2ad6ed30b640ba73c4a2535836c67289) + +## [v1.0.1](https://github.com/ljharb/side-channel-weakmap/compare/v1.0.0...v1.0.1) - 2024-12-10 + +### Commits + +- [types] fix generics ordering [`08a4a5d`](https://github.com/ljharb/side-channel-weakmap/commit/08a4a5dbffedc3ebc79f1aaaf5a3dd6d2196dc1b) +- [Deps] update `side-channel-map` [`b53fe44`](https://github.com/ljharb/side-channel-weakmap/commit/b53fe447dfdd3a9aebedfd015b384eac17fce916) + +## v1.0.0 - 2024-12-10 + +### Commits + +- Initial implementation, tests, readme, types [`53c0fa4`](https://github.com/ljharb/side-channel-weakmap/commit/53c0fa4788435a006f58b9d7b43cb65989ecee49) +- Initial commit [`a157947`](https://github.com/ljharb/side-channel-weakmap/commit/a157947f26fcaf2c4a941d3a044e76bf67343532) +- npm init [`54dfc55`](https://github.com/ljharb/side-channel-weakmap/commit/54dfc55bafb16265910d5aad4e743c43aee5bbbb) +- Only apps should have lockfiles [`0ddd6c7`](https://github.com/ljharb/side-channel-weakmap/commit/0ddd6c7b07fe8ee04d67b2e9f7255af7ce62c07d) diff --git a/node_modules/side-channel-weakmap/LICENSE b/node_modules/side-channel-weakmap/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3900dd7e2ffe6d5205fde1cd3f890aa51ea36234 --- /dev/null +++ b/node_modules/side-channel-weakmap/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +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. diff --git a/node_modules/side-channel-weakmap/README.md b/node_modules/side-channel-weakmap/README.md new file mode 100644 index 0000000000000000000000000000000000000000..856ee3643b0832a52930b5e346539d9593640094 --- /dev/null +++ b/node_modules/side-channel-weakmap/README.md @@ -0,0 +1,62 @@ +# side-channel-weakmap [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel. Uses WeakMap if available. + +Warning: this implementation will leak memory until you `delete` the `key`. +Use [`side-channel`](https://npmjs.com/side-channel) for the best available strategy. + +## Getting started + +```sh +npm install --save side-channel-weakmap +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannelList = require('side-channel-weakmap'); + +const channel = getSideChannelList(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel-weakmap +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel-weakmap.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel-weakmap.svg +[deps-url]: https://david-dm.org/ljharb/side-channel-weakmap +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel-weakmap/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel-weakmap#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel-weakmap.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel-weakmap.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel-weakmap.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel-weakmap +[codecov-image]: https://codecov.io/gh/ljharb/side-channel-weakmap/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel-weakmap/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/side-channel-weakmap +[actions-url]: https://github.com/ljharb/side-channel-weakmap/actions diff --git a/node_modules/side-channel-weakmap/index.d.ts b/node_modules/side-channel-weakmap/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce1bc2a4ae2ea0be0eac679b305b6d20d69a7793 --- /dev/null +++ b/node_modules/side-channel-weakmap/index.d.ts @@ -0,0 +1,15 @@ +declare namespace getSideChannelWeakMap { + type Channel = { + assert: (key: K) => void; + has: (key: K) => boolean; + get: (key: K) => V | undefined; + set: (key: K, value: V) => void; + delete: (key: K) => boolean; + } +} + +declare function getSideChannelWeakMap(): getSideChannelWeakMap.Channel; + +declare const x: false | typeof getSideChannelWeakMap; + +export = x; diff --git a/node_modules/side-channel-weakmap/index.js b/node_modules/side-channel-weakmap/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e5b8183d9717d5917efee321be4bf12c01c025cb --- /dev/null +++ b/node_modules/side-channel-weakmap/index.js @@ -0,0 +1,84 @@ +'use strict'; + +var GetIntrinsic = require('get-intrinsic'); +var callBound = require('call-bound'); +var inspect = require('object-inspect'); +var getSideChannelMap = require('side-channel-map'); + +var $TypeError = require('es-errors/type'); +var $WeakMap = GetIntrinsic('%WeakMap%', true); + +/** @type {(thisArg: WeakMap, key: K) => V} */ +var $weakMapGet = callBound('WeakMap.prototype.get', true); +/** @type {(thisArg: WeakMap, key: K, value: V) => void} */ +var $weakMapSet = callBound('WeakMap.prototype.set', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapHas = callBound('WeakMap.prototype.has', true); +/** @type {(thisArg: WeakMap, key: K) => boolean} */ +var $weakMapDelete = callBound('WeakMap.prototype.delete', true); + +/** @type {import('.')} */ +module.exports = $WeakMap + ? /** @type {Exclude} */ function getSideChannelWeakMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {WeakMap | undefined} */ var $wm; + /** @type {Channel | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapDelete($wm, key); + } + } else if (getSideChannelMap) { + if ($m) { + return $m['delete'](key); + } + } + return false; + }, + get: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } + return $m && $m.get(key); + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } + return !!$m && $m.has(key); + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if (getSideChannelMap) { + if (!$m) { + $m = getSideChannelMap(); + } + // eslint-disable-next-line no-extra-parens + /** @type {NonNullable} */ ($m).set(key, value); + } + } + }; + + // @ts-expect-error TODO: figure out why this is erroring + return channel; + } + : getSideChannelMap; diff --git a/node_modules/side-channel-weakmap/package.json b/node_modules/side-channel-weakmap/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9ef6583335d8670f8f86c7508cd047c6ae224a68 --- /dev/null +++ b/node_modules/side-channel-weakmap/package.json @@ -0,0 +1,87 @@ +{ + "name": "side-channel-weakmap", + "version": "1.0.2", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel-weakmap.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel-weakmap/issues" + }, + "homepage": "https://github.com/ljharb/side-channel-weakmap#readme", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/call-bind": "^1.0.5", + "@types/get-intrinsic": "^1.2.3", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel-weakmap/test/index.js b/node_modules/side-channel-weakmap/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a01248b5729c1308909cdd62a8344b8de9b19c89 --- /dev/null +++ b/node_modules/side-channel-weakmap/test/index.js @@ -0,0 +1,114 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannelWeakMap = require('../'); + +test('getSideChannelMap', { skip: typeof WeakMap !== 'function' && typeof Map !== 'function' }, function (t) { + var getSideChannel = getSideChannelWeakMap || function () { + throw new EvalError('should never happen'); + }; + + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); + +test('getSideChannelMap, no WeakMaps and/or Maps', { skip: typeof WeakMap === 'function' || typeof Map === 'function' }, function (t) { + t.equal(getSideChannelWeakMap, false, 'is false'); + + t.end(); +}); diff --git a/node_modules/side-channel-weakmap/tsconfig.json b/node_modules/side-channel-weakmap/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d9a6668c3ae6be748c78fbd5694053706b3d6942 --- /dev/null +++ b/node_modules/side-channel-weakmap/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/side-channel/.editorconfig b/node_modules/side-channel/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..72e0ebaa7f319d2bde03e55c8e58748245095f06 --- /dev/null +++ b/node_modules/side-channel/.editorconfig @@ -0,0 +1,9 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +indent_style = tab +indent_size = 2 +trim_trailing_whitespace = true diff --git a/node_modules/side-channel/.eslintrc b/node_modules/side-channel/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..9b13ad8ba555410581c1b389ca2cdfbd9d91310d --- /dev/null +++ b/node_modules/side-channel/.eslintrc @@ -0,0 +1,12 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "max-lines-per-function": 0, + "multiline-comment-style": 1, + "new-cap": [2, { "capIsNewExceptions": ["GetIntrinsic"] }], + }, +} diff --git a/node_modules/side-channel/.github/FUNDING.yml b/node_modules/side-channel/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..2a94840c6ee509fc0eee1ca4574deea75163df27 --- /dev/null +++ b/node_modules/side-channel/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/side-channel +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/side-channel/.nycrc b/node_modules/side-channel/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/node_modules/side-channel/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/side-channel/CHANGELOG.md b/node_modules/side-channel/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..decafe54f0af9e4f11be779a7f0d8b89116741d4 --- /dev/null +++ b/node_modules/side-channel/CHANGELOG.md @@ -0,0 +1,120 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.1](https://github.com/ljharb/side-channel/compare/v1.1.0...v1.1.1) - 2026-06-08 + +### Commits + +- [Fix] `assert`: do not observably access object keys when throwing [`fc17361`](https://github.com/ljharb/side-channel/commit/fc173615136e6a6c3194656e6088afbc0bd6f9b8) +- [actions] update workflows [`35b18c0`](https://github.com/ljharb/side-channel/commit/35b18c0bced5769d59226cd44a7e4003ad0aee81) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/tape`, `auto-changelog`, `eslint`, `npmignore` [`b456a01`](https://github.com/ljharb/side-channel/commit/b456a01396cfdd028e5d39ea84885fe9178a72cf) +- [Deps] update `object-inspect`, `side-channel-list` [`accf1a1`](https://github.com/ljharb/side-channel/commit/accf1a1a2767a22b1f5eeb5769a1db4c35a78090) +- [readme] replace runkit CI badge with shields.io check-runs badge [`7e0c956`](https://github.com/ljharb/side-channel/commit/7e0c956411cc29267197a49a155a3d9bd01bacac) + +## [v1.1.0](https://github.com/ljharb/side-channel/compare/v1.0.6...v1.1.0) - 2024-12-11 + +### Commits + +- [Refactor] extract implementations to `side-channel-weakmap`, `side-channel-map`, `side-channel-list` [`ada5955`](https://github.com/ljharb/side-channel/commit/ada595549a5c4c6c853756d598846b180941c6da) +- [New] add `channel.delete` [`c01d2d3`](https://github.com/ljharb/side-channel/commit/c01d2d3fd51dbb1ce6da72ad7916e61bd6172aad) +- [types] improve types [`0c54356`](https://github.com/ljharb/side-channel/commit/0c5435651417df41b8cc1a5f7cdce8bffae68cde) +- [readme] add content [`be24868`](https://github.com/ljharb/side-channel/commit/be248682ac294b0e22c883092c45985aa91c490a) +- [actions] split out node 10-20, and 20+ [`c4488e2`](https://github.com/ljharb/side-channel/commit/c4488e241ef3d49a19fe266ac830a2e644305911) +- [types] use shared tsconfig [`0e0d57c`](https://github.com/ljharb/side-channel/commit/0e0d57c2ff17c7b45c6cbd43ebcf553edc9e3adc) +- [Dev Deps] update `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/get-intrinsic`, `@types/object-inspect`, `@types/tape`, `auto-changelog`, `tape` [`fb4f622`](https://github.com/ljharb/side-channel/commit/fb4f622e64a99a1e40b6e5cd7691674a9dc429e4) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`b78336b`](https://github.com/ljharb/side-channel/commit/b78336b886172d1b457d414ac9e28de8c5fecc78) +- [Tests] replace `aud` with `npm audit` [`ee3ab46`](https://github.com/ljharb/side-channel/commit/ee3ab4690d954311c35115651bcfd45edd205aa1) +- [Dev Deps] add missing peer dep [`c03e21a`](https://github.com/ljharb/side-channel/commit/c03e21a7def3b67cdc15ae22316884fefcb2f6a8) + +## [v1.0.6](https://github.com/ljharb/side-channel/compare/v1.0.5...v1.0.6) - 2024-02-29 + +### Commits + +- add types [`9beef66`](https://github.com/ljharb/side-channel/commit/9beef6643e6d717ea57bedabf86448123a7dd9e9) +- [meta] simplify `exports` [`4334cf9`](https://github.com/ljharb/side-channel/commit/4334cf9df654151504c383b62a2f9ebdc8d9d5ac) +- [Deps] update `call-bind` [`d6043c4`](https://github.com/ljharb/side-channel/commit/d6043c4d8f4d7be9037dd0f0419c7a2e0e39ec6a) +- [Dev Deps] update `tape` [`6aca376`](https://github.com/ljharb/side-channel/commit/6aca3761868dc8cd5ff7fd9799bf6b95e09a6eb0) + +## [v1.0.5](https://github.com/ljharb/side-channel/compare/v1.0.4...v1.0.5) - 2024-02-06 + +### Commits + +- [actions] reuse common workflows [`3d2e1ff`](https://github.com/ljharb/side-channel/commit/3d2e1ffd16dd6eaaf3e40ff57951f840d2d63c04) +- [meta] use `npmignore` to autogenerate an npmignore file [`04296ea`](https://github.com/ljharb/side-channel/commit/04296ea17d1544b0a5d20fd5bfb31aa4f6513eb9) +- [meta] add `.editorconfig`; add `eclint` [`130f0a6`](https://github.com/ljharb/side-channel/commit/130f0a6adbc04d385c7456a601d38344dce3d6a9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `safe-publish-latest`, `tape` [`d480c2f`](https://github.com/ljharb/side-channel/commit/d480c2fbe757489ae9b4275491ffbcc3ac4725e9) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`ecbe70e`](https://github.com/ljharb/side-channel/commit/ecbe70e53a418234081a77971fec1fdfae20c841) +- [actions] update rebase action [`75240b9`](https://github.com/ljharb/side-channel/commit/75240b9963b816e8846400d2287cb68f88c7fba7) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`ae8d281`](https://github.com/ljharb/side-channel/commit/ae8d281572430099109870fd9430d2ca3f320b8d) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`7125b88`](https://github.com/ljharb/side-channel/commit/7125b885fd0eacad4fee9b073b72d14065ece278) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`82577c9`](https://github.com/ljharb/side-channel/commit/82577c9796304519139a570f82a317211b5f3b86) +- [Deps] update `call-bind`, `get-intrinsic`, `object-inspect` [`550aadf`](https://github.com/ljharb/side-channel/commit/550aadf20475a6081fd70304cc54f77259a5c8a8) +- [Tests] increase coverage [`5130877`](https://github.com/ljharb/side-channel/commit/5130877a7b27c862e64e6d1c12a178b28808859d) +- [Deps] update `get-intrinsic`, `object-inspect` [`ba0194c`](https://github.com/ljharb/side-channel/commit/ba0194c505b1a8a0427be14cadd5b8a46d4d01b8) +- [meta] add missing `engines.node` [`985fd24`](https://github.com/ljharb/side-channel/commit/985fd249663cb06617a693a94fe08cad12f5cb70) +- [Refactor] use `es-errors`, so things that only need those do not need `get-intrinsic` [`40227a8`](https://github.com/ljharb/side-channel/commit/40227a87b01709ad2c0eebf87eb4223a800099b9) +- [Deps] update `get-intrinsic` [`a989b40`](https://github.com/ljharb/side-channel/commit/a989b4024958737ae7be9fbffdeff2078f33a0fd) +- [Deps] update `object-inspect` [`aec42d2`](https://github.com/ljharb/side-channel/commit/aec42d2ec541a31aaa02475692c87d489237d9a3) + +## [v1.0.4](https://github.com/ljharb/side-channel/compare/v1.0.3...v1.0.4) - 2020-12-29 + +### Commits + +- [Tests] migrate tests to Github Actions [`10909cb`](https://github.com/ljharb/side-channel/commit/10909cbf8ce9c0bf96f604cf13d7ffd5a22c2d40) +- [Refactor] Use a linked list rather than an array, and move accessed nodes to the beginning [`195613f`](https://github.com/ljharb/side-channel/commit/195613f28b5c1e6072ef0b61b5beebaf2b6a304e) +- [meta] do not publish github action workflow files [`290ec29`](https://github.com/ljharb/side-channel/commit/290ec29cd21a60585145b4a7237ec55228c52c27) +- [Tests] run `nyc` on all tests; use `tape` runner [`ea6d030`](https://github.com/ljharb/side-channel/commit/ea6d030ff3fe6be2eca39e859d644c51ecd88869) +- [actions] add "Allow Edits" workflow [`d464d8f`](https://github.com/ljharb/side-channel/commit/d464d8fe52b5eddf1504a0ed97f0941a90f32c15) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog` [`02daca8`](https://github.com/ljharb/side-channel/commit/02daca87c6809821c97be468d1afa2f5ef447383) +- [Refactor] use `call-bind` and `get-intrinsic` instead of `es-abstract` [`e09d481`](https://github.com/ljharb/side-channel/commit/e09d481528452ebafa5cdeae1af665c35aa2deee) +- [Deps] update `object.assign` [`ee83aa8`](https://github.com/ljharb/side-channel/commit/ee83aa81df313b5e46319a63adb05cf0c179079a) +- [actions] update rebase action to use checkout v2 [`7726b0b`](https://github.com/ljharb/side-channel/commit/7726b0b058b632fccea709f58960871defaaa9d7) + +## [v1.0.3](https://github.com/ljharb/side-channel/compare/v1.0.2...v1.0.3) - 2020-08-23 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`1f10561`](https://github.com/ljharb/side-channel/commit/1f105611ef3acf32dec8032ae5c0baa5e56bb868) +- [Deps] update `es-abstract`, `object-inspect` [`bc20159`](https://github.com/ljharb/side-channel/commit/bc201597949a505e37cef9eaf24c7010831e6f03) +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`b9b2b22`](https://github.com/ljharb/side-channel/commit/b9b2b225f9e0ea72a6ec2b89348f0bd690bc9ed1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`7055ab4`](https://github.com/ljharb/side-channel/commit/7055ab4de0860606efd2003674a74f1fe6ebc07e) +- [Dev Deps] update `auto-changelog`; add `aud` [`d278c37`](https://github.com/ljharb/side-channel/commit/d278c37d08227be4f84aa769fcd919e73feeba40) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`3bcf982`](https://github.com/ljharb/side-channel/commit/3bcf982faa122745b39c33ce83d32fdf003741c6) +- [Tests] only audit prod deps [`18d01c4`](https://github.com/ljharb/side-channel/commit/18d01c4015b82a3d75044c4d5ba7917b2eac01ec) +- [Deps] update `es-abstract` [`6ab096d`](https://github.com/ljharb/side-channel/commit/6ab096d9de2b482cf5e0717e34e212f5b2b9bc9a) +- [Dev Deps] update `tape` [`9dc174c`](https://github.com/ljharb/side-channel/commit/9dc174cc651dfd300b4b72da936a0a7eda5f9452) +- [Deps] update `es-abstract` [`431d0f0`](https://github.com/ljharb/side-channel/commit/431d0f0ff11fbd2ae6f3115582a356d3a1cfce82) +- [Deps] update `es-abstract` [`49869fd`](https://github.com/ljharb/side-channel/commit/49869fd323bf4453f0ba515c0fb265cf5ab7b932) +- [meta] Add package.json to package's exports [`77d9cdc`](https://github.com/ljharb/side-channel/commit/77d9cdceb2a9e47700074f2ae0c0a202e7dac0d4) + +## [v1.0.2](https://github.com/ljharb/side-channel/compare/v1.0.1...v1.0.2) - 2019-12-20 + +### Commits + +- [Dev Deps] update `@ljharb/eslint-config`, `tape` [`4a526df`](https://github.com/ljharb/side-channel/commit/4a526df44e4701566ed001ec78546193f818b082) +- [Deps] update `es-abstract` [`d4f6e62`](https://github.com/ljharb/side-channel/commit/d4f6e629b6fb93a07415db7f30d3c90fd7f264fe) + +## [v1.0.1](https://github.com/ljharb/side-channel/compare/v1.0.0...v1.0.1) - 2019-12-01 + +### Commits + +- [Fix] add missing "exports" [`d212907`](https://github.com/ljharb/side-channel/commit/d2129073abf0701a5343bf28aa2145617604dc2e) + +## v1.0.0 - 2019-12-01 + +### Commits + +- Initial implementation [`dbebd3a`](https://github.com/ljharb/side-channel/commit/dbebd3a4b5ed64242f9a6810efe7c4214cd8cde4) +- Initial tests [`73bdefe`](https://github.com/ljharb/side-channel/commit/73bdefe568c9076cf8c0b8719bc2141aec0e19b8) +- Initial commit [`43c03e1`](https://github.com/ljharb/side-channel/commit/43c03e1c2849ec50a87b7a5cd76238a62b0b8770) +- npm init [`5c090a7`](https://github.com/ljharb/side-channel/commit/5c090a765d66a5527d9889b89aeff78dee91348c) +- [meta] add `auto-changelog` [`a5c4e56`](https://github.com/ljharb/side-channel/commit/a5c4e5675ec02d5eb4d84b4243aeea2a1d38fbec) +- [actions] add automatic rebasing / merge commit blocking [`bab1683`](https://github.com/ljharb/side-channel/commit/bab1683d8f9754b086e94397699fdc645e0d7077) +- [meta] add `funding` field; create FUNDING.yml [`63d7aea`](https://github.com/ljharb/side-channel/commit/63d7aeaf34f5650650ae97ca4b9fae685bd0937c) +- [Tests] add `npm run lint` [`46a5a81`](https://github.com/ljharb/side-channel/commit/46a5a81705cd2664f83df232c01dbbf2ee952885) +- Only apps should have lockfiles [`8b16b03`](https://github.com/ljharb/side-channel/commit/8b16b0305f00895d90c4e2e5773c854cfea0e448) +- [meta] add `safe-publish-latest` [`2f098ef`](https://github.com/ljharb/side-channel/commit/2f098ef092a39399cfe548b19a1fc03c2fd2f490) diff --git a/node_modules/side-channel/LICENSE b/node_modules/side-channel/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3900dd7e2ffe6d5205fde1cd3f890aa51ea36234 --- /dev/null +++ b/node_modules/side-channel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Jordan Harband + +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. diff --git a/node_modules/side-channel/README.md b/node_modules/side-channel/README.md new file mode 100644 index 0000000000000000000000000000000000000000..73ba466cc7f497e2a9c7ea49fa8425d70628eb69 --- /dev/null +++ b/node_modules/side-channel/README.md @@ -0,0 +1,61 @@ +# side-channel [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Store information about any JS value in a side channel. Uses WeakMap if available. + +Warning: in an environment that lacks `WeakMap`, this implementation will leak memory until you `delete` the `key`. + +## Getting started + +```sh +npm install --save side-channel +``` + +## Usage/Examples + +```js +const assert = require('assert'); +const getSideChannel = require('side-channel'); + +const channel = getSideChannel(); + +const key = {}; +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); + +channel.set(key, 42); + +channel.assert(key); // does not throw +assert.equal(channel.has(key), true); +assert.equal(channel.get(key), 42); + +channel.delete(key); +assert.equal(channel.has(key), false); +assert.throws(() => channel.assert(key), TypeError); +``` + +## Tests + +Clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/side-channel +[npm-version-svg]: https://versionbadg.es/ljharb/side-channel.svg +[deps-svg]: https://david-dm.org/ljharb/side-channel.svg +[deps-url]: https://david-dm.org/ljharb/side-channel +[dev-deps-svg]: https://david-dm.org/ljharb/side-channel/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/side-channel#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/side-channel.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/side-channel.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/side-channel.svg +[downloads-url]: https://npm-stat.com/charts.html?package=side-channel +[codecov-image]: https://codecov.io/gh/ljharb/side-channel/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/side-channel/ +[actions-image]: https://img.shields.io/github/check-runs/ljharb/side-channel/main +[actions-url]: https://github.com/ljharb/side-channel/actions diff --git a/node_modules/side-channel/index.d.ts b/node_modules/side-channel/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..18c63171cfd927fd9d4d69a89d2c360c81df67c6 --- /dev/null +++ b/node_modules/side-channel/index.d.ts @@ -0,0 +1,14 @@ +import getSideChannelList from 'side-channel-list'; +import getSideChannelMap from 'side-channel-map'; +import getSideChannelWeakMap from 'side-channel-weakmap'; + +declare namespace getSideChannel { + type Channel = + | getSideChannelList.Channel + | ReturnType, false>> + | ReturnType, false>>; +} + +declare function getSideChannel(): getSideChannel.Channel; + +export = getSideChannel; diff --git a/node_modules/side-channel/index.js b/node_modules/side-channel/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c5fe1fac336634e4879b5e216862f08ccf8af001 --- /dev/null +++ b/node_modules/side-channel/index.js @@ -0,0 +1,46 @@ +'use strict'; + +var $TypeError = require('es-errors/type'); +var inspect = require('object-inspect'); +var getSideChannelList = require('side-channel-list'); +var getSideChannelMap = require('side-channel-map'); +var getSideChannelWeakMap = require('side-channel-weakmap'); + +var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; + +/** @type {import('.')} */ +module.exports = function getSideChannel() { + /** @typedef {ReturnType} Channel */ + + /** @type {Channel | undefined} */ var $channelData; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + var keyDesc = key && Object(key) === key + ? 'the given object key' + : inspect(key); + throw new $TypeError('Side channel does not contain ' + keyDesc); + } + }, + 'delete': function (key) { + return !!$channelData && $channelData['delete'](key); + }, + get: function (key) { + return $channelData && $channelData.get(key); + }, + has: function (key) { + return !!$channelData && $channelData.has(key); + }, + set: function (key, value) { + if (!$channelData) { + $channelData = makeChannel(); + } + + $channelData.set(key, value); + } + }; + + return channel; +}; diff --git a/node_modules/side-channel/package.json b/node_modules/side-channel/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e39158e597ffc9bf60913b39a9170e5c154ec065 --- /dev/null +++ b/node_modules/side-channel/package.json @@ -0,0 +1,85 @@ +{ + "name": "side-channel", + "version": "1.1.1", + "description": "Store information about any JS value in a side channel. Uses WeakMap if available.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "./index.d.ts", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "eclint check $(git ls-files | xargs find 2> /dev/null | grep -vE 'node_modules|\\.git')", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/side-channel.git" + }, + "keywords": [ + "weakmap", + "map", + "side", + "channel", + "metadata" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/side-channel/issues" + }, + "homepage": "https://github.com/ljharb/side-channel#readme", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.18.3", + "@ljharb/eslint-config": "^22.2.3", + "@ljharb/tsconfig": "^0.3.2", + "@types/object-inspect": "^1.13.0", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.6.0", + "eclint": "^2.8.1", + "encoding": "^0.1.13", + "eslint": "^8.57.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/side-channel/test/index.js b/node_modules/side-channel/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5d28efd861e65d5cd7ad06eaff4fe0a64f0746e5 --- /dev/null +++ b/node_modules/side-channel/test/index.js @@ -0,0 +1,120 @@ +'use strict'; + +var test = require('tape'); + +var getSideChannel = require('../'); + +test('getSideChannel', function (t) { + t.test('export', function (st) { + st.equal(typeof getSideChannel, 'function', 'is a function'); + + st.equal(getSideChannel.length, 0, 'takes no arguments'); + + var channel = getSideChannel(); + st.ok(channel, 'is truthy'); + st.equal(typeof channel, 'object', 'is an object'); + st.end(); + }); + + t.test('assert', function (st) { + var channel = getSideChannel(); + st['throws']( + function () { channel.assert({}); }, + TypeError, + 'nonexistent value throws' + ); + + var o = {}; + channel.set(o, 'data'); + st.doesNotThrow(function () { channel.assert(o); }, 'existent value noops'); + + var accessed = false; + var trap = {}; + Object.defineProperty(trap, 'foo', { + enumerable: true, + get: function () { + accessed = true; + return 1; + } + }); + st['throws']( + function () { channel.assert(trap); }, + TypeError, + 'missing object key throws' + ); + st.equal(accessed, false, 'a missing object key is not observably accessed'); + + st.end(); + }); + + t.test('has', function (st) { + var channel = getSideChannel(); + /** @type {unknown[]} */ var o = []; + + st.equal(channel.has(o), false, 'nonexistent value yields false'); + + channel.set(o, 'foo'); + st.equal(channel.has(o), true, 'existent value yields true'); + + st.equal(channel.has('abc'), false, 'non object value non existent yields false'); + + channel.set('abc', 'foo'); + st.equal(channel.has('abc'), true, 'non object value that exists yields true'); + + st.end(); + }); + + t.test('get', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel.get(o), undefined, 'nonexistent value yields undefined'); + + var data = {}; + channel.set(o, data); + st.equal(channel.get(o), data, '"get" yields data set by "set"'); + + st.end(); + }); + + t.test('set', function (st) { + var channel = getSideChannel(); + var o = function () {}; + st.equal(channel.get(o), undefined, 'value not set'); + + channel.set(o, 42); + st.equal(channel.get(o), 42, 'value was set'); + + channel.set(o, Infinity); + st.equal(channel.get(o), Infinity, 'value was set again'); + + var o2 = {}; + channel.set(o2, 17); + st.equal(channel.get(o), Infinity, 'o is not modified'); + st.equal(channel.get(o2), 17, 'o2 is set'); + + channel.set(o, 14); + st.equal(channel.get(o), 14, 'o is modified'); + st.equal(channel.get(o2), 17, 'o2 is not modified'); + + st.end(); + }); + + t.test('delete', function (st) { + var channel = getSideChannel(); + var o = {}; + st.equal(channel['delete']({}), false, 'nonexistent value yields false'); + + channel.set(o, 42); + st.equal(channel.has(o), true, 'value is set'); + + st.equal(channel['delete']({}), false, 'nonexistent value still yields false'); + + st.equal(channel['delete'](o), true, 'deleted value yields true'); + + st.equal(channel.has(o), false, 'value is no longer set'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/side-channel/tsconfig.json b/node_modules/side-channel/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d9a6668c3ae6be748c78fbd5694053706b3d6942 --- /dev/null +++ b/node_modules/side-channel/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/siginfo/.travis.yml b/node_modules/siginfo/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..4f54568c078cb484fb8e3f258fceb8b4f4a96252 --- /dev/null +++ b/node_modules/siginfo/.travis.yml @@ -0,0 +1,13 @@ +notifications: + email: false +language: node_js +node_js: +- node +deploy: + provider: npm + email: + secure: Y10Dvn9UbfpZPbulnl/e7dsiN/1xr06h7k6nJZyxRzr9Hh0UUFPism6k5CFaSegyPIF7sODNBQz4lvXIi2NwcvTLQruw5ehXW0NJ/G7x1TU94pzzhVJ31KBlRWzjKdvVTDsDzFxe5wKWxagPUTkieiIN9CWTQjafByNs3zbK8HL7cmu4Nc42JquVGbtpGgLs7Js+tY+WVB1dMQ4SfqpFgWjm2h05uyXCWHLK5amEAZJLP755lOVgMzw/jQGRg7J4vX4+eRE0r/g0v09x9FUU3ROEmJvqYa14CmGESRhSUyRlv4pnMIs/aK8ZDD8ia3eoTSvMJv8mzdvpkvKzWV1HSZFUX3QZVgWJEmeoF6XP+mdkWu5gnZVlOIBc8NANcS60Dr8QwF470xpPxsyAyf2o9UzX8Xy2qO8XNY/TykGO4soCfOEuVNdw5F9hHEldMHY8p9Z8EJSCn/xfM//LEvxRKREYsMqFtsnwUsv+qiAkHPSHXWQo6HYp+/xDchv63NxtjGHdPs9VpUFr1F8CxZjdis2HZfOnx51W0JIwNYlXNxeqC3WjRUqvRp2NknS982lRHCkHtZfHijGvMm7kj3QL+Ufc7pIfEGnMAKKiNv9kOryjQc29046pRZww9lWjrhoCeEPRhFbkgFV7Mo3bvOExstsSdRnOTlogCe4NviKOwfE= + api_key: + secure: cAmf8extX/sPl+sxC/6sWTmaiSGrXQY9C/lLg9c76Qn12MLysxDYgCRXfl8Az3RIbRuajq0SbyWXeDa/4wZc1PazuUGjZG82na+kuEDg8m5z0gLiJlhp60C0nj3WMJaRBRsOha1Jbs59eU3XNy+H0U5VczHrdw6v2yCHTlauhT/NYiPXMyKmTIJPB/X7gryFuXVhCPNdRBp3rPicbt0d68J+vWv9KNpjA1WB0WDUSl5rMUQbjjsRF2/DKj9WxXjmci+ac+/pCN3rQxgYZ0Ot5o5/RcWucc21ZdFgsLo8dq5YZDl/EQf/pPmkhquiiLRhiTyCBbEw1sDzYHTbTJThrukrZALg0on7XvxbXSQrxgc/IMJ/RT0PoGLEqyAZUSzGa6HPVlHUBt4LB3zgrswGmGUVkZmbiag0foIFeCKlydwEyBYfnFdRddxF6n3irft1l1NJ1HKNxKLnKvyt8iaOlGteXOOfLXzU17DgMgwTsZsvFmtFQcs6yolLHW9RnRTLf56+x/kJZ4kVJjHuyb/98pS4F7etJ2SpZqt1cVUFd/AYtnxL3jKiUhJLNL8hNUIH3eSpMfZUOUxGv1OWuwgyEhSONkITF2VPn4yuyxS23Ewq4LLj/u/9sPlLaGSN4Avaw21gi6L+M9x620sTZHYtNLniVMTAu6aPiM32zPreK2I= + on: + tags: true diff --git a/node_modules/siginfo/LICENSE b/node_modules/siginfo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b45703b88a6742577786fa46c73b018dbe75cf26 --- /dev/null +++ b/node_modules/siginfo/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2017, Emil Bay + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/siginfo/README.md b/node_modules/siginfo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3552e2ad95f08f009f8fc6c495d299ddc8ae790e --- /dev/null +++ b/node_modules/siginfo/README.md @@ -0,0 +1,47 @@ +# `siginfo` + +[![Build Status](https://travis-ci.org/emilbayes/siginfo.svg?branch=master)](https://travis-ci.org/eemilbayes/siginfo) + +> Utility module to print pretty messages on SIGINFO/SIGUSR1 + +`SIGINFO` on BSD / macOS and `SIGUSR1` on Linux, usually triggered by +`Ctrl + T`, are by convention used to print information about +a long running process internal state. Eg. `dd` will tell you how many blocks it +has written and at what speed, while `xz` will tell you progress, compression +ratio and estimated time remaining. + +This module wraps both signals, checks if the process is connected to TTY and +lets you do whatever you want. + +## Usage + +```js +var siginfo = require('siginfo') +var pkg = require('./package.json') + +siginfo(function () { + console.dir({ + version: pkg.version, + uptime: process.uptime() + }) +}) + +``` + +## API + +### `var removeListener = siginfo(queryFn, [force])` + +`queryFn` can be used for whatever you want (logging, sending a UDP message, etc.). +Setting `force = true` will attach the event handlers whether a TTY is present +or not. + +## Install + +```sh +npm install siginfo +``` + +## License + +[ISC](LICENSE) diff --git a/node_modules/siginfo/index.js b/node_modules/siginfo/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5092b6115d70e97ec511c1ed98e622f83eef9925 --- /dev/null +++ b/node_modules/siginfo/index.js @@ -0,0 +1,20 @@ +module.exports = function (query, force) { + var isAttached = false + if (process.stderr.isTTY || force === true) { + isAttached = true + process.on('SIGINFO', onsiginfo) + process.on('SIGUSR1', onsiginfo) + } + + return function () { + if (isAttached === true) { + process.removeListener('SIGINFO', onsiginfo) + process.removeListener('SIGUSR1', onsiginfo) + isAttached = false + } + } + + function onsiginfo () { + query() + } +} diff --git a/node_modules/siginfo/package.json b/node_modules/siginfo/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4f0e7154346583f6d5df9c690ef0abc76531e6dc --- /dev/null +++ b/node_modules/siginfo/package.json @@ -0,0 +1,32 @@ +{ + "name": "siginfo", + "version": "2.0.0", + "description": "Utility module to print pretty messages on SIGINFO/SIGUSR1", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "standard": "^14.3.4" + }, + "scripts": { + "test": "standard" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/emilbayes/siginfo.git" + }, + "keywords": [ + "siginfo", + "sigusr1", + "ctrl", + "t", + "info", + "progress", + "inspect" + ], + "author": "Emil Bay ", + "license": "ISC", + "bugs": { + "url": "https://github.com/emilbayes/siginfo/issues" + }, + "homepage": "https://github.com/emilbayes/siginfo#readme" +} diff --git a/node_modules/siginfo/test.js b/node_modules/siginfo/test.js new file mode 100644 index 0000000000000000000000000000000000000000..eaf6824f64e295ce5ff64a08fcc316fc9524ed9d --- /dev/null +++ b/node_modules/siginfo/test.js @@ -0,0 +1,16 @@ +var siginfo = require('.') +var pkg = require('./package.json') + +var stop = siginfo(function () { + console.dir({ + version: pkg.version, + uptime: process.uptime() + }) +}) + +process.stdout.resume() + +setTimeout(function () { + stop() + process.exit(0) +}, 2000) diff --git a/node_modules/signal-exit/LICENSE.txt b/node_modules/signal-exit/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..954f2fa8235009998fe29a775bbaf8c23f5e2d50 --- /dev/null +++ b/node_modules/signal-exit/LICENSE.txt @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) 2015-2023 Benjamin Coe, Isaac Z. Schlueter, and Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/signal-exit/README.md b/node_modules/signal-exit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c55cd45ee316e8025759f5da2a124446814cc387 --- /dev/null +++ b/node_modules/signal-exit/README.md @@ -0,0 +1,74 @@ +# signal-exit + +When you want to fire an event no matter how a process exits: + +- reaching the end of execution. +- explicitly having `process.exit(code)` called. +- having `process.kill(pid, sig)` called. +- receiving a fatal signal from outside the process + +Use `signal-exit`. + +```js +// Hybrid module, either works +import { onExit } from 'signal-exit' +// or: +// const { onExit } = require('signal-exit') + +onExit((code, signal) => { + console.log('process exited!', code, signal) +}) +``` + +## API + +`remove = onExit((code, signal) => {}, options)` + +The return value of the function is a function that will remove +the handler. + +Note that the function _only_ fires for signals if the signal +would cause the process to exit. That is, there are no other +listeners, and it is a fatal signal. + +If the global `process` object is not suitable for this purpose +(ie, it's unset, or doesn't have an `emit` method, etc.) then the +`onExit` function is a no-op that returns a no-op `remove` method. + +### Options + +- `alwaysLast`: Run this handler after any other signal or exit + handlers. This causes `process.emit` to be monkeypatched. + +### Capturing Signal Exits + +If the handler returns an exact boolean `true`, and the exit is a +due to signal, then the signal will be considered handled, and +will _not_ trigger a synthetic `process.kill(process.pid, +signal)` after firing the `onExit` handlers. + +In this case, it your responsibility as the caller to exit with a +signal (for example, by calling `process.kill()`) if you wish to +preserve the same exit status that would otherwise have occurred. +If you do not, then the process will likely exit gracefully with +status 0 at some point, assuming that no other terminating signal +or other exit trigger occurs. + +Prior to calling handlers, the `onExit` machinery is unloaded, so +any subsequent exits or signals will not be handled, even if the +signal is captured and the exit is thus prevented. + +Note that numeric code exits may indicate that the process is +already committed to exiting, for example due to a fatal +exception or unhandled promise rejection, and so there is no way to +prevent it safely. + +### Browser Fallback + +The `'signal-exit/browser'` module is the same fallback shim that +just doesn't do anything, but presents the same function +interface. + +Patches welcome to add something that hooks onto +`window.onbeforeunload` or similar, but it might just not be a +thing that makes sense there. diff --git a/node_modules/signal-exit/package.json b/node_modules/signal-exit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ac176cec743748840fdb8f143beb60bf47e599ac --- /dev/null +++ b/node_modules/signal-exit/package.json @@ -0,0 +1,106 @@ +{ + "name": "signal-exit", + "version": "4.1.0", + "description": "when you want to fire an event no matter how a process exits.", + "main": "./dist/cjs/index.js", + "module": "./dist/mjs/index.js", + "browser": "./dist/mjs/browser.js", + "types": "./dist/mjs/index.d.ts", + "exports": { + ".": { + "import": { + "types": "./dist/mjs/index.d.ts", + "default": "./dist/mjs/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.ts", + "default": "./dist/cjs/index.js" + } + }, + "./signals": { + "import": { + "types": "./dist/mjs/signals.d.ts", + "default": "./dist/mjs/signals.js" + }, + "require": { + "types": "./dist/cjs/signals.d.ts", + "default": "./dist/cjs/signals.js" + } + }, + "./browser": { + "import": { + "types": "./dist/mjs/browser.d.ts", + "default": "./dist/mjs/browser.js" + }, + "require": { + "types": "./dist/cjs/browser.d.ts", + "default": "./dist/cjs/browser.js" + } + } + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=14" + }, + "repository": { + "type": "git", + "url": "https://github.com/tapjs/signal-exit.git" + }, + "keywords": [ + "signal", + "exit" + ], + "author": "Ben Coe ", + "license": "ISC", + "devDependencies": { + "@types/cross-spawn": "^6.0.2", + "@types/node": "^18.15.11", + "@types/signal-exit": "^3.0.1", + "@types/tap": "^15.0.8", + "c8": "^7.13.0", + "prettier": "^2.8.6", + "tap": "^16.3.4", + "ts-node": "^10.9.1", + "typedoc": "^0.23.28", + "typescript": "^5.0.2" + }, + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags", + "preprepare": "rm -rf dist", + "prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json && bash ./scripts/fixup.sh", + "pretest": "npm run prepare", + "presnap": "npm run prepare", + "test": "c8 tap", + "snap": "c8 tap", + "format": "prettier --write . --loglevel warn", + "typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts" + }, + "prettier": { + "semi": false, + "printWidth": 75, + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "jsxSingleQuote": false, + "bracketSameLine": true, + "arrowParens": "avoid", + "endOfLine": "lf" + }, + "tap": { + "coverage": false, + "jobs": 1, + "node-arg": [ + "--no-warnings", + "--loader", + "ts-node/esm" + ], + "ts": false + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } +} diff --git a/node_modules/simple-concat/.travis.yml b/node_modules/simple-concat/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..c159f6acecab74f3b3ec5c09a970e9f3c226e667 --- /dev/null +++ b/node_modules/simple-concat/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - lts/* diff --git a/node_modules/simple-concat/LICENSE b/node_modules/simple-concat/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c7e6852752b72edbf0eb6b2adef53f0863ae5876 --- /dev/null +++ b/node_modules/simple-concat/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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. diff --git a/node_modules/simple-concat/README.md b/node_modules/simple-concat/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b7d39bdea998f5dc6ad2c3d9637586eb453a87b3 --- /dev/null +++ b/node_modules/simple-concat/README.md @@ -0,0 +1,44 @@ +# simple-concat [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/simple-concat/master.svg +[travis-url]: https://travis-ci.org/feross/simple-concat +[npm-image]: https://img.shields.io/npm/v/simple-concat.svg +[npm-url]: https://npmjs.org/package/simple-concat +[downloads-image]: https://img.shields.io/npm/dm/simple-concat.svg +[downloads-url]: https://npmjs.org/package/simple-concat +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +### Super-minimalist version of [`concat-stream`](https://github.com/maxogden/concat-stream). Less than 15 lines! + +## install + +``` +npm install simple-concat +``` + +## usage + +This example is longer than the implementation. + +```js +var s = new stream.PassThrough() +concat(s, function (err, buf) { + if (err) throw err + console.error(buf) +}) +s.write('abc') +setTimeout(function () { + s.write('123') +}, 10) +setTimeout(function () { + s.write('456') +}, 20) +setTimeout(function () { + s.end('789') +}, 30) +``` + +## license + +MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). diff --git a/node_modules/simple-concat/index.js b/node_modules/simple-concat/index.js new file mode 100644 index 0000000000000000000000000000000000000000..59237fc6284738fdb149b4c4a9be0e123711a295 --- /dev/null +++ b/node_modules/simple-concat/index.js @@ -0,0 +1,15 @@ +/*! simple-concat. MIT License. Feross Aboukhadijeh */ +module.exports = function (stream, cb) { + var chunks = [] + stream.on('data', function (chunk) { + chunks.push(chunk) + }) + stream.once('end', function () { + if (cb) cb(null, Buffer.concat(chunks)) + cb = null + }) + stream.once('error', function (err) { + if (cb) cb(err) + cb = null + }) +} diff --git a/node_modules/simple-concat/package.json b/node_modules/simple-concat/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2bb2c60a2f9e995a7e3d5c94a9c93290ba047aea --- /dev/null +++ b/node_modules/simple-concat/package.json @@ -0,0 +1,47 @@ +{ + "name": "simple-concat", + "description": "Super-minimalist version of `concat-stream`. Less than 15 lines!", + "version": "1.0.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/simple-concat/issues" + }, + "dependencies": {}, + "devDependencies": { + "standard": "*", + "tape": "^5.0.1" + }, + "homepage": "https://github.com/feross/simple-concat", + "keywords": [ + "concat", + "concat-stream", + "concat stream" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/feross/simple-concat.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/simple-concat/test/basic.js b/node_modules/simple-concat/test/basic.js new file mode 100644 index 0000000000000000000000000000000000000000..4bf6f9c2d9d82844996f27791e73defb2c66933e --- /dev/null +++ b/node_modules/simple-concat/test/basic.js @@ -0,0 +1,41 @@ +var concat = require('../') +var stream = require('stream') +var test = require('tape') + +test('basic', function (t) { + t.plan(2) + var s = new stream.PassThrough() + concat(s, function (err, buf) { + t.error(err) + t.deepEqual(buf, Buffer.from('abc123456789')) + }) + s.write('abc') + setTimeout(function () { + s.write('123') + }, 10) + setTimeout(function () { + s.write('456') + }, 20) + setTimeout(function () { + s.end('789') + }, 30) +}) + +test('error', function (t) { + t.plan(2) + var s = new stream.PassThrough() + concat(s, function (err, buf) { + t.ok(err, 'got expected error') + t.ok(!buf) + }) + s.write('abc') + setTimeout(function () { + s.write('123') + }, 10) + setTimeout(function () { + s.write('456') + }, 20) + setTimeout(function () { + s.emit('error', new Error('error')) + }, 30) +}) diff --git a/node_modules/simple-get/.github/dependabot.yml b/node_modules/simple-get/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..0221fbcbc3977776e0c6d60f760fbe147f2e81e5 --- /dev/null +++ b/node_modules/simple-get/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 +updates: + - package-ecosystem: npm + directory: / + schedule: + interval: daily + labels: + - dependency + versioning-strategy: increase-if-necessary + - package-ecosystem: github-actions + directory: / + schedule: + interval: daily + labels: + - dependency diff --git a/node_modules/simple-get/.github/workflows/ci.yml b/node_modules/simple-get/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..822d21cc9d5264b5439f9bfaea12f0e162064cc3 --- /dev/null +++ b/node_modules/simple-get/.github/workflows/ci.yml @@ -0,0 +1,23 @@ +name: ci +'on': + - push + - pull_request +jobs: + test: + name: Node ${{ matrix.node }} / ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: + - ubuntu-latest + node: + - '14' + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-node@v2 + with: + node-version: ${{ matrix.node }} + - run: npm install + - run: npm run build --if-present + - run: npm test diff --git a/node_modules/simple-get/LICENSE b/node_modules/simple-get/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c7e6852752b72edbf0eb6b2adef53f0863ae5876 --- /dev/null +++ b/node_modules/simple-get/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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. diff --git a/node_modules/simple-get/README.md b/node_modules/simple-get/README.md new file mode 100644 index 0000000000000000000000000000000000000000..63c6a6bae8888b6749dcc0fab06816e16ee5d485 --- /dev/null +++ b/node_modules/simple-get/README.md @@ -0,0 +1,333 @@ +# simple-get [![ci][ci-image]][ci-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[ci-image]: https://img.shields.io/github/workflow/status/feross/simple-get/ci/master +[ci-url]: https://github.com/feross/simple-get/actions +[npm-image]: https://img.shields.io/npm/v/simple-get.svg +[npm-url]: https://npmjs.org/package/simple-get +[downloads-image]: https://img.shields.io/npm/dm/simple-get.svg +[downloads-url]: https://npmjs.org/package/simple-get +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +### Simplest way to make http get requests + +## features + +This module is the lightest possible wrapper on top of node.js `http`, but supporting these essential features: + +- follows redirects +- automatically handles gzip/deflate responses +- supports HTTPS +- supports specifying a timeout +- supports convenience `url` key so there's no need to use `url.parse` on the url when specifying options +- composes well with npm packages for features like cookies, proxies, form data, & OAuth + +All this in < 100 lines of code. + +## install + +``` +npm install simple-get +``` + +## usage + +Note, all these examples also work in the browser with [browserify](http://browserify.org/). + +### simple GET request + +Doesn't get easier than this: + +```js +const get = require('simple-get') + +get('http://example.com', function (err, res) { + if (err) throw err + console.log(res.statusCode) // 200 + res.pipe(process.stdout) // `res` is a stream +}) +``` + +### even simpler GET request + +If you just want the data, and don't want to deal with streams: + +```js +const get = require('simple-get') + +get.concat('http://example.com', function (err, res, data) { + if (err) throw err + console.log(res.statusCode) // 200 + console.log(data) // Buffer('this is the server response') +}) +``` + +### POST, PUT, PATCH, HEAD, DELETE support + +For `POST`, call `get.post` or use option `{ method: 'POST' }`. + +```js +const get = require('simple-get') + +const opts = { + url: 'http://example.com', + body: 'this is the POST body' +} +get.post(opts, function (err, res) { + if (err) throw err + res.pipe(process.stdout) // `res` is a stream +}) +``` + +#### A more complex example: + +```js +const get = require('simple-get') + +get({ + url: 'http://example.com', + method: 'POST', + body: 'this is the POST body', + + // simple-get accepts all options that node.js `http` accepts + // See: http://nodejs.org/api/http.html#http_http_request_options_callback + headers: { + 'user-agent': 'my cool app' + } +}, function (err, res) { + if (err) throw err + + // All properties/methods from http.IncomingResponse are available, + // even if a gunzip/inflate transform stream was returned. + // See: http://nodejs.org/api/http.html#http_http_incomingmessage + res.setTimeout(10000) + console.log(res.headers) + + res.on('data', function (chunk) { + // `chunk` is the decoded response, after it's been gunzipped or inflated + // (if applicable) + console.log('got a chunk of the response: ' + chunk) + })) + +}) +``` + +### JSON + +You can serialize/deserialize request and response with JSON: + +```js +const get = require('simple-get') + +const opts = { + method: 'POST', + url: 'http://example.com', + body: { + key: 'value' + }, + json: true +} +get.concat(opts, function (err, res, data) { + if (err) throw err + console.log(data.key) // `data` is an object +}) +``` + +### Timeout + +You can set a timeout (in milliseconds) on the request with the `timeout` option. +If the request takes longer than `timeout` to complete, then the entire request +will fail with an `Error`. + +```js +const get = require('simple-get') + +const opts = { + url: 'http://example.com', + timeout: 2000 // 2 second timeout +} + +get(opts, function (err, res) {}) +``` + +### One Quick Tip + +It's a good idea to set the `'user-agent'` header so the provider can more easily +see how their resource is used. + +```js +const get = require('simple-get') +const pkg = require('./package.json') + +get('http://example.com', { + headers: { + 'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)` + } +}) +``` + +### Proxies + +You can use the [`tunnel`](https://github.com/koichik/node-tunnel) module with the +`agent` option to work with proxies: + +```js +const get = require('simple-get') +const tunnel = require('tunnel') + +const opts = { + url: 'http://example.com', + agent: tunnel.httpOverHttp({ + proxy: { + host: 'localhost' + } + }) +} + +get(opts, function (err, res) {}) +``` + +### Cookies + +You can use the [`cookie`](https://github.com/jshttp/cookie) module to include +cookies in a request: + +```js +const get = require('simple-get') +const cookie = require('cookie') + +const opts = { + url: 'http://example.com', + headers: { + cookie: cookie.serialize('foo', 'bar') + } +} + +get(opts, function (err, res) {}) +``` + +### Form data + +You can use the [`form-data`](https://github.com/form-data/form-data) module to +create POST request with form data: + +```js +const fs = require('fs') +const get = require('simple-get') +const FormData = require('form-data') +const form = new FormData() + +form.append('my_file', fs.createReadStream('/foo/bar.jpg')) + +const opts = { + url: 'http://example.com', + body: form +} + +get.post(opts, function (err, res) {}) +``` + +#### Or, include `application/x-www-form-urlencoded` form data manually: + +```js +const get = require('simple-get') + +const opts = { + url: 'http://example.com', + form: { + key: 'value' + } +} +get.post(opts, function (err, res) {}) +``` + +### Specifically disallowing redirects + +```js +const get = require('simple-get') + +const opts = { + url: 'http://example.com/will-redirect-elsewhere', + followRedirects: false +} +// res.statusCode will be 301, no error thrown +get(opts, function (err, res) {}) +``` + +### Basic Auth + +```js +const user = 'someuser' +const pass = 'pa$$word' +const encodedAuth = Buffer.from(`${user}:${pass}`).toString('base64') + +get('http://example.com', { + headers: { + authorization: `Basic ${encodedAuth}` + } +}) +``` + +### OAuth + +You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) module to create +a signed OAuth request: + +```js +const get = require('simple-get') +const crypto = require('crypto') +const OAuth = require('oauth-1.0a') + +const oauth = OAuth({ + consumer: { + key: process.env.CONSUMER_KEY, + secret: process.env.CONSUMER_SECRET + }, + signature_method: 'HMAC-SHA1', + hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64') +}) + +const token = { + key: process.env.ACCESS_TOKEN, + secret: process.env.ACCESS_TOKEN_SECRET +} + +const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json' + +const opts = { + url: url, + headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)), + json: true +} + +get(opts, function (err, res) {}) +``` + +### Throttle requests + +You can use [limiter](https://github.com/jhurliman/node-rate-limiter) to throttle requests. This is useful when calling an API that is rate limited. + +```js +const simpleGet = require('simple-get') +const RateLimiter = require('limiter').RateLimiter +const limiter = new RateLimiter(1, 'second') + +const get = (opts, cb) => limiter.removeTokens(1, () => simpleGet(opts, cb)) +get.concat = (opts, cb) => limiter.removeTokens(1, () => simpleGet.concat(opts, cb)) + +var opts = { + url: 'http://example.com' +} + +get.concat(opts, processResult) +get.concat(opts, processResult) + +function processResult (err, res, data) { + if (err) throw err + console.log(data.toString()) +} +``` + +## license + +MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org). diff --git a/node_modules/simple-get/index.js b/node_modules/simple-get/index.js new file mode 100644 index 0000000000000000000000000000000000000000..80e52e8ccade8e92c290462ae404a7ce70a937f1 --- /dev/null +++ b/node_modules/simple-get/index.js @@ -0,0 +1,108 @@ +/*! simple-get. MIT License. Feross Aboukhadijeh */ +module.exports = simpleGet + +const concat = require('simple-concat') +const decompressResponse = require('decompress-response') // excluded from browser build +const http = require('http') +const https = require('https') +const once = require('once') +const querystring = require('querystring') +const url = require('url') + +const isStream = o => o !== null && typeof o === 'object' && typeof o.pipe === 'function' + +function simpleGet (opts, cb) { + opts = Object.assign({ maxRedirects: 10 }, typeof opts === 'string' ? { url: opts } : opts) + cb = once(cb) + + if (opts.url) { + const { hostname, port, protocol, auth, path } = url.parse(opts.url) // eslint-disable-line node/no-deprecated-api + delete opts.url + if (!hostname && !port && !protocol && !auth) opts.path = path // Relative redirect + else Object.assign(opts, { hostname, port, protocol, auth, path }) // Absolute redirect + } + + const headers = { 'accept-encoding': 'gzip, deflate' } + if (opts.headers) Object.keys(opts.headers).forEach(k => (headers[k.toLowerCase()] = opts.headers[k])) + opts.headers = headers + + let body + if (opts.body) { + body = opts.json && !isStream(opts.body) ? JSON.stringify(opts.body) : opts.body + } else if (opts.form) { + body = typeof opts.form === 'string' ? opts.form : querystring.stringify(opts.form) + opts.headers['content-type'] = 'application/x-www-form-urlencoded' + } + + if (body) { + if (!opts.method) opts.method = 'POST' + if (!isStream(body)) opts.headers['content-length'] = Buffer.byteLength(body) + if (opts.json && !opts.form) opts.headers['content-type'] = 'application/json' + } + delete opts.body; delete opts.form + + if (opts.json) opts.headers.accept = 'application/json' + if (opts.method) opts.method = opts.method.toUpperCase() + + const originalHost = opts.hostname // hostname before potential redirect + const protocol = opts.protocol === 'https:' ? https : http // Support http/https urls + const req = protocol.request(opts, res => { + if (opts.followRedirects !== false && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + opts.url = res.headers.location // Follow 3xx redirects + delete opts.headers.host // Discard `host` header on redirect (see #32) + res.resume() // Discard response + + const redirectHost = url.parse(opts.url).hostname // eslint-disable-line node/no-deprecated-api + // If redirected host is different than original host, drop headers to prevent cookie leak (#73) + if (redirectHost !== null && redirectHost !== originalHost) { + delete opts.headers.cookie + delete opts.headers.authorization + } + + if (opts.method === 'POST' && [301, 302].includes(res.statusCode)) { + opts.method = 'GET' // On 301/302 redirect, change POST to GET (see #35) + delete opts.headers['content-length']; delete opts.headers['content-type'] + } + + if (opts.maxRedirects-- === 0) return cb(new Error('too many redirects')) + else return simpleGet(opts, cb) + } + + const tryUnzip = typeof decompressResponse === 'function' && opts.method !== 'HEAD' + cb(null, tryUnzip ? decompressResponse(res) : res) + }) + req.on('timeout', () => { + req.abort() + cb(new Error('Request timed out')) + }) + req.on('error', cb) + + if (isStream(body)) body.on('error', cb).pipe(req) + else req.end(body) + + return req +} + +simpleGet.concat = (opts, cb) => { + return simpleGet(opts, (err, res) => { + if (err) return cb(err) + concat(res, (err, data) => { + if (err) return cb(err) + if (opts.json) { + try { + data = JSON.parse(data.toString()) + } catch (err) { + return cb(err, res, data) + } + } + cb(null, res, data) + }) + }) +} + +;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(method => { + simpleGet[method] = (opts, cb) => { + if (typeof opts === 'string') opts = { url: opts } + return simpleGet(Object.assign({ method: method.toUpperCase() }, opts), cb) + } +}) diff --git a/node_modules/simple-get/package.json b/node_modules/simple-get/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e80fc5eb315786b6f7410be415256000977f8fe9 --- /dev/null +++ b/node_modules/simple-get/package.json @@ -0,0 +1,67 @@ +{ + "name": "simple-get", + "description": "Simplest way to make http get requests. Supports HTTPS, redirects, gzip/deflate, streams in < 100 lines.", + "version": "4.0.1", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "https://feross.org" + }, + "browser": { + "decompress-response": false + }, + "bugs": { + "url": "https://github.com/feross/simple-get/issues" + }, + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" + }, + "devDependencies": { + "self-signed-https": "^1.0.5", + "standard": "*", + "string-to-stream": "^3.0.0", + "tape": "^5.0.0" + }, + "homepage": "https://github.com/feross/simple-get", + "keywords": [ + "request", + "http", + "GET", + "get request", + "http.get", + "redirects", + "follow redirects", + "gzip", + "deflate", + "https", + "http-https", + "stream", + "simple request", + "simple get" + ], + "license": "MIT", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/feross/simple-get.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] +} diff --git a/node_modules/simple-swizzle/LICENSE b/node_modules/simple-swizzle/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1b77e5bee18c116aa8df433809effc03a8971ac8 --- /dev/null +++ b/node_modules/simple-swizzle/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Josh Junon + +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. diff --git a/node_modules/simple-swizzle/README.md b/node_modules/simple-swizzle/README.md new file mode 100644 index 0000000000000000000000000000000000000000..299fedf048f2476c407e2dde4749c8ff12f23c8b --- /dev/null +++ b/node_modules/simple-swizzle/README.md @@ -0,0 +1,43 @@ +> **NOTE:** ⚠️ **Don't use this package in new projects.** It is a **huge anti-pattern** and will only confuse and annoy people who use whatever code you write with it. I wrote this in a time when Javascript and Node.js were still pretty experimental and clever things like this weren't frowned upon. I've also learned a LOT about proper API design since I wrote this package. DO. NOT. USE. THIS. PACKAGE. If you're reaching for it, please *really* reconsider your API's design. + +--- + +# simple-swizzle [![Travis-CI.org Build Status](https://img.shields.io/travis/Qix-/node-simple-swizzle.svg?style=flat-square)](https://travis-ci.org/Qix-/node-simple-swizzle) [![Coveralls.io Coverage Rating](https://img.shields.io/coveralls/Qix-/node-simple-swizzle.svg?style=flat-square)](https://coveralls.io/r/Qix-/node-simple-swizzle) + +> [Swizzle](https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)) your function arguments; pass in mixed arrays/values and get a clean array + +## Usage + +```js +var swizzle = require('simple-swizzle'); + +function myFunc() { + var args = swizzle(arguments); + // ... + return args; +} + +myFunc(1, [2, 3], 4); // [1, 2, 3, 4] +myFunc(1, 2, 3, 4); // [1, 2, 3, 4] +myFunc([1, 2, 3, 4]); // [1, 2, 3, 4] +``` + +Functions can also be wrapped to automatically swizzle arguments and be passed +the resulting array. + +```js +var swizzle = require('simple-swizzle'); + +var swizzledFn = swizzle.wrap(function (args) { + // ... + return args; +}); + +swizzledFn(1, [2, 3], 4); // [1, 2, 3, 4] +swizzledFn(1, 2, 3, 4); // [1, 2, 3, 4] +swizzledFn([1, 2, 3, 4]); // [1, 2, 3, 4] +``` + +## License +Licensed under the [MIT License](http://opensource.org/licenses/MIT). +You can find a copy of it in [LICENSE](LICENSE). diff --git a/node_modules/simple-swizzle/index.js b/node_modules/simple-swizzle/index.js new file mode 100644 index 0000000000000000000000000000000000000000..4d6b8ff7eb7ad8a654c49dc66c2a9098571a6f34 --- /dev/null +++ b/node_modules/simple-swizzle/index.js @@ -0,0 +1,29 @@ +'use strict'; + +var isArrayish = require('is-arrayish'); + +var concat = Array.prototype.concat; +var slice = Array.prototype.slice; + +var swizzle = module.exports = function swizzle(args) { + var results = []; + + for (var i = 0, len = args.length; i < len; i++) { + var arg = args[i]; + + if (isArrayish(arg)) { + // http://jsperf.com/javascript-array-concat-vs-push/98 + results = concat.call(results, slice.call(arg)); + } else { + results.push(arg); + } + } + + return results; +}; + +swizzle.wrap = function (fn) { + return function () { + return fn(swizzle(arguments)); + }; +}; diff --git a/node_modules/simple-swizzle/package.json b/node_modules/simple-swizzle/package.json new file mode 100644 index 0000000000000000000000000000000000000000..82c8218c8326007546565c8488538d4daf5c07bf --- /dev/null +++ b/node_modules/simple-swizzle/package.json @@ -0,0 +1,36 @@ +{ + "name": "simple-swizzle", + "description": "Simply swizzle your arguments", + "version": "0.2.4", + "author": "Qix (http://github.com/qix-)", + "keywords": [ + "argument", + "arguments", + "swizzle", + "swizzling", + "parameter", + "parameters", + "mixed", + "array" + ], + "license": "MIT", + "scripts": { + "pretest": "xo", + "test": "mocha --compilers coffee:coffee-script/register" + }, + "files": [ + "index.js" + ], + "repository": "qix-/node-simple-swizzle", + "devDependencies": { + "coffee-script": "^1.9.3", + "coveralls": "^2.11.2", + "istanbul": "^0.3.17", + "mocha": "^2.2.5", + "should": "^7.0.1", + "xo": "^0.7.1" + }, + "dependencies": { + "is-arrayish": "^0.3.1" + } +} diff --git a/node_modules/simple-update-notifier/LICENSE b/node_modules/simple-update-notifier/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..1e0b0c116923cb899cb0ebc49528551dde1f6ab9 --- /dev/null +++ b/node_modules/simple-update-notifier/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Alex Brazier + +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. diff --git a/node_modules/simple-update-notifier/README.md b/node_modules/simple-update-notifier/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ec177944638c4be4d4d8cf639d00bab0cc774acc --- /dev/null +++ b/node_modules/simple-update-notifier/README.md @@ -0,0 +1,82 @@ +# simple-update-notifier [![GitHub stars](https://img.shields.io/github/stars/alexbrazier/simple-update-notifier?label=Star%20Project&style=social)](https://github.com/alexbrazier/simple-update-notifier/stargazers) + +[![CI](https://github.com/alexbrazier/simple-update-notifier/workflows/Build%20and%20Deploy/badge.svg)](https://github.com/alexbrazier/simple-update-notifier/actions) +[![Dependencies](https://img.shields.io/librariesio/release/npm/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier?activeTab=dependencies) +[![npm](https://img.shields.io/npm/v/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier) +[![npm bundle size](https://img.shields.io/bundlephobia/min/simple-update-notifier)](https://bundlephobia.com/result?p=simple-update-notifier) +[![npm downloads](https://img.shields.io/npm/dw/simple-update-notifier)](https://www.npmjs.com/package/simple-update-notifier) +[![License](https://img.shields.io/npm/l/simple-update-notifier)](./LICENSE) + +Simple update notifier to check for npm updates for cli applications. + +Demo in terminal showing an update is required + +Checks for updates for an npm module and outputs to the command line if there is one available. The result is cached for the specified time so it doesn't check every time the app runs. + +## Install + +```bash +npm install simple-update-notifier +OR +yarn add simple-update-notifier +``` + +## Usage + +```js +import updateNotifier from 'simple-update-notifier'; +import packageJson from './package.json' assert { type: 'json' }; + +updateNotifier({ pkg: packageJson }); +``` + +### Options + +#### pkg + +Type: `object` + +##### name + +_Required_\ +Type: `string` + +##### version + +_Required_\ +Type: `string` + +#### updateCheckInterval + +Type: `number`\ +Default: `1000 * 60 * 60 * 24` _(1 day)_ + +How often to check for updates. + +#### shouldNotifyInNpmScript + +Type: `boolean`\ +Default: `false` + +Allows notification to be shown when running as an npm script. + +#### distTag + +Type: `string`\ +Default: `'latest'` + +Which [dist-tag](https://docs.npmjs.com/adding-dist-tags-to-packages) to use to find the latest version. + +#### alwaysRun + +Type: `boolean`\ +Default: `false` + +When set, `updateCheckInterval` will not be respected and a check for an update will always be performed. + +#### debug + +Type: `boolean`\ +Default: `false` + +When set, logs explaining the decision will be output to `stderr` whenever the module opts to not print an update notification diff --git a/node_modules/simple-update-notifier/build/index.d.ts b/node_modules/simple-update-notifier/build/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..60f53e0560e592029577d1e0c965d55c252b5e36 --- /dev/null +++ b/node_modules/simple-update-notifier/build/index.d.ts @@ -0,0 +1,13 @@ +interface IUpdate { + pkg: { + name: string; + version: string; + }; + updateCheckInterval?: number; + shouldNotifyInNpmScript?: boolean; + distTag?: string; + alwaysRun?: boolean; + debug?: boolean; +} +declare const simpleUpdateNotifier: (args: IUpdate) => Promise; +export { simpleUpdateNotifier as default }; diff --git a/node_modules/simple-update-notifier/build/index.js b/node_modules/simple-update-notifier/build/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d7c3cde2ef4e3a4b4e97ed23d3645735f3f6d0cb --- /dev/null +++ b/node_modules/simple-update-notifier/build/index.js @@ -0,0 +1,210 @@ +'use strict'; + +var process$1 = require('process'); +var semver = require('semver'); +var os = require('os'); +var path = require('path'); +var fs = require('fs'); +var https = require('https'); + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + + +function __awaiter(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()); + }); +} + +function __generator(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 (g && (g = 0, op[0] && (_ = 0)), _) 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 packageJson = process$1.env.npm_package_json; +var userAgent = process$1.env.npm_config_user_agent; +var isNpm6 = Boolean(userAgent && userAgent.startsWith('npm')); +var isNpm7 = Boolean(packageJson && packageJson.endsWith('package.json')); +var isNpm = isNpm6 || isNpm7; +var isYarn = Boolean(userAgent && userAgent.startsWith('yarn')); +var isNpmOrYarn = isNpm || isYarn; + +var homeDirectory = os.homedir(); +var configDir = process.env.XDG_CONFIG_HOME || + path.join(homeDirectory, '.config', 'simple-update-notifier'); +var getConfigFile = function (packageName) { + return path.join(configDir, "".concat(packageName.replace('@', '').replace('/', '__'), ".json")); +}; +var createConfigDir = function () { + if (!fs.existsSync(configDir)) { + fs.mkdirSync(configDir, { recursive: true }); + } +}; +var getLastUpdate = function (packageName) { + var configFile = getConfigFile(packageName); + try { + if (!fs.existsSync(configFile)) { + return undefined; + } + var file = JSON.parse(fs.readFileSync(configFile, 'utf8')); + return file.lastUpdateCheck; + } + catch (_a) { + return undefined; + } +}; +var saveLastUpdate = function (packageName) { + var configFile = getConfigFile(packageName); + fs.writeFileSync(configFile, JSON.stringify({ lastUpdateCheck: new Date().getTime() })); +}; + +var getDistVersion = function (packageName, distTag) { return __awaiter(void 0, void 0, void 0, function () { + var url; + return __generator(this, function (_a) { + url = "https://registry.npmjs.org/-/package/".concat(packageName, "/dist-tags"); + return [2 /*return*/, new Promise(function (resolve, reject) { + https + .get(url, function (res) { + var body = ''; + res.on('data', function (chunk) { return (body += chunk); }); + res.on('end', function () { + try { + var json = JSON.parse(body); + var version = json[distTag]; + if (!version) { + reject(new Error('Error getting version')); + } + resolve(version); + } + catch (_a) { + reject(new Error('Could not parse version response')); + } + }); + }) + .on('error', function (err) { return reject(err); }); + })]; + }); +}); }; + +var hasNewVersion = function (_a) { + var pkg = _a.pkg, _b = _a.updateCheckInterval, updateCheckInterval = _b === void 0 ? 1000 * 60 * 60 * 24 : _b, _c = _a.distTag, distTag = _c === void 0 ? 'latest' : _c, alwaysRun = _a.alwaysRun, debug = _a.debug; + return __awaiter(void 0, void 0, void 0, function () { + var lastUpdateCheck, latestVersion; + return __generator(this, function (_d) { + switch (_d.label) { + case 0: + createConfigDir(); + lastUpdateCheck = getLastUpdate(pkg.name); + if (!(alwaysRun || + !lastUpdateCheck || + lastUpdateCheck < new Date().getTime() - updateCheckInterval)) return [3 /*break*/, 2]; + return [4 /*yield*/, getDistVersion(pkg.name, distTag)]; + case 1: + latestVersion = _d.sent(); + saveLastUpdate(pkg.name); + if (semver.gt(latestVersion, pkg.version)) { + return [2 /*return*/, latestVersion]; + } + else if (debug) { + console.error("Latest version (".concat(latestVersion, ") not newer than current version (").concat(pkg.version, ")")); + } + return [3 /*break*/, 3]; + case 2: + if (debug) { + console.error("Too recent to check for a new update. simpleUpdateNotifier() interval set to ".concat(updateCheckInterval, "ms but only ").concat(new Date().getTime() - lastUpdateCheck, "ms since last check.")); + } + _d.label = 3; + case 3: return [2 /*return*/, false]; + } + }); + }); +}; + +var borderedText = function (text) { + var lines = text.split('\n'); + var width = Math.max.apply(Math, lines.map(function (l) { return l.length; })); + var res = ["\u250C".concat('─'.repeat(width + 2), "\u2510")]; + for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) { + var line = lines_1[_i]; + res.push("\u2502 ".concat(line.padEnd(width), " \u2502")); + } + res.push("\u2514".concat('─'.repeat(width + 2), "\u2518")); + return res.join('\n'); +}; + +var simpleUpdateNotifier = function (args) { return __awaiter(void 0, void 0, void 0, function () { + var latestVersion, err_1; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!args.alwaysRun && + (!process.stdout.isTTY || (isNpmOrYarn && !args.shouldNotifyInNpmScript))) { + if (args.debug) { + console.error('Opting out of running simpleUpdateNotifier()'); + } + return [2 /*return*/]; + } + _a.label = 1; + case 1: + _a.trys.push([1, 3, , 4]); + return [4 /*yield*/, hasNewVersion(args)]; + case 2: + latestVersion = _a.sent(); + if (latestVersion) { + console.error(borderedText("New version of ".concat(args.pkg.name, " available!\nCurrent Version: ").concat(args.pkg.version, "\nLatest Version: ").concat(latestVersion))); + } + return [3 /*break*/, 4]; + case 3: + err_1 = _a.sent(); + // Catch any network errors or cache writing errors so module doesn't cause a crash + if (args.debug && err_1 instanceof Error) { + console.error('Unexpected error in simpleUpdateNotifier():', err_1); + } + return [3 /*break*/, 4]; + case 4: return [2 /*return*/]; + } + }); +}); }; + +module.exports = simpleUpdateNotifier; diff --git a/node_modules/simple-update-notifier/package.json b/node_modules/simple-update-notifier/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4d710a72e90eba53c3e080174ce488e85608e6d4 --- /dev/null +++ b/node_modules/simple-update-notifier/package.json @@ -0,0 +1,100 @@ +{ + "name": "simple-update-notifier", + "version": "2.0.0", + "description": "Simple update notifier to check for npm updates for cli applications", + "main": "build/index.js", + "types": "build/index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/alexbrazier/simple-update-notifier.git" + }, + "homepage": "https://github.com/alexbrazier/simple-update-notifier.git", + "author": "alexbrazier", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "jest src --noStackTrace", + "build": "rollup -c rollup.config.js --bundleConfigAsCjs", + "prettier:check": "prettier --check src/**/*.ts", + "prettier": "prettier --write src/**/*.ts", + "eslint": "eslint src/**/*.ts", + "lint": "yarn prettier:check && yarn eslint", + "prepare": "yarn lint && yarn build", + "release": "release-it" + }, + "dependencies": { + "semver": "^7.5.3" + }, + "devDependencies": { + "@babel/preset-env": "^7.22.5", + "@babel/preset-typescript": "^7.22.5", + "@release-it/conventional-changelog": "^5.1.1", + "@types/jest": "^29.5.2", + "@types/node": "^20.3.1", + "@typescript-eslint/eslint-plugin": "^5.60.0", + "@typescript-eslint/parser": "^5.60.0", + "eslint": "^8.43.0", + "eslint-config-prettier": "^8.8.0", + "eslint-plugin-prettier": "^4.0.0", + "jest": "^29.5.0", + "prettier": "^2.8.8", + "release-it": "^15.11.0", + "rollup": "^3.25.2", + "rollup-plugin-ts": "^3.2.0", + "typescript": "^5.1.3" + }, + "resolutions": { + "semver": "^7.5.3" + }, + "publishConfig": { + "registry": "https://registry.npmjs.org/" + }, + "files": [ + "build", + "src" + ], + "release-it": { + "git": { + "commitMessage": "chore: release ${version}", + "tagName": "v${version}" + }, + "npm": { + "publish": true + }, + "github": { + "release": true + }, + "plugins": { + "@release-it/conventional-changelog": { + "preset": "angular", + "infile": "CHANGELOG.md" + } + } + }, + "eslintConfig": { + "plugins": [ + "@typescript-eslint", + "prettier" + ], + "extends": [ + "prettier", + "eslint:recommended", + "plugin:@typescript-eslint/recommended" + ], + "parser": "@typescript-eslint/parser", + "rules": { + "prettier/prettier": [ + "error", + { + "quoteProps": "consistent", + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "es5", + "useTabs": false + } + ] + } + } +} diff --git a/node_modules/simple-update-notifier/src/borderedText.ts b/node_modules/simple-update-notifier/src/borderedText.ts new file mode 100644 index 0000000000000000000000000000000000000000..7145ac2f43189ec3c945d1009df3dfe3d4c92d36 --- /dev/null +++ b/node_modules/simple-update-notifier/src/borderedText.ts @@ -0,0 +1,12 @@ +const borderedText = (text: string) => { + const lines = text.split('\n'); + const width = Math.max(...lines.map((l) => l.length)); + const res = [`┌${'─'.repeat(width + 2)}┐`]; + for (const line of lines) { + res.push(`│ ${line.padEnd(width)} │`); + } + res.push(`└${'─'.repeat(width + 2)}┘`); + return res.join('\n'); +}; + +export default borderedText; diff --git a/node_modules/simple-update-notifier/src/cache.spec.ts b/node_modules/simple-update-notifier/src/cache.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..49e1cb276993af3991196dca44a43f9f14da17a9 --- /dev/null +++ b/node_modules/simple-update-notifier/src/cache.spec.ts @@ -0,0 +1,17 @@ +import { createConfigDir, getLastUpdate, saveLastUpdate } from './cache'; + +createConfigDir(); + +jest.useFakeTimers().setSystemTime(new Date('2022-01-01')); + +const fakeTime = new Date('2022-01-01').getTime(); + +test('can save update then get the update details', () => { + saveLastUpdate('test'); + expect(getLastUpdate('test')).toBe(fakeTime); +}); + +test('prefixed module can save update then get the update details', () => { + saveLastUpdate('@alexbrazier/test'); + expect(getLastUpdate('@alexbrazier/test')).toBe(fakeTime); +}); diff --git a/node_modules/simple-update-notifier/src/cache.ts b/node_modules/simple-update-notifier/src/cache.ts new file mode 100644 index 0000000000000000000000000000000000000000..e11deba0ae1e8694311a9cc792014d727534d0df --- /dev/null +++ b/node_modules/simple-update-notifier/src/cache.ts @@ -0,0 +1,44 @@ +import os from 'os'; +import path from 'path'; +import fs from 'fs'; + +const homeDirectory = os.homedir(); +const configDir = + process.env.XDG_CONFIG_HOME || + path.join(homeDirectory, '.config', 'simple-update-notifier'); + +const getConfigFile = (packageName: string) => { + return path.join( + configDir, + `${packageName.replace('@', '').replace('/', '__')}.json` + ); +}; + +export const createConfigDir = () => { + if (!fs.existsSync(configDir)) { + fs.mkdirSync(configDir, { recursive: true }); + } +}; + +export const getLastUpdate = (packageName: string) => { + const configFile = getConfigFile(packageName); + + try { + if (!fs.existsSync(configFile)) { + return undefined; + } + const file = JSON.parse(fs.readFileSync(configFile, 'utf8')); + return file.lastUpdateCheck as number; + } catch { + return undefined; + } +}; + +export const saveLastUpdate = (packageName: string) => { + const configFile = getConfigFile(packageName); + + fs.writeFileSync( + configFile, + JSON.stringify({ lastUpdateCheck: new Date().getTime() }) + ); +}; diff --git a/node_modules/simple-update-notifier/src/getDistVersion.spec.ts b/node_modules/simple-update-notifier/src/getDistVersion.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..b78a42e5aa90f08aa6508eb9243e612b8f7c9040 --- /dev/null +++ b/node_modules/simple-update-notifier/src/getDistVersion.spec.ts @@ -0,0 +1,35 @@ +import Stream from 'stream'; +import https from 'https'; +import getDistVersion from './getDistVersion'; + +jest.mock('https', () => ({ + get: jest.fn(), +})); + +test('Valid response returns version', async () => { + const st = new Stream(); + (https.get as jest.Mock).mockImplementation((url, cb) => { + cb(st); + + st.emit('data', '{"latest":"1.0.0"}'); + st.emit('end'); + }); + + const version = await getDistVersion('test', 'latest'); + + expect(version).toEqual('1.0.0'); +}); + +test('Invalid response throws error', async () => { + const st = new Stream(); + (https.get as jest.Mock).mockImplementation((url, cb) => { + cb(st); + + st.emit('data', 'some invalid json'); + st.emit('end'); + }); + + expect(getDistVersion('test', 'latest')).rejects.toThrow( + 'Could not parse version response' + ); +}); diff --git a/node_modules/simple-update-notifier/src/getDistVersion.ts b/node_modules/simple-update-notifier/src/getDistVersion.ts new file mode 100644 index 0000000000000000000000000000000000000000..d474e1f9ead19135a390c930e5801f4e6910c0a4 --- /dev/null +++ b/node_modules/simple-update-notifier/src/getDistVersion.ts @@ -0,0 +1,29 @@ +import https from 'https'; + +const getDistVersion = async (packageName: string, distTag: string) => { + const url = `https://registry.npmjs.org/-/package/${packageName}/dist-tags`; + + return new Promise((resolve, reject) => { + https + .get(url, (res) => { + let body = ''; + + res.on('data', (chunk) => (body += chunk)); + res.on('end', () => { + try { + const json = JSON.parse(body); + const version = json[distTag]; + if (!version) { + reject(new Error('Error getting version')); + } + resolve(version); + } catch { + reject(new Error('Could not parse version response')); + } + }); + }) + .on('error', (err) => reject(err)); + }); +}; + +export default getDistVersion; diff --git a/node_modules/simple-update-notifier/src/hasNewVersion.spec.ts b/node_modules/simple-update-notifier/src/hasNewVersion.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..af7ab22cacee30687de862601171a819fd95c782 --- /dev/null +++ b/node_modules/simple-update-notifier/src/hasNewVersion.spec.ts @@ -0,0 +1,82 @@ +import hasNewVersion from './hasNewVersion'; +import { getLastUpdate } from './cache'; +import getDistVersion from './getDistVersion'; + +jest.mock('./getDistVersion', () => jest.fn().mockReturnValue('1.0.0')); +jest.mock('./cache', () => ({ + getLastUpdate: jest.fn().mockReturnValue(undefined), + createConfigDir: jest.fn(), + saveLastUpdate: jest.fn(), +})); + +const pkg = { name: 'test', version: '1.0.0' }; + +afterEach(() => jest.clearAllMocks()); + +const defaultArgs = { + pkg, + shouldNotifyInNpmScript: true, + alwaysRun: true, +}; + +test('it should not trigger update for same version', async () => { + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe(false); +}); + +test('it should trigger update for patch version bump', async () => { + (getDistVersion as jest.Mock).mockReturnValue('1.0.1'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe('1.0.1'); +}); + +test('it should trigger update for minor version bump', async () => { + (getDistVersion as jest.Mock).mockReturnValue('1.1.0'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe('1.1.0'); +}); + +test('it should trigger update for major version bump', async () => { + (getDistVersion as jest.Mock).mockReturnValue('2.0.0'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe('2.0.0'); +}); + +test('it should not trigger update if version is lower', async () => { + (getDistVersion as jest.Mock).mockReturnValue('0.0.9'); + + const newVersion = await hasNewVersion(defaultArgs); + + expect(newVersion).toBe(false); +}); + +it('should trigger update check if last update older than config', async () => { + const TWO_WEEKS = new Date().getTime() - 1000 * 60 * 60 * 24 * 14; + (getLastUpdate as jest.Mock).mockReturnValue(TWO_WEEKS); + const newVersion = await hasNewVersion({ + pkg, + shouldNotifyInNpmScript: true, + }); + + expect(newVersion).toBe(false); + expect(getDistVersion).toHaveBeenCalled(); +}); + +it('should not trigger update check if last update is too recent', async () => { + const TWELVE_HOURS = new Date().getTime() - 1000 * 60 * 60 * 12; + (getLastUpdate as jest.Mock).mockReturnValue(TWELVE_HOURS); + const newVersion = await hasNewVersion({ + pkg, + shouldNotifyInNpmScript: true, + }); + + expect(newVersion).toBe(false); + expect(getDistVersion).not.toHaveBeenCalled(); +}); diff --git a/node_modules/simple-update-notifier/src/hasNewVersion.ts b/node_modules/simple-update-notifier/src/hasNewVersion.ts new file mode 100644 index 0000000000000000000000000000000000000000..31d5069f97d3abf90d2c105374c21c44bde35b82 --- /dev/null +++ b/node_modules/simple-update-notifier/src/hasNewVersion.ts @@ -0,0 +1,40 @@ +import semver from 'semver'; +import { createConfigDir, getLastUpdate, saveLastUpdate } from './cache'; +import getDistVersion from './getDistVersion'; +import { IUpdate } from './types'; + +const hasNewVersion = async ({ + pkg, + updateCheckInterval = 1000 * 60 * 60 * 24, + distTag = 'latest', + alwaysRun, + debug, +}: IUpdate) => { + createConfigDir(); + const lastUpdateCheck = getLastUpdate(pkg.name); + if ( + alwaysRun || + !lastUpdateCheck || + lastUpdateCheck < new Date().getTime() - updateCheckInterval + ) { + const latestVersion = await getDistVersion(pkg.name, distTag); + saveLastUpdate(pkg.name); + if (semver.gt(latestVersion, pkg.version)) { + return latestVersion; + } else if (debug) { + console.error( + `Latest version (${latestVersion}) not newer than current version (${pkg.version})` + ); + } + } else if (debug) { + console.error( + `Too recent to check for a new update. simpleUpdateNotifier() interval set to ${updateCheckInterval}ms but only ${ + new Date().getTime() - lastUpdateCheck + }ms since last check.` + ); + } + + return false; +}; + +export default hasNewVersion; diff --git a/node_modules/simple-update-notifier/src/index.spec.ts b/node_modules/simple-update-notifier/src/index.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..98ffb5a9201cc15e27251e3bbe4f190a422ab0eb --- /dev/null +++ b/node_modules/simple-update-notifier/src/index.spec.ts @@ -0,0 +1,27 @@ +import simpleUpdateNotifier from '.'; +import hasNewVersion from './hasNewVersion'; + +const consoleSpy = jest.spyOn(console, 'error'); + +jest.mock('./hasNewVersion', () => jest.fn().mockResolvedValue('2.0.0')); + +beforeEach(jest.clearAllMocks); + +test('it logs message if update is available', async () => { + await simpleUpdateNotifier({ + pkg: { name: 'test', version: '1.0.0' }, + alwaysRun: true, + }); + + expect(consoleSpy).toHaveBeenCalledTimes(1); +}); + +test('it does not log message if update is not available', async () => { + (hasNewVersion as jest.Mock).mockResolvedValue(false); + await simpleUpdateNotifier({ + pkg: { name: 'test', version: '2.0.0' }, + alwaysRun: true, + }); + + expect(consoleSpy).toHaveBeenCalledTimes(0); +}); diff --git a/node_modules/simple-update-notifier/src/index.ts b/node_modules/simple-update-notifier/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..2b0d2cfcd7a4d1596e2257c7fe0d73cdf9bb49e4 --- /dev/null +++ b/node_modules/simple-update-notifier/src/index.ts @@ -0,0 +1,34 @@ +import isNpmOrYarn from './isNpmOrYarn'; +import hasNewVersion from './hasNewVersion'; +import { IUpdate } from './types'; +import borderedText from './borderedText'; + +const simpleUpdateNotifier = async (args: IUpdate) => { + if ( + !args.alwaysRun && + (!process.stdout.isTTY || (isNpmOrYarn && !args.shouldNotifyInNpmScript)) + ) { + if (args.debug) { + console.error('Opting out of running simpleUpdateNotifier()'); + } + return; + } + + try { + const latestVersion = await hasNewVersion(args); + if (latestVersion) { + console.error( + borderedText(`New version of ${args.pkg.name} available! +Current Version: ${args.pkg.version} +Latest Version: ${latestVersion}`) + ); + } + } catch (err) { + // Catch any network errors or cache writing errors so module doesn't cause a crash + if (args.debug && err instanceof Error) { + console.error('Unexpected error in simpleUpdateNotifier():', err); + } + } +}; + +export default simpleUpdateNotifier; diff --git a/node_modules/simple-update-notifier/src/isNpmOrYarn.ts b/node_modules/simple-update-notifier/src/isNpmOrYarn.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee4c8371afc074e93c8bd48bfe6ba9257c19cbee --- /dev/null +++ b/node_modules/simple-update-notifier/src/isNpmOrYarn.ts @@ -0,0 +1,12 @@ +import process from 'process'; + +const packageJson = process.env.npm_package_json; +const userAgent = process.env.npm_config_user_agent; +const isNpm6 = Boolean(userAgent && userAgent.startsWith('npm')); +const isNpm7 = Boolean(packageJson && packageJson.endsWith('package.json')); + +const isNpm = isNpm6 || isNpm7; +const isYarn = Boolean(userAgent && userAgent.startsWith('yarn')); +const isNpmOrYarn = isNpm || isYarn; + +export default isNpmOrYarn; diff --git a/node_modules/simple-update-notifier/src/types.ts b/node_modules/simple-update-notifier/src/types.ts new file mode 100644 index 0000000000000000000000000000000000000000..c395eb002762d0d4cca2b254b073b33db8b83da4 --- /dev/null +++ b/node_modules/simple-update-notifier/src/types.ts @@ -0,0 +1,8 @@ +export interface IUpdate { + pkg: { name: string; version: string }; + updateCheckInterval?: number; + shouldNotifyInNpmScript?: boolean; + distTag?: string; + alwaysRun?: boolean; + debug?: boolean; +} diff --git a/node_modules/simple-xml-to-json/README.md b/node_modules/simple-xml-to-json/README.md new file mode 100644 index 0000000000000000000000000000000000000000..de175a793945c47b61a197ee0e116b8d627db834 --- /dev/null +++ b/node_modules/simple-xml-to-json/README.md @@ -0,0 +1,87 @@ +# A simple XML to JSON converter + +[![npm version](https://img.shields.io/npm/v/simple-xml-to-json.svg?style=flat-square)](https://www.npmjs.com/package/simple-xml-to-json) +[![Test CI](https://github.com/nirgit/simple-xml-to-json/actions/workflows/node.js.yml/badge.svg)](https://github.com/nirgit/simple-xml-to-json/actions/workflows/node.js.yml) +[![codecov](https://codecov.io/gh/nirgit/simple-xml-to-json/branch/master/graph/badge.svg?token=XW7CWWM4RV)](https://codecov.io/gh/nirgit/simple-xml-to-json) + +## Install +Simply install using NPM in your project directory +> npm install simple-xml-to-json + + +## Usage and API +### 1. convertXML(xmlToConvert [,customConverter]) + * `xmlToConvert` \ + * `customConverter` \ + * Returns: \ by default or other if `customConverter` is used + +### 2. createAST(xmlToConvert) + * `xmlToConvert` \ + * Returns: An AST representation of the XML \ + +**CommonJS (Node.js):** +```javascript +const { convertXML, createAST } = require("simple-xml-to-json") + +const myJson = convertXML(myXMLString) +const myYaml = convertXML(myXMLString, yamlConverter) +const myAst = createAST(myXMLString) +``` + +**ESM (modern frontend apps, Node.js with `"type": "module"`, bundlers):** +```javascript +import { convertXML, createAST } from "simple-xml-to-json" + +const myJson = convertXML(myXMLString) +const myYaml = convertXML(myXMLString, yamlConverter) +const myAst = createAST(myXMLString) +``` + +--- +### ![TS](https://raw.githubusercontent.com/nirgit/assets/master/simple-xml-to-json/ts_icon_32.png) Typescript compatible +--- + +## Notes and how to use code +1. The easiest thing to start is to run `node example/example.js` (CJS) or `node example/example.mjs` (ESM) in your terminal and see what happens. +2. There's the `xmlToJson.js` file for convenience. Just pass in the XML as a String. +3. MIT licensed allowing code customization +4. Profit + +## How this works in a nutshell +1. The library converts the XML to an AST +2. There is a JSON converter that takes the AST and spits out a JSON +3. You can write your own converters if you need XML-to-ANY-OTHER-FORMAT + +## Benchmark + +_Take these results with a grain of salt._\ +According to a __simple__ benchmark test I performed in __April 2024__ with a random XML. _YMMV_. +![Benchmark Chart](https://github.com/nirgit/assets/blob/master/simple-xml-to-json/simple-xml-to-json-benchmark-2.png?raw=true) + +* The chart results __may be__ outdated. [Run the test yourself](https://runkit.com/nirgit/6620cf27943a41000847221d) + + +## Current Drawbacks +1. All values are translated to strings in JSON +2. There are currently reserved words in the JSON converter: + * "content" - up to version 1.2.3 + * "children" + +### Default Mapping & Collisions + +By default, an element's **text content** is mapped to a `"content"` property, while its **attributes** are mapped directly to JSON properties of the same name. + +#### The Risk +If an XML element possesses an attribute actually named `content` while also containing text content, a **name collision** occurs. This typically results in a parsing error or data loss due to duplicate keys. + +**Example Collision:** +```xml +text-content + ``` + +### Version 1.2.3+ Fix +To prevent these collisions, versions newer than 1.2.3 will specifically prefix the `"content"` attribute name with an `@` symbol. So the attribute `"content"` now becomes the `"@content"` JSON property. + + +> [!NOTE] +> If you need to, you can write your own converter from the AST created by the parser, and pass it as a 2nd parameter after the xml string diff --git a/node_modules/simple-xml-to-json/lib/simpleXmlToJson.js b/node_modules/simple-xml-to-json/lib/simpleXmlToJson.js new file mode 100644 index 0000000000000000000000000000000000000000..9eeb8f8316e15f591b5a665889495ea45c3fea3b --- /dev/null +++ b/node_modules/simple-xml-to-json/lib/simpleXmlToJson.js @@ -0,0 +1,590 @@ +'use strict'; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var constants; +var hasRequiredConstants; + +function requireConstants () { + if (hasRequiredConstants) return constants; + hasRequiredConstants = 1; + + constants = { + BUILD: { + COMPTIME: true + }, + NODE_TYPE: { + ATTRIBUTE: 'ATTRIBUTE', + CONTENT: 'CONTENT', + ELEMENT: 'ELEMENT', + ROOT: 'ROOT' + }, + TOKEN_TYPE: { + OPEN_BRACKET: 'OPEN_BRACKET', + ELEMENT_TYPE: 'ELEMENT_TYPE', + CLOSE_ELEMENT: 'CLOSE_ELEMENT', + ATTRIB_NAME: 'ATTRIB_NAME', + ATTRIB_VALUE: 'ATTRIB_VALUE', + ASSIGN: 'ASSIGN', + CLOSE_BRACKET: 'CLOSE_BRACKET', + CONTENT: 'CONTENT', + EOF: 'EOF' + } + }; + return constants; +} + +var astToJson; +var hasRequiredAstToJson; + +function requireAstToJson () { + if (hasRequiredAstToJson) return astToJson; + hasRequiredAstToJson = 1; + + const { NODE_TYPE } = requireConstants(); + + const convertToJSON = ast => { + return buildJSONFromNode(ast.value.children[0]) + }; + + const buildJSONFromNode = node => { + if (!node) return null + const json = {}; + switch (node.type) { + case "ELEMENT": { + let element = {}; + const attribs = buildAttributes(node.value.attributes); + const children = buildJSONFromNode(node.value.children); + if (attribs) { + element = Object.assign(element, attribs); + } + if (children) { + const jsonChildren = buildChildren(node.value.children); + element = Object.assign(element, jsonChildren); + } + json[node.value.type] = element; + break + } + case "ATTRIBUTE": { + const attribNameAndValue = node.value; + json[attribNameAndValue.name] = attribNameAndValue.value; + break + } + case "CONTENT": { + return {content: node.value} + } + } + + return json + }; + + const buildChildren = children => { + if (!children || !Array.isArray(children) || children.length === 0) return null + if (isContentChildren(children)) { + return { + content: children[0].value + } + } + return { + children: children.map(buildJSONFromNode) + } + }; + + const isContentChildren = children => children && Array.isArray(children) && children.length === 1 && children[0].type === "CONTENT"; + + const buildAttributes = arrayNodes => { + if (arrayNodes && Array.isArray(arrayNodes)) { + const jsonArray = arrayNodes.map(buildJSONFromNode); + return jsonArray.reduce((agg, j) => Object.assign(agg, j), {}) + } + return null + }; + + astToJson = { + convert: convertToJSON + }; + return astToJson; +} + +var model; +var hasRequiredModel; + +function requireModel () { + if (hasRequiredModel) return model; + hasRequiredModel = 1; + + const Token = (type, value) => ({ + type, + value + }); + + model = { + Token + }; + return model; +} + +var lexer; +var hasRequiredLexer; + +function requireLexer () { + if (hasRequiredLexer) return lexer; + hasRequiredLexer = 1; + + const { BUILD, TOKEN_TYPE } = requireConstants(); + const { Token } = requireModel(); + + const EOF_TOKEN = Token("EOF"); + + const isCharBlank = (char) => + char === ' ' || char === '\n' || char === '\r' || char === '\t'; + + const skipXMLDocumentHeader = (xmlAsString, pos) => { + if (xmlAsString.startsWith('') { + return pos + 2 // skip "?>"" + } else { + pos++; + } + } + } + return pos + }; + + const replaceQuotes = (str) => str.replace(/'/g, "'"); + + const getInitialPosForLexer = (xmlAsString) => { + let pos = 0; + while (pos < xmlAsString.length && isCharBlank(xmlAsString[pos])) pos++; + return skipXMLDocumentHeader(xmlAsString, pos) + }; + + function createLexer(xmlAsString) { + let currentToken = null; + let pos = getInitialPosForLexer(xmlAsString); + let scopingElement = []; + + const peek = () => xmlAsString[pos]; + const hasNext = () => currentToken !== EOF_TOKEN && pos < xmlAsString.length; + const isBlankSpace = () => isCharBlank(xmlAsString[pos]); + + const skipQuotes = () => { + if (hasNext() && isQuote(peek())) pos++; + }; + + const isQuote = (char) => '"' === char || "'" === char; + + const skipSpaces = () => { + while (hasNext() && isBlankSpace()) pos++; + }; + + const readAlphaNumericCharsOrBrackets = (areSpecialCharsSupported) => { + if (hasNext()) { + if (xmlAsString[pos] === '<') { + let buffer = '<'; + pos++; + if (hasNext() && xmlAsString[pos] === '/') { + pos++; + buffer = '') { + pos++; + buffer = '/>'; + } + return buffer + } else if (xmlAsString[pos] === '=' || xmlAsString[pos] === '>') { + const buffer = xmlAsString[pos]; + pos++; + return buffer + } + } + return readAlphaNumericChars(!!areSpecialCharsSupported) + }; + + const readAlphaNumericChars = (areSpecialCharsSupported) => { + const ELEMENT_TYPE_MATCHER = /[a-zA-Z0-9_:-]/; + const NAMES_VALS_CONTENT_MATCHER = /[^>=<]/u; + const matcher = areSpecialCharsSupported + ? NAMES_VALS_CONTENT_MATCHER + : ELEMENT_TYPE_MATCHER; + let start = pos; + while (hasNext() && xmlAsString[pos].match(matcher)) pos++; + return replaceQuotes(xmlAsString.substring(start, pos)) + }; + + const isElementBegin = () => + currentToken && currentToken.type === "OPEN_BRACKET"; + const isAssignToAttribute = () => + currentToken && currentToken.type === "ASSIGN"; + + const next = () => { + const prevPos = pos; + skipSpaces(); + const numOfSpacesSkipped = pos - prevPos; + if (!hasNext()) { + currentToken = EOF_TOKEN; + } else if (isElementBegin()) { + // starting new element + skipSpaces(); + const buffer = readAlphaNumericCharsOrBrackets(false); + currentToken = Token("ELEMENT_TYPE", buffer); + scopingElement.push(buffer); + } else if (isAssignToAttribute()) { + // assign value to attribute + skipQuotes(); + const openingQuote = xmlAsString[pos - 1]; + let start = pos; + while (hasNext() && peek() !== openingQuote) pos++; + const buffer = replaceQuotes(xmlAsString.substring(start, pos)); + pos++; + currentToken = Token("ATTRIB_VALUE", buffer); + } else { + skipSpaces(); + let buffer = readAlphaNumericCharsOrBrackets(true); + switch (buffer) { + case '=': { + if (currentToken.type === "ATTRIB_NAME") { + currentToken = Token("ASSIGN"); + } else { + currentToken = Token("CONTENT", buffer); + } + break + } + case '') pos++; + currentToken = Token( + "CLOSE_ELEMENT", + xmlAsString.substring(start, pos) + ); + pos++; // skip the ">" + scopingElement.pop(); + break + } + case '/>': { + const scopingElementName = scopingElement.pop(); + currentToken = Token( + "CLOSE_ELEMENT", + scopingElementName + ); + break + } + case ' + +-------------------------------------------------------------------------------- + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer)](#sourcemapgeneratorfromsourcemapsourcemapconsumer) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA' +}; + +var smc = new SourceMapConsumer(rawSourceMap); + +console.log(smc.sources); +// [ 'http://example.com/www/js/one.js', +// 'http://example.com/www/js/two.js' ] + +console.log(smc.originalPositionFor({ + line: 2, + column: 28 +})); +// { source: 'http://example.com/www/js/two.js', +// line: 2, +// column: 10, +// name: 'n' } + +console.log(smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10 +})); +// { line: 2, column: 28 } + +smc.eachMapping(function (m) { + // ... +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), " + ", compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error("Bad AST"); + } +} + +var ast = parse("40 + 2", "add.js"); +console.log(compile(ast).toStringWithSourceMap({ + file: 'add.js' +})); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: "source-mapped.js" +}); + +map.addMapping({ + generated: { + line: 10, + column: 35 + }, + source: "foo.js", + original: { + line: 33, + column: 2 + }, + name: "christopher" +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require("devtools/toolkit/sourcemap/source-map.js"); +``` + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +* `version`: Which version of the source map spec this map is following. + +* `sources`: An array of URLs to the original source files. + +* `names`: An array of identifiers which can be referenced by individual + mappings. + +* `sourceRoot`: Optional. The URL root from which all sources are relative. + +* `sourcesContent`: Optional. An array of contents of the original source files. + +* `mappings`: A string of base64 VLQs which contain the actual mappings. + +* `file`: Optional. The generated filename this source map is associated with. + +```js +var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +``` + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] + +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +* `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +* `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +* `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +* `source`: The original source file, or null if this information is not + available. + +* `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +* `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +* `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }) +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ line: 99999999999999999, column: 999999999999999 }) +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: "example.js", line: 2, column: 10 }) +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +* `source`: The filename of the original source. + +* `line`: The line number in the original source. The line number is + 1-based. + +* `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +* `line`: The line number in the generated source, or null. The line + number is 1-based. + +* `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: "foo.coffee" }) +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor("my-cool-lib.clj") +// "..." + +consumer.sourceContentFor("this is not in the source map"); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor("this is not in the source map", true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +* `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, + name }` + +* `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +* `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { console.log(m); }) +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +* `file`: The filename of the generated source that this source map is + associated with. + +* `sourceRoot`: A root for all relative URLs in this source map. + +* `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +* `ignoreInvalidMapping`: Optional. When `true`, instead of throwing error on + invalid mapping, it will be ignored. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: "my-generated-javascript-file.js", + sourceRoot: "http://example.com/app/js/" +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer, sourceMapGeneratorOptions) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +* `sourceMapConsumer` The SourceMap. + +* `sourceMapGeneratorOptions` options that will be passed to the SourceMapGenerator constructor which used under the hood. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer, { + ignoreInvalidMapping: true, +}); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +* `generated`: An object with the generated line and column positions. + +* `original`: An object with the original line and column positions. + +* `source`: The original source file (relative to the sourceRoot). + +* `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: "module-one.scm", + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 } +}) +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +* `sourceFile` the URL of the original source file. + +* `sourceContent` the content of the source file. + +```js +generator.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +* `sourceMapConsumer`: The SourceMap to be applied. + +* `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +* `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString() +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +* `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +* `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +* `source`: The original source's filename; null if no filename is provided. + +* `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +* `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, "a.cpp", [ + new SourceNode(3, 4, "b.cpp", "extern int status;\n"), + new SourceNode(5, 6, "c.cpp", "std::string* make_string(size_t n);\n"), + new SourceNode(7, 8, "d.cpp", "int main(int argc, char** argv) {}\n"), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +* `code`: The generated code + +* `sourceMapConsumer` The SourceMap for the generated code + +* `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +var consumer = new SourceMapConsumer(fs.readFileSync("path/to/my-file.js.map", "utf8")); +var node = SourceNode.fromStringWithSourceMap(fs.readFileSync("path/to/my-file.js"), + consumer); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(" + "); +node.add(otherNode); +node.add([leftHandOperandNode, " + ", rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +* `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend("/** Build Id: f783haef86324gf **/\n\n"); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +* `sourceFile`: The filename of the source file + +* `sourceContent`: The content of the source file + +```js +node.setSourceContent("module-one.scm", + fs.readFileSync("path/to/module-one.scm")) +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +* `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.walk(function (code, loc) { console.log("WALK:", code, loc); }) +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +* `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, "a.js", "generated from a"); +a.setSourceContent("a.js", "original a"); +var b = new SourceNode(1, 2, "b.js", "generated from b"); +b.setSourceContent("b.js", "original b"); +var c = new SourceNode(1, 2, "c.js", "generated from c"); +c.setSourceContent("c.js", "original c"); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { console.log("WALK:", source, ":", contents); }) +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +* `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, "a.rs", "my_copy"); +var operand = new SourceNode(3, 4, "a.rs", "="); +var rhs = new SourceNode(5, 6, "a.rs", "orig.clone()"); + +var node = new SourceNode(null, null, null, [ lhs, operand, rhs ]); +var joinedNode = node.join(" "); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +* `pattern`: The pattern to replace. + +* `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ""); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toString() +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, "a.js", [ + new SourceNode(3, 4, "b.js", "uno"), + "dos", + [ + "tres", + new SourceNode(5, 6, "c.js", "quatro") + ] +]); + +node.toStringWithSourceMap({ file: "my-output-file.js" }) +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/node_modules/source-map-js/lib/array-set.js b/node_modules/source-map-js/lib/array-set.js new file mode 100644 index 0000000000000000000000000000000000000000..fbd5c81cae66fa6401f871ac7fb02e96fdb9c213 --- /dev/null +++ b/node_modules/source-map-js/lib/array-set.js @@ -0,0 +1,121 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== "undefined"; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/node_modules/source-map-js/lib/base64-vlq.js b/node_modules/source-map-js/lib/base64-vlq.js new file mode 100644 index 0000000000000000000000000000000000000000..612b404018ece911ab71fc0a8db326d16e6b1287 --- /dev/null +++ b/node_modules/source-map-js/lib/base64-vlq.js @@ -0,0 +1,140 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. 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. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/node_modules/source-map-js/lib/base64.js b/node_modules/source-map-js/lib/base64.js new file mode 100644 index 0000000000000000000000000000000000000000..8aa86b30264363990334a7df0aa0d0c9cc1aecfc --- /dev/null +++ b/node_modules/source-map-js/lib/base64.js @@ -0,0 +1,67 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/node_modules/source-map-js/lib/binary-search.js b/node_modules/source-map-js/lib/binary-search.js new file mode 100644 index 0000000000000000000000000000000000000000..010ac941e1568d59c89b67cb649051a14608ee79 --- /dev/null +++ b/node_modules/source-map-js/lib/binary-search.js @@ -0,0 +1,111 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/node_modules/source-map-js/lib/mapping-list.js b/node_modules/source-map-js/lib/mapping-list.js new file mode 100644 index 0000000000000000000000000000000000000000..06d1274a025a8a30879f31c9c6703a14f79f73b9 --- /dev/null +++ b/node_modules/source-map-js/lib/mapping-list.js @@ -0,0 +1,79 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/node_modules/source-map-js/lib/quick-sort.js b/node_modules/source-map-js/lib/quick-sort.js new file mode 100644 index 0000000000000000000000000000000000000000..23f9eda57f7383b5291361e4593cf2fdef5409ba --- /dev/null +++ b/node_modules/source-map-js/lib/quick-sort.js @@ -0,0 +1,132 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. + +function SortTemplate(comparator) { + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot, false) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } +} + + return doQuickSort; +} + +function cloneSort(comparator) { + let template = SortTemplate.toString(); + let templateFn = new Function(`return ${template}`)(); + return templateFn(comparator); +} + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + +let sortCache = new WeakMap(); +exports.quickSort = function (ary, comparator, start = 0) { + let doQuickSort = sortCache.get(comparator); + if (doQuickSort === void 0) { + doQuickSort = cloneSort(comparator); + sortCache.set(comparator, doQuickSort); + } + doQuickSort(ary, comparator, start, ary.length - 1); +}; diff --git a/node_modules/source-map-js/lib/source-map-consumer.d.ts b/node_modules/source-map-js/lib/source-map-consumer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..744bda73d103b79b7e654972b9a42c3c95ff432a --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-consumer.d.ts @@ -0,0 +1 @@ +export { SourceMapConsumer } from '..'; diff --git a/node_modules/source-map-js/lib/source-map-consumer.js b/node_modules/source-map-js/lib/source-map-consumer.js new file mode 100644 index 0000000000000000000000000000000000000000..ee66114636c1e3f1b455457ad9e91b0eeeb2d360 --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-consumer.js @@ -0,0 +1,1188 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +} + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + var boundCallback = aCallback.bind(context); + var names = this._names; + var sources = this._sources; + var sourceMapURL = this._sourceMapURL; + + for (var i = 0, n = mappings.length; i < n; i++) { + var mapping = mappings[i]; + var source = mapping.source === null ? null : sources.at(mapping.source); + if(source !== null) { + source = util.computeSourceURL(sourceRoot, source, sourceMapURL); + } + boundCallback({ + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : names.at(mapping.name) + }); + } + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + } +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + +const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine; +function sortGenerated(array, start) { + let l = array.length; + let n = array.length - start; + if (n <= 1) { + return; + } else if (n == 2) { + let a = array[start]; + let b = array[start + 1]; + if (compareGenerated(a, b) > 0) { + array[start] = b; + array[start + 1] = a; + } + } else if (n < 20) { + for (let i = start; i < l; i++) { + for (let j = i; j > start; j--) { + let a = array[j - 1]; + let b = array[j]; + if (compareGenerated(a, b) <= 0) { + break; + } + array[j - 1] = b; + array[j] = a; + } + } + } else { + quickSort(array, compareGenerated, start); + } +} +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + let subarrayStart = 0; + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + + sortGenerated(generatedMappings, subarrayStart); + subarrayStart = generatedMappings.length; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + let currentSource = mapping.source; + while (originalMappings.length <= currentSource) { + originalMappings.push(null); + } + if (originalMappings[currentSource] === null) { + originalMappings[currentSource] = []; + } + originalMappings[currentSource].push(mapping); + } + } + } + + sortGenerated(generatedMappings, subarrayStart); + this.__generatedMappings = generatedMappings; + + for (var i = 0; i < originalMappings.length; i++) { + if (originalMappings[i] != null) { + quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource); + } + } + this.__originalMappings = [].concat(...originalMappings); + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + relativeSource)) { + return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL) + } + }); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content || content === '') { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + if(source !== null) { + source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/node_modules/source-map-js/lib/source-map-generator.d.ts b/node_modules/source-map-js/lib/source-map-generator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f59d70aa9ca827224617e01d390c9c10b4e81cbc --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-generator.d.ts @@ -0,0 +1 @@ +export { SourceMapGenerator } from '..'; diff --git a/node_modules/source-map-js/lib/source-map-generator.js b/node_modules/source-map-js/lib/source-map-generator.js new file mode 100644 index 0000000000000000000000000000000000000000..bab04ff85b38eb50f942fb7ba84dd46dfe1f00c6 --- /dev/null +++ b/node_modules/source-map-js/lib/source-map-generator.js @@ -0,0 +1,444 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._ignoreInvalidMapping = util.getArg(aArgs, 'ignoreInvalidMapping', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer, generatorOps) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator(Object.assign(generatorOps || {}, { + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + })); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + if (this._validateMapping(generated, original, source, name) === false) { + return; + } + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') { + var message = '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 (this._ignoreInvalidMapping) { + if (typeof console !== 'undefined' && console.warn) { + console.warn(message); + } + return false; + } else { + throw new Error(message); + } + } + + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + var message = 'Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + }); + + if (this._ignoreInvalidMapping) { + if (typeof console !== 'undefined' && console.warn) { + console.warn(message); + } + return false; + } else { + throw new Error(message) + } + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/node_modules/source-map-js/lib/source-node.d.ts b/node_modules/source-map-js/lib/source-node.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4df6a1aca10c42f674f4403b803ced48e030253f --- /dev/null +++ b/node_modules/source-map-js/lib/source-node.d.ts @@ -0,0 +1 @@ +export { SourceNode } from '..'; diff --git a/node_modules/source-map-js/lib/source-node.js b/node_modules/source-map-js/lib/source-node.js new file mode 100644 index 0000000000000000000000000000000000000000..8bcdbe385d2c0d333bcd62648ca700f13f9d3181 --- /dev/null +++ b/node_modules/source-map-js/lib/source-node.js @@ -0,0 +1,413 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = "$$$isSourceNode$$$"; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function() { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ""; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length ? + remainingLines[remainingLinesIndex++] : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; +}; + +exports.SourceNode = SourceNode; diff --git a/node_modules/source-map-js/lib/util.js b/node_modules/source-map-js/lib/util.js new file mode 100644 index 0000000000000000000000000000000000000000..430e2d0ff0b2f2a084d00fbfbcf9a229d0a7bfff --- /dev/null +++ b/node_modules/source-map-js/lib/util.js @@ -0,0 +1,594 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +var MAX_CACHED_INPUTS = 32; + +/** + * Takes some function `f(input) -> result` and returns a memoized version of + * `f`. + * + * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The + * memoization is a dumb-simple, linear least-recently-used cache. + */ +function lruMemoize(f) { + var cache = []; + + return function(input) { + for (var i = 0; i < cache.length; i++) { + if (cache[i].input === input) { + var temp = cache[0]; + cache[0] = cache[i]; + cache[i] = temp; + return cache[0].result; + } + } + + var result = f(input); + + cache.unshift({ + input, + result, + }); + + if (cache.length > MAX_CACHED_INPUTS) { + cache.pop(); + } + + return result; + }; +} + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +var normalize = lruMemoize(function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + // Split the path into parts between `/` characters. This is much faster than + // using `.split(/\/+/g)`. + var parts = []; + var start = 0; + var i = 0; + while (true) { + start = i; + i = path.indexOf("/", start); + if (i === -1) { + parts.push(path.slice(start)); + break; + } else { + parts.push(path.slice(start, i)); + while (i < path.length && path[i] === "/") { + i++; + } + } + } + + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +}); +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +}()); + +function identity (s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +function compareByOriginalPositionsNoSource(mappingA, mappingB, onlyCompareOriginal) { + var cmp + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + +function compareByGeneratedPositionsDeflatedNoLine(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflatedNoLine = compareByGeneratedPositionsDeflatedNoLine; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error("sourceMapURL could not be parsed"); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/node_modules/source-map-js/package.json b/node_modules/source-map-js/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f58dbeb4eca3ad3118fbd5e2a7f6241d5b5aceaa --- /dev/null +++ b/node_modules/source-map-js/package.json @@ -0,0 +1,71 @@ +{ + "name": "source-map-js", + "description": "Generates and consumes source maps", + "version": "1.2.1", + "homepage": "https://github.com/7rulnik/source-map-js", + "author": "Valentin 7rulnik Semirulnik ", + "contributors": [ + "Nick Fitzgerald ", + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": "7rulnik/source-map-js", + "main": "./source-map.js", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/" + ], + "engines": { + "node": ">=0.10.0" + }, + "license": "BSD-3-Clause", + "scripts": { + "test": "npm run build && node test/run-tests.js", + "build": "webpack --color", + "toc": "doctoc --title '## Table of Contents' README.md && doctoc --title '## Table of Contents' CONTRIBUTING.md" + }, + "devDependencies": { + "clean-publish": "^3.1.0", + "doctoc": "^0.15.0", + "webpack": "^1.12.0" + }, + "clean-publish": { + "cleanDocs": true + }, + "typings": "source-map.d.ts" +} diff --git a/node_modules/source-map-js/source-map.d.ts b/node_modules/source-map-js/source-map.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec8892fa11313d34c668e6f0ca9f80fdd5b53aec --- /dev/null +++ b/node_modules/source-map-js/source-map.d.ts @@ -0,0 +1,104 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +export interface RawSourceMap extends StartOfSourceMap { + version: string; + sources: string[]; + names: string[]; + sourcesContent?: string[]; + mappings: string; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string | null; + generatedLine: number; + generatedColumn: number; + originalLine: number | null; + originalColumn: number | null; + name: string | null; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + constructor(rawSourceMap: RawSourceMap); + readonly file: string | undefined | null; + readonly sourceRoot: string | undefined | null; + readonly sourcesContent: readonly string[] | null | undefined; + readonly sources: readonly string[] + + computeColumnSpans(): void; + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + allGeneratedPositionsFor(originalPosition: MappedPosition): Position[]; + hasContentsOfAllSources(): boolean; + sourceContentFor(source: string, returnNullOnMissing?: boolean): string | null; + eachMapping(callback: (mapping: MappingItem) => void, context?: any, order?: number): void; +} + +export interface Mapping { + generated: Position; + original?: Position | null; + source?: string | null; + name?: string | null; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: StartOfSourceMap); + static fromSourceMap(sourceMapConsumer: SourceMapConsumer, startOfSourceMap?: StartOfSourceMap): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent(sourceFile: string, sourceContent: string | null | undefined): void; + applySourceMap(sourceMapConsumer: SourceMapConsumer, sourceFile?: string, sourceMapPath?: string): void; + toString(): string; + toJSON(): RawSourceMap; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +export class SourceNode { + constructor(); + constructor(line: number, column: number, source: string); + constructor(line: number, column: number, source: string, chunk?: string, name?: string); + static fromStringWithSourceMap(code: string, sourceMapConsumer: SourceMapConsumer, relativePath?: string): SourceNode; + add(chunk: string): void; + prepend(chunk: string): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight(pattern: string, replacement: string): SourceNode; + toString(): string; + toStringWithSourceMap(startOfSourceMap?: StartOfSourceMap): CodeWithSourceMap; +} diff --git a/node_modules/source-map-js/source-map.js b/node_modules/source-map-js/source-map.js new file mode 100644 index 0000000000000000000000000000000000000000..bc88fe820c87a217d27eb010281fe39b71163835 --- /dev/null +++ b/node_modules/source-map-js/source-map.js @@ -0,0 +1,8 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/node_modules/source-map-support/LICENSE.md b/node_modules/source-map-support/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..6247ca912cb4bcc379aed9b711290dc3d174f915 --- /dev/null +++ b/node_modules/source-map-support/LICENSE.md @@ -0,0 +1,21 @@ +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. diff --git a/node_modules/source-map-support/README.md b/node_modules/source-map-support/README.md new file mode 100644 index 0000000000000000000000000000000000000000..40228b7910cd798dd5ff06d68d82255c5b9096bb --- /dev/null +++ b/node_modules/source-map-support/README.md @@ -0,0 +1,284 @@ +# Source Map Support +[![Build Status](https://travis-ci.org/evanw/node-source-map-support.svg?branch=master)](https://travis-ci.org/evanw/node-source-map-support) + +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 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 source-map-support/register compiled.js +``` + +##### Programmatic Usage + +Put the following line at the top of the compiled file. + +```js +require('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 'source-map-support/register' + +// Instead of: +import sourceMapSupport from '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 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 + + +``` + +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 + +``` + +## 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('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('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('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('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('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. (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('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. (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('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. (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('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 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. (demo.coffee:5:1) + at Object. (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). diff --git a/node_modules/source-map-support/browser-source-map-support.js b/node_modules/source-map-support/browser-source-map-support.js new file mode 100644 index 0000000000000000000000000000000000000000..782da501459760dd729b76cb0a80358063f70e30 --- /dev/null +++ b/node_modules/source-map-support/browser-source-map-support.js @@ -0,0 +1,114 @@ +/* + * 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 + 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;mm)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>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> +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>>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;ba)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||ba.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>>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>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||ba.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=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=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>>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;hw?"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= +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;ab&&(a+=" ... "));return""};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>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>>=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(wb||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-bw||!e.TYPED_ARRAY_SUPPORT)for(var y=0;yb||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>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;for(r+=m;0>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<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;gl&&(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(),0p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0=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<>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=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:0p?-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=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=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._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||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";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||""):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||"")}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 C:/dir/file + '/'; // file:///root-dir/file -> /root-dir/file + }); + } + if (path in fileContentsCache) { + return fileContentsCache[path]; + } + + 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 fileContentsCache[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; + var dir = path.dirname(file); + var match = /^\w+:\/\/[^\/]*/.exec(dir); + var protocol = match ? match[0] : ''; + var startPath = dir.slice(protocol.length); + if (protocol && /^\/\w\:/.test(startPath)) { + // handle file:///C:/ paths + protocol += '/'; + return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/'); + } + return protocol + path.resolve(dir.slice(protocol.length), url); +} + +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(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). +var retrieveSourceMap = handlerExec(retrieveMapHandlers); +retrieveMapHandlers.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 = bufferFrom(rawData, "base64").toString(); + sourceMappingURL = source; + } else { + // Support source map URLs relative to the source URL + sourceMappingURL = supportRelativeURL(source, sourceMappingURL); + sourceMapData = retrieveFile(sourceMappingURL); + } + + if (!sourceMapData) { + return null; + } + + return { + url: sourceMappingURL, + map: sourceMapData + }; +}); + +function mapSourcePosition(position) { + var sourceMap = sourceMapCache[position.source]; + if (!sourceMap) { + // Call the (overrideable) retrieveSourceMap function to get the source map. + var urlAndMap = retrieveSourceMap(position.source); + if (urlAndMap) { + sourceMap = sourceMapCache[position.source] = { + url: urlAndMap.url, + map: new SourceMapConsumer(urlAndMap.map) + }; + + // 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.sources.forEach(function(source, i) { + var contents = sourceMap.map.sourcesContent[i]; + if (contents) { + var url = supportRelativeURL(sourceMap.url, source); + fileContentsCache[url] = contents; + } + }); + } + } else { + sourceMap = sourceMapCache[position.source] = { + url: null, + map: null + }; + } + } + + // Resolve the source URL relative to the URL of the source map + if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') { + var originalPosition = sourceMap.map.originalPositionFor(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 = supportRelativeURL( + sourceMap.url, 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. 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 += ""; + } + var lineNumber = this.getLineNumber(); + if (lineNumber != null) { + fileLocation += ":" + lineNumber; + var columnNumber = this.getColumnNumber(); + if (columnNumber) { + fileLocation += ":" + columnNumber; + } + } + } + + var line = ""; + 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 || ""); + } + } else if (isConstructor) { + line += "new " + (functionName || ""); + } 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) { + 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(globalProcessVersion()) ? 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; +} + +// 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 (emptyCacheBetweenOperations) { + fileContentsCache = {}; + sourceMapCache = {}; + } + + var name = error.name || 'Error'; + var message = error.message || ''; + var errorString = name + ": " + message; + + 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 = fileContentsCache[source]; + + // Support files on disk + if (!contents && fs && fs.existsSync(source)) { + try { + contents = fs.readFileSync(source, '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 printErrorAndExit (error) { + var source = getErrorSource(error); + + // Ensure error is printed synchronously and not truncated + var stderr = globalProcessStderr(); + if (stderr && stderr._handle && stderr._handle.setBlocking) { + stderr._handle.setBlocking(true); + } + + if (source) { + console.error(); + console.error(source); + } + + console.error(error.stack); + globalProcessExit(1); +} + +function shimEmitUncaughtException () { + var origEmit = process.emit; + + process.emit = function (type) { + if (type === 'uncaughtException') { + var hasStack = (arguments[1] && arguments[1].stack); + var hasListeners = (this.listeners(type).length > 0); + + if (hasStack && !hasListeners) { + return printErrorAndExit(arguments[1]); + } + } + + return origEmit.apply(this, arguments); + }; +} + +var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0); +var originalRetrieveMapHandlers = 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}") + } + } + + // Allow sources to be found by methods other than reading the files + // directly from disk. + if (options.retrieveFile) { + if (options.overrideRetrieveFile) { + retrieveFileHandlers.length = 0; + } + + 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) { + retrieveMapHandlers.length = 0; + } + + retrieveMapHandlers.unshift(options.retrieveSourceMap); + } + + // Support runtime transpilers that include inline source maps + if (options.hookRequire && !isInBrowser()) { + // Use dynamicRequire to avoid including in browser bundles + var Module = dynamicRequire(module, 'module'); + var $compile = Module.prototype._compile; + + if (!$compile.__sourceMapSupport) { + Module.prototype._compile = function(content, filename) { + fileContentsCache[filename] = content; + sourceMapCache[filename] = undefined; + return $compile.call(this, content, filename); + }; + + Module.prototype._compile.__sourceMapSupport = true; + } + } + + // Configure options + if (!emptyCacheBetweenOperations) { + emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ? + options.emptyCacheBetweenOperations : false; + } + + // Install the error reformatter + if (!errorFormatterInstalled) { + errorFormatterInstalled = true; + Error.prepareStackTrace = prepareStackTrace; + } + + if (!uncaughtShimInstalled) { + 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()) { + uncaughtShimInstalled = true; + shimEmitUncaughtException(); + } + } +}; + +exports.resetRetrieveHandlers = function() { + retrieveFileHandlers.length = 0; + retrieveMapHandlers.length = 0; + + retrieveFileHandlers = originalRetrieveFileHandlers.slice(0); + retrieveMapHandlers = originalRetrieveMapHandlers.slice(0); + + retrieveSourceMap = handlerExec(retrieveMapHandlers); + retrieveFile = handlerExec(retrieveFileHandlers); +} diff --git a/node_modules/space-separated-tokens/index.d.ts b/node_modules/space-separated-tokens/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe504d81b13fa7502dd519c42e228f372f5d9b49 --- /dev/null +++ b/node_modules/space-separated-tokens/index.d.ts @@ -0,0 +1,18 @@ +/** + * Parse space-separated tokens to an array of strings. + * + * @param {string} value + * Space-separated tokens. + * @returns {Array} + * List of tokens. + */ +export function parse(value: string): Array +/** + * Serialize an array of strings as space separated-tokens. + * + * @param {Array} values + * List of tokens. + * @returns {string} + * Space-separated tokens. + */ +export function stringify(values: Array): string diff --git a/node_modules/space-separated-tokens/index.js b/node_modules/space-separated-tokens/index.js new file mode 100644 index 0000000000000000000000000000000000000000..18810b1a4c778a2ef2726f9fc54b786a7fb65b06 --- /dev/null +++ b/node_modules/space-separated-tokens/index.js @@ -0,0 +1,24 @@ +/** + * Parse space-separated tokens to an array of strings. + * + * @param {string} value + * Space-separated tokens. + * @returns {Array} + * List of tokens. + */ +export function parse(value) { + const input = String(value || '').trim() + return input ? input.split(/[ \t\n\r\f]+/g) : [] +} + +/** + * Serialize an array of strings as space separated-tokens. + * + * @param {Array} values + * List of tokens. + * @returns {string} + * Space-separated tokens. + */ +export function stringify(values) { + return values.join(' ').trim() +} diff --git a/node_modules/space-separated-tokens/license b/node_modules/space-separated-tokens/license new file mode 100644 index 0000000000000000000000000000000000000000..8d8660d36ef2eced1f9cce91e17ae0290261734c --- /dev/null +++ b/node_modules/space-separated-tokens/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2016 Titus Wormer + +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. diff --git a/node_modules/space-separated-tokens/package.json b/node_modules/space-separated-tokens/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f0c5c9bb7013b6631ae985732a151846358560c5 --- /dev/null +++ b/node_modules/space-separated-tokens/package.json @@ -0,0 +1,67 @@ +{ + "name": "space-separated-tokens", + "version": "2.0.2", + "description": "Parse and stringify space separated tokens", + "license": "MIT", + "keywords": [ + "dom", + "html", + "space", + "separated", + "tokens", + "parse", + "stringify" + ], + "repository": "wooorm/space-separated-tokens", + "bugs": "https://github.com/wooorm/space-separated-tokens/issues", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + }, + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "main": "index.js", + "types": "index.d.ts", + "files": [ + "index.d.ts", + "index.js" + ], + "devDependencies": { + "@types/node": "^18.0.0", + "c8": "^7.0.0", + "prettier": "^2.0.0", + "remark-cli": "^11.0.0", + "remark-preset-wooorm": "^9.0.0", + "type-coverage": "^2.0.0", + "typescript": "^4.0.0", + "xo": "^0.52.0" + }, + "scripts": { + "prepack": "npm run build && npm run format", + "build": "tsc --build --clean && tsc --build && type-coverage", + "format": "remark . -qfo && prettier . -w --loglevel warn && xo --fix", + "test-api": "node --conditions development test.js", + "test-coverage": "c8 --check-coverage --100 --reporter lcov npm run test-api", + "test": "npm run build && npm run format && npm run test-coverage" + }, + "prettier": { + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "bracketSpacing": false, + "semi": false, + "trailingComma": "none" + }, + "xo": { + "prettier": true + }, + "remarkConfig": { + "plugins": [ + "preset-wooorm" + ] + } +} diff --git a/node_modules/space-separated-tokens/readme.md b/node_modules/space-separated-tokens/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..eb187d3619c59b4192b02608ebb749d0446bd932 --- /dev/null +++ b/node_modules/space-separated-tokens/readme.md @@ -0,0 +1,156 @@ +# space-separated-tokens + +[![Build][build-badge]][build] +[![Coverage][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] + +Parse and stringify space-separated tokens. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`parse(value)`](#parsevalue) + * [`stringify(values)`](#stringifyvalues) +* [Types](#types) +* [Compatibility](#compatibility) +* [Related](#related) +* [Contribute](#contribute) +* [Security](#security) +* [License](#license) + +## What is this? + +This is a tiny package that can parse and stringify space-separated tokens, as +used for example in the HTML `class` attribute, according to the +[WHATWG spec][spec]. + +## When should I use this? + +This package is rather niche, it’s low-level and particularly useful when +working with [hast][]. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 14.14+, 16.0+), install with [npm][]: + +```sh +npm install space-separated-tokens +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {parse, stringify} from 'https://esm.sh/space-separated-tokens@2' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {parse, stringify} from 'space-separated-tokens' + +parse(' foo\tbar\nbaz ') +//=> ['foo', 'bar', 'baz'] + +stringify(['foo', 'bar', 'baz']) +//=> 'foo bar baz' +``` + +## API + +This package exports the identifiers `parse` and `stringify`. +There is no default export. + +### `parse(value)` + +Parse space-separated tokens (`string`) to an array of strings +(`Array`), according to the [WHATWG spec][spec]. + +### `stringify(values)` + +Serialize an array of strings or numbers (`Array`) to +space-separated tokens (`string`). + +> 👉 **Note**: it’s not possible to specify empty or whitespace only values. + +## Types + +This package is fully typed with [TypeScript][]. +It exports no additional types. + +## Compatibility + +This package is at least compatible with all maintained versions of Node.js. +As of now, that is Node.js 14.14+ and 16.0+. +It also works in Deno and modern browsers. + +## Related + +* [`comma-separated-tokens`](https://github.com/wooorm/comma-separated-tokens) + — parse/stringify comma-separated tokens +* [`collapse-white-space`](https://github.com/wooorm/collapse-white-space) + — replace multiple white-space characters with a single space +* [`property-information`](https://github.com/wooorm/property-information) + — info on HTML properties + +## Contribute + +Yes please! +See [How to Contribute to Open Source][contribute]. + +## Security + +This package is safe. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/wooorm/space-separated-tokens/workflows/main/badge.svg + +[build]: https://github.com/wooorm/space-separated-tokens/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/space-separated-tokens.svg + +[coverage]: https://codecov.io/github/wooorm/space-separated-tokens + +[downloads-badge]: https://img.shields.io/npm/dm/space-separated-tokens.svg + +[downloads]: https://www.npmjs.com/package/space-separated-tokens + +[size-badge]: https://img.shields.io/bundlephobia/minzip/space-separated-tokens.svg + +[size]: https://bundlephobia.com/result?p=space-separated-tokens + +[npm]: https://docs.npmjs.com/cli/install + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[esmsh]: https://esm.sh + +[typescript]: https://www.typescriptlang.org + +[contribute]: https://opensource.guide/how-to-contribute/ + +[license]: license + +[author]: https://wooorm.com + +[spec]: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#space-separated-tokens + +[hast]: https://github.com/syntax-tree/hast diff --git a/node_modules/splaytree/Readme.md b/node_modules/splaytree/Readme.md new file mode 100644 index 0000000000000000000000000000000000000000..385a9216564b80d8333705b8b7af3c1629d8fb63 --- /dev/null +++ b/node_modules/splaytree/Readme.md @@ -0,0 +1,202 @@ +# Splay tree [![npm version](https://badge.fury.io/js/splaytree.svg)](https://badge.fury.io/js/splaytree) [![CircleCI](https://circleci.com/gh/w8r/splay-tree.svg?style=svg)](https://circleci.com/gh/w8r/splay-tree) + +[Splay-tree](https://en.wikipedia.org/wiki/Splay_tree): **[fast](#benchmarks)**(non-recursive) and **simple**(< 500 lines of code) +Implementation is adapted directly from Wikipedia with the same API as [w8r/avl](https://github.com/w8r/avl), to run the benchmarks agains other trees. + +![Splay-tree](https://i.stack.imgur.com/CNSAZ.png) + +| Operation | Average | Worst case | +| ------------- | ------------- | ---------------------- | +| Space | **O(n)** | **O(n)** | +| Search | **O(log n)** | **amortized O(log n)** | +| Insert | **O(log n)** | **amortized O(log n)** | +| Delete | **O(log n)** | **amortized O(log n)** | + + +## Install + +```shell +npm i -S splaytree +``` + +```js +import SplayTree from 'splaytree'; +const tree = new SplayTree(); +``` + +Or get it from CDN +```html + + +``` +Or use the compiled version 'dist/splay.js'. + +[Try it in your browser](https://npm.runkit.com/splaytree) + +## API + +* `new SplayTree([comparator], [noDuplicates:Boolean])`, where `comparator` is optional comparison function +* `tree.insert(key:any, [data:any]):Node` - Insert item +* `tree.remove(key:any):Boolean` - Remove item +* `tree.removeNode(Node:any)|Boolean` - Remove node +* `tree.find(key):Node|Null` - Return node by its key +* `tree.at(index:Number):Node|Null` - Return node by its index in sorted order of keys +* `tree.contains(key):Boolean` - Whether a node with the given key is in the tree +* `tree.forEach(function(node) {...}):Tree` In-order traversal +* `tree.keys():Array` - Returns the array of keys in order +* `tree.values():Array<*>` - Returns the array of data fields in order +* `tree.range(lo, high, function(node) {} [, context]):Tree` - Walks the range of keys in order. Stops, if the visitor function returns a non-zero value. +* `tree.pop():Node` - Removes smallest node +* `tree.min():key` - Returns min key +* `tree.max():key` - Returns max key +* `tree.minNode():Node` - Returns the node with smallest key +* `tree.maxNode():Node` - Returns the node with highest key +* `tree.prev(node):Node` - Predecessor node +* `tree.next(node):Node` - Successor node +* `tree.load(keys:Array<*>, [values:Array<*>][,presort=false]):Tree` - Bulk-load items. It expects values and keys to be sorted, but if `presort` is `true`, it will sort keys and values using the comparator(in-place!). You can only use it on an empty tree. +* `SplayTree.createTree(keys:Array, [values:Array][,comparator][,presort:Boolean][,noDuplicates:Boolean]):SplayTree` - creates and loads the tree. Equivalent of `new SplayTree(comparator, noDuplicates).load(keys, values, presort)`. + +**Comparator** + +`function(a:key,b:key):Number` - Comparator function between two keys, it returns + * `0` if the keys are equal + * `<0` if `a < b` + * `>0` if `a > b` + + The comparator function is extremely important, in case of errors you might end + up with a wrongly constructed tree or would not be able to retrieve your items. + It is crucial to test the return values of your `comparator(a,b)` and `comparator(b,a)` + to make sure it's working correctly, otherwise you may have bugs that are very + unpredictable and hard to catch. + + **Duplicate keys** + + By default, tree allows duplicate keys. You can disable that by passing `true` + as a second parameter to the tree constructor. In that case if you would try to + instert an item with the key, that is already present in the tree, it will not + be inserted. + However, the default behavior allows for duplicate keys, cause there are cases + where you cannot predict that the keys would be unique (example: overlapping + points in 2D). + +## Example + +```js +import Tree from 'splaytree'; + +const t = new Tree(); +t.insert(5); +t.insert(-10); +t.insert(0); +t.insert(33); +t.insert(2); + +console.log(t.keys()); // [-10, 0, 2, 5, 33] +console.log(t.size); // 5 +console.log(t.min()); // -10 +console.log(t.max()); // -33 + +t.remove(0); +console.log(t.size); // 4 +``` + +**Custom comparator (reverse sort)** + +```js +import Tree from 'splaytree'; + +const t = new Tree((a, b) => b - a); +t.insert(5); +t.insert(-10); +t.insert(0); +t.insert(33); +t.insert(2); + +console.log(t.keys()); // [33, 5, 2, 0, -10] +``` + +**Bulk insert** + +```js +import Tree from 'splaytree'; + +const t = new Tree(); +t.load([3,2,-10,20], ['C', 'B', 'A', 'D']); +console.log(t.keys()); // [-10, 2, 3, 20] +console.log(t.values()); // ['A', 'B', 'C', 'D'] +``` + +## Benchmarks + +```shell +npm run benchmark +``` + +``` +Insert (x1000) +Bintrees x 3,320 ops/sec ±4.69% (81 runs sampled) +Functional red black tree x 1,717 ops/sec ±7.36% (71 runs sampled) +Google Closure library AVL x 538 ops/sec ±7.55% (70 runs sampled) +Splay (current) x 1,783 ops/sec ±6.07% (73 runs sampled) +AVL x 4,790 ops/sec ±4.38% (76 runs sampled) +- Fastest is AVL + +Random read (x1000) +Bintrees x 7,342 ops/sec ±2.72% (83 runs sampled) +Functional red black tree x 12,263 ops/sec ±5.32% (77 runs sampled) +Google Closure library AVL x 19.12 ops/sec ±12.82% (39 runs sampled) +Splay (current) x 14,897 ops/sec ±1.16% (85 runs sampled) +AVL x 14,381 ops/sec ±2.42% (88 runs sampled) +- Fastest is Splay (current) + +Remove (x1000) +Bintrees x 99,828 ops/sec ±2.22% (83 runs sampled) +Functional red black tree x 22,012 ops/sec ±4.16% (80 runs sampled) +Splay (current) x 112,646 ops/sec ±4.04% (80 runs sampled) +Google Closure library AVL x 25,676 ops/sec ±3.97% (75 runs sampled) +AVL x 78,340 ops/sec ±2.44% (85 runs sampled) +- Fastest is Splay (current) +``` + +Adding google closure library to the benchmark is, of course, unfair, cause the +node.js version of it is not optimised by the compiler, but in this case it +plays the role of straight-forward robust implementation. + +## Develop + +```shell +npm i +npm t +npm run build +``` + +## TODO + +- [ ] Add option for bubbling elements up as you retrieve them +- [ ] Fix splaying for performance + +## License + +The MIT License (MIT) + +Copyright (c) 2017 Alexander Milevski + +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. diff --git a/node_modules/splaytree/index.d.ts b/node_modules/splaytree/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..53a14f3b54bd65126ea2a0d62eb0c2ac2c1f66cd --- /dev/null +++ b/node_modules/splaytree/index.d.ts @@ -0,0 +1,39 @@ +export type Node = { + parent?: Node, + left?: Node, + right?: Node, + balanceFactor: number, + key?: Key, + data?: Value +}; +export type Comparator = (a: Key, b: Key) => number +export type ForEachCallback = (node: Node, index: number) => void +export type TraverseCallback = (node: Node) => (void | boolean) + +export default class SplayTree { + constructor (comparator?: Comparator, noDuplicates?: boolean); + size: number; + insert(key: Key, data?: Value): Node; + remove(key: Key): boolean; + removeNode(node: Node): boolean; + find(key: Key): Node; + at(index: number): Node; + contains(key: Key): boolean; + isEmpty(): boolean; + keys(): Array; + values(): Array; + range(minKey:Key, maxKey:Key, visit:TraverseCallback, context?:any); + pop(): Node; + min(): Key; + max(): Key; + minNode(): Node; + maxNode(): Node; + forEach(callback: ForEachCallback): SplayTree; + load(keys: Array, values?:Array, presort?:Boolean): SplayTree; + prev(node: Node): Node; + next(node: Node): Node; + isBalanced(): boolean; + toString(): string; + destroy(): SplayTree; + static createTree(keys: Array, values?:Array, comparator?: Comparator, presort?:Boolean, noDuplicates?: boolean):SplayTree +} diff --git a/node_modules/splaytree/index.js b/node_modules/splaytree/index.js new file mode 100644 index 0000000000000000000000000000000000000000..478a7fd489938e03d798808ca912ee8360d2a5e1 --- /dev/null +++ b/node_modules/splaytree/index.js @@ -0,0 +1,606 @@ +function DEFAULT_COMPARE (a, b) { return a > b ? 1 : a < b ? -1 : 0; } + +export default class SplayTree { + + constructor(compare = DEFAULT_COMPARE, noDuplicates = false) { + this._compare = compare; + this._root = null; + this._size = 0; + this._noDuplicates = !!noDuplicates; + } + + + rotateLeft(x) { + var y = x.right; + if (y) { + x.right = y.left; + if (y.left) y.left.parent = x; + y.parent = x.parent; + } + + if (!x.parent) this._root = y; + else if (x === x.parent.left) x.parent.left = y; + else x.parent.right = y; + if (y) y.left = x; + x.parent = y; + } + + + rotateRight(x) { + var y = x.left; + if (y) { + x.left = y.right; + if (y.right) y.right.parent = x; + y.parent = x.parent; + } + + if (!x.parent) this._root = y; + else if(x === x.parent.left) x.parent.left = y; + else x.parent.right = y; + if (y) y.right = x; + x.parent = y; + } + + + _splay(x) { + while (x.parent) { + var p = x.parent; + if (!p.parent) { + if (p.left === x) this.rotateRight(p); + else this.rotateLeft(p); + } else if (p.left === x && p.parent.left === p) { + this.rotateRight(p.parent); + this.rotateRight(p); + } else if (p.right === x && p.parent.right === p) { + this.rotateLeft(p.parent); + this.rotateLeft(p); + } else if (p.left === x && p.parent.right === p) { + this.rotateRight(p); + this.rotateLeft(p); + } else { + this.rotateLeft(p); + this.rotateRight(p); + } + } + } + + + splay(x) { + var p, gp, ggp, l, r; + + while (x.parent) { + p = x.parent; + gp = p.parent; + + if (gp && gp.parent) { + ggp = gp.parent; + if (ggp.left === gp) ggp.left = x; + else ggp.right = x; + x.parent = ggp; + } else { + x.parent = null; + this._root = x; + } + + l = x.left; r = x.right; + + if (x === p.left) { // left + if (gp) { + if (gp.left === p) { + /* zig-zig */ + if (p.right) { + gp.left = p.right; + gp.left.parent = gp; + } else gp.left = null; + + p.right = gp; + gp.parent = p; + } else { + /* zig-zag */ + if (l) { + gp.right = l; + l.parent = gp; + } else gp.right = null; + + x.left = gp; + gp.parent = x; + } + } + if (r) { + p.left = r; + r.parent = p; + } else p.left = null; + + x.right = p; + p.parent = x; + } else { // right + if (gp) { + if (gp.right === p) { + /* zig-zig */ + if (p.left) { + gp.right = p.left; + gp.right.parent = gp; + } else gp.right = null; + + p.left = gp; + gp.parent = p; + } else { + /* zig-zag */ + if (r) { + gp.left = r; + r.parent = gp; + } else gp.left = null; + + x.right = gp; + gp.parent = x; + } + } + if (l) { + p.right = l; + l.parent = p; + } else p.right = null; + + x.left = p; + p.parent = x; + } + } + } + + + replace(u, v) { + if (!u.parent) this._root = v; + else if (u === u.parent.left) u.parent.left = v; + else u.parent.right = v; + if (v) v.parent = u.parent; + } + + + minNode(u = this._root) { + if (u) while (u.left) u = u.left; + return u; + } + + + maxNode(u = this._root) { + if (u) while (u.right) u = u.right; + return u; + } + + + insert(key, data) { + var z = this._root; + var p = null; + var comp = this._compare; + var cmp; + + if (this._noDuplicates) { + while (z) { + p = z; + cmp = comp(z.key, key); + if (cmp === 0) return; + else if (comp(z.key, key) < 0) z = z.right; + else z = z.left; + } + } else { + while (z) { + p = z; + if (comp(z.key, key) < 0) z = z.right; + else z = z.left; + } + } + + z = { key, data, left: null, right: null, parent: p }; + + if (!p) this._root = z; + else if (comp(p.key, z.key) < 0) p.right = z; + else p.left = z; + + this.splay(z); + this._size++; + return z; + } + + + find (key) { + var z = this._root; + var comp = this._compare; + while (z) { + var cmp = comp(z.key, key); + if (cmp < 0) z = z.right; + else if (cmp > 0) z = z.left; + else return z; + } + return null; + } + + /** + * Whether the tree contains a node with the given key + * @param {Key} key + * @return {boolean} true/false + */ + contains (key) { + var node = this._root; + var comparator = this._compare; + while (node) { + var cmp = comparator(key, node.key); + if (cmp === 0) return true; + else if (cmp < 0) node = node.left; + else node = node.right; + } + + return false; + } + + + remove (key) { + var z = this.find(key); + + if (!z) return false; + + this.splay(z); + + if (!z.left) this.replace(z, z.right); + else if (!z.right) this.replace(z, z.left); + else { + var y = this.minNode(z.right); + if (y.parent !== z) { + this.replace(y, y.right); + y.right = z.right; + y.right.parent = y; + } + this.replace(z, y); + y.left = z.left; + y.left.parent = y; + } + + this._size--; + return true; + } + + + removeNode(z) { + if (!z) return false; + + this.splay(z); + + if (!z.left) this.replace(z, z.right); + else if (!z.right) this.replace(z, z.left); + else { + var y = this.minNode(z.right); + if (y.parent !== z) { + this.replace(y, y.right); + y.right = z.right; + y.right.parent = y; + } + this.replace(z, y); + y.left = z.left; + y.left.parent = y; + } + + this._size--; + return true; + } + + + erase (key) { + var z = this.find(key); + if (!z) return; + + this.splay(z); + + var s = z.left; + var t = z.right; + + var sMax = null; + if (s) { + s.parent = null; + sMax = this.maxNode(s); + this.splay(sMax); + this._root = sMax; + } + if (t) { + if (s) sMax.right = t; + else this._root = t; + t.parent = sMax; + } + + this._size--; + } + + /** + * Removes and returns the node with smallest key + * @return {?Node} + */ + pop () { + var node = this._root, returnValue = null; + if (node) { + while (node.left) node = node.left; + returnValue = { key: node.key, data: node.data }; + this.remove(node.key); + } + return returnValue; + } + + + /* eslint-disable class-methods-use-this */ + + /** + * Successor node + * @param {Node} node + * @return {?Node} + */ + next (node) { + var successor = node; + if (successor) { + if (successor.right) { + successor = successor.right; + while (successor && successor.left) successor = successor.left; + } else { + successor = node.parent; + while (successor && successor.right === node) { + node = successor; successor = successor.parent; + } + } + } + return successor; + } + + + /** + * Predecessor node + * @param {Node} node + * @return {?Node} + */ + prev (node) { + var predecessor = node; + if (predecessor) { + if (predecessor.left) { + predecessor = predecessor.left; + while (predecessor && predecessor.right) predecessor = predecessor.right; + } else { + predecessor = node.parent; + while (predecessor && predecessor.left === node) { + node = predecessor; + predecessor = predecessor.parent; + } + } + } + return predecessor; + } + /* eslint-enable class-methods-use-this */ + + + /** + * @param {forEachCallback} callback + * @return {SplayTree} + */ + forEach(callback) { + var current = this._root; + var s = [], done = false, i = 0; + + while (!done) { + // Reach the left most Node of the current Node + if (current) { + // Place pointer to a tree node on the stack + // before traversing the node's left subtree + s.push(current); + current = current.left; + } else { + // BackTrack from the empty subtree and visit the Node + // at the top of the stack; however, if the stack is + // empty you are done + if (s.length > 0) { + current = s.pop(); + callback(current, i++); + + // We have visited the node and its left + // subtree. Now, it's right subtree's turn + current = current.right; + } else done = true; + } + } + return this; + } + + + /** + * Walk key range from `low` to `high`. Stops if `fn` returns a value. + * @param {Key} low + * @param {Key} high + * @param {Function} fn + * @param {*?} ctx + * @return {SplayTree} + */ + range(low, high, fn, ctx) { + const Q = []; + const compare = this._compare; + let node = this._root, cmp; + + while (Q.length !== 0 || node) { + if (node) { + Q.push(node); + node = node.left; + } else { + node = Q.pop(); + cmp = compare(node.key, high); + if (cmp > 0) { + break; + } else if (compare(node.key, low) >= 0) { + if (fn.call(ctx, node)) return this; // stop if smth is returned + } + node = node.right; + } + } + return this; + } + + /** + * Returns all keys in order + * @return {Array} + */ + keys () { + var current = this._root; + var s = [], r = [], done = false; + + while (!done) { + if (current) { + s.push(current); + current = current.left; + } else { + if (s.length > 0) { + current = s.pop(); + r.push(current.key); + current = current.right; + } else done = true; + } + } + return r; + } + + + /** + * Returns `data` fields of all nodes in order. + * @return {Array} + */ + values () { + var current = this._root; + var s = [], r = [], done = false; + + while (!done) { + if (current) { + s.push(current); + current = current.left; + } else { + if (s.length > 0) { + current = s.pop(); + r.push(current.data); + current = current.right; + } else done = true; + } + } + return r; + } + + + /** + * Returns node at given index + * @param {number} index + * @return {?Node} + */ + at (index) { + // removed after a consideration, more misleading than useful + // index = index % this.size; + // if (index < 0) index = this.size - index; + + var current = this._root; + var s = [], done = false, i = 0; + + while (!done) { + if (current) { + s.push(current); + current = current.left; + } else { + if (s.length > 0) { + current = s.pop(); + if (i === index) return current; + i++; + current = current.right; + } else done = true; + } + } + return null; + } + + /** + * Bulk-load items. Both array have to be same size + * @param {Array} keys + * @param {Array} [values] + * @param {Boolean} [presort=false] Pre-sort keys and values, using + * tree's comparator. Sorting is done + * in-place + * @return {AVLTree} + */ + load(keys = [], values = [], presort = false) { + if (this._size !== 0) throw new Error('bulk-load: tree is not empty'); + const size = keys.length; + if (presort) sort(keys, values, 0, size - 1, this._compare); + this._root = loadRecursive(null, keys, values, 0, size); + this._size = size; + return this; + } + + + min() { + var node = this.minNode(this._root); + if (node) return node.key; + else return null; + } + + + max() { + var node = this.maxNode(this._root); + if (node) return node.key; + else return null; + } + + isEmpty() { return this._root === null; } + get size() { return this._size; } + + + /** + * Create a tree and load it with items + * @param {Array} keys + * @param {Array?} [values] + + * @param {Function?} [comparator] + * @param {Boolean?} [presort=false] Pre-sort keys and values, using + * tree's comparator. Sorting is done + * in-place + * @param {Boolean?} [noDuplicates=false] Allow duplicates + * @return {SplayTree} + */ + static createTree(keys, values, comparator, presort, noDuplicates) { + return new SplayTree(comparator, noDuplicates).load(keys, values, presort); + } +} + + +function loadRecursive (parent, keys, values, start, end) { + const size = end - start; + if (size > 0) { + const middle = start + Math.floor(size / 2); + const key = keys[middle]; + const data = values[middle]; + const node = { key, data, parent }; + node.left = loadRecursive(node, keys, values, start, middle); + node.right = loadRecursive(node, keys, values, middle + 1, end); + return node; + } + return null; +} + + +function sort(keys, values, left, right, compare) { + if (left >= right) return; + + const pivot = keys[(left + right) >> 1]; + let i = left - 1; + let j = right + 1; + + while (true) { + do i++; while (compare(keys[i], pivot) < 0); + do j--; while (compare(keys[j], pivot) > 0); + if (i >= j) break; + + let tmp = keys[i]; + keys[i] = keys[j]; + keys[j] = tmp; + + tmp = values[i]; + values[i] = values[j]; + values[j] = tmp; + } + + sort(keys, values, left, j, compare); + sort(keys, values, j + 1, right, compare); +} diff --git a/node_modules/splaytree/package.json b/node_modules/splaytree/package.json new file mode 100644 index 0000000000000000000000000000000000000000..820cb3e3337c6676b06efc95d2258bb2614ac482 --- /dev/null +++ b/node_modules/splaytree/package.json @@ -0,0 +1,61 @@ +{ + "name": "splaytree", + "version": "0.1.4", + "author": "Alexander Milevski ", + "license": "MIT", + "description": "Fast Splay tree for Node and browser", + "main": "dist/splay.js", + "jsnext:main": "index", + "module": "index", + "types": "index.d.ts", + "files": [ + "dist", + "index.js", + "index.d.ts" + ], + "repository": { + "type": "git", + "url": "https://github.com/w8r/splay.git" + }, + "scripts": { + "prebuild": "npm run lint", + "lint": "eslint src", + "build": "rollup -c build/rollup.config.umd.js && rollup -c build/rollup.config.es6.js && npm run types", + "types": "tsc index.d.ts tests/types.ts", + "pretest": "rollup -c build/rollup.config.tests.js", + "prebenchmark": "npm run build", + "benchmark": "node bench/benchmark.js", + "start": "npm run test:watch", + "test:watch": "nodemon --watch src --watch tests --exec 'npm test'", + "test": "mocha build/tests-bundle.js && npm run types", + "prepublish": "npm run build && npm test" + }, + "devDependencies": { + "avl": "^1.4.0", + "benchmark": "^2.1.4", + "bintrees": "^1.0.1", + "chai": "^4.1.0", + "eslint": "^4.2.0", + "eslint-config-airbnb-base": "^11.2.0", + "eslint-plugin-import": "^2.7.0", + "functional-red-black-tree": "^1.0.1", + "google-closure-library": "^20170626.0.0", + "mocha": "^3.4.2", + "nodemon": "^1.11.0", + "rollup": "^0.45.2", + "rollup-plugin-buble": "^0.15.0", + "rollup-plugin-multi-entry": "^2.0.1", + "rollup-watch": "^4.3.1", + "source-map-support": "^0.4.15", + "tern": "^0.21.0", + "typescript": "^2.4.2" + }, + "keywords": [ + "binary-tree", + "bst", + "splay-tree", + "splay", + "balanced-search-tree" + ], + "dependencies": {} +} diff --git a/node_modules/stackback/.npmignore b/node_modules/stackback/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..3c3629e647f5ddf82548912e337bea9826b434af --- /dev/null +++ b/node_modules/stackback/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/stackback/.travis.yml b/node_modules/stackback/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..320698af0f565b2ac32987b5d23ed6aca5c7ef5a --- /dev/null +++ b/node_modules/stackback/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/stackback/README.md b/node_modules/stackback/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fb6bde7486827b31d96cd2bfc1f96fd945bbf011 --- /dev/null +++ b/node_modules/stackback/README.md @@ -0,0 +1,41 @@ +# stackback + +Returns an array of CallSite objects for a captured stacktrace. Useful if you want to access the frame for an error object. + +## use + +```javascript +var stackback = require('stackback'); + +// error generated from somewhere +var err = new Error('some sample error'); + +// stack is an array of CallSite objects +var stack = stackback(err); +``` + +## CallSite object + +From the [V8 StackTrace API](https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi) + +The structured stack trace is an Array of CallSite objects, each of which represents a stack frame. A CallSite object defines the following methods + +getThis: returns the value of this +getTypeName: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object's [[Class]] internal property. +getFunction: returns the current function +getFunctionName: returns the name of the current function, typically its name property. If a name property is not available an attempt will be made to try to infer a name from the function's context. +getMethodName: returns the name of the property of this or one of its prototypes that holds the current function +getFileName: if this function was defined in a script returns the name of the script +getLineNumber: if this function was defined in a script returns the current line number +getColumnNumber: if this function was defined in a script returns the current column number +getEvalOrigin: if this function was created using a call to eval returns a CallSite object representing the location where eval was called +isToplevel: is this a toplevel invocation, that is, is this the global object? +isEval: does this call take place in code defined by a call to eval? +isNative: is this call in native V8 code? +isConstructor: is this a constructor call? + +## install + +```shell +npm install stackback +``` diff --git a/node_modules/stackback/formatstack.js b/node_modules/stackback/formatstack.js new file mode 100644 index 0000000000000000000000000000000000000000..d64307d210dd134dff936607480695b86f3b6776 --- /dev/null +++ b/node_modules/stackback/formatstack.js @@ -0,0 +1,57 @@ +// Copyright 2012 the V8 project authors. 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. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +function FormatStackTrace(error, frames) { + var lines = []; + try { + lines.push(error.toString()); + } catch (e) { + try { + lines.push(""); + } catch (ee) { + lines.push(""); + } + } + for (var i = 0; i < frames.length; i++) { + var frame = frames[i]; + var line; + try { + line = frame.toString(); + } catch (e) { + try { + line = ""; + } catch (ee) { + // Any code that reaches this point is seriously nasty! + line = ""; + } + } + lines.push(" at " + line); + } + return lines.join("\n"); +} + +module.exports = FormatStackTrace; diff --git a/node_modules/stackback/index.js b/node_modules/stackback/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8b87042343d7e6fc238075138f72f4ff3fa58d5e --- /dev/null +++ b/node_modules/stackback/index.js @@ -0,0 +1,46 @@ + +// v8 builtin format stack trace +// for when there was no previous prepareStackTrace function to call +var FormatStackTrace = require('./formatstack'); + +// some notes on the behavior below: +// because the 'stack' member is a one shot access variable (the raw stack is +// formatted on accessing it) +// we try to avoid modifying what the user would have wanted +// thus we use the previous value for prepareStackTrace +// +// The reason we store the callsite variable is because prepareStackTrace +// will not be called again once it has been called for a given error object +// but we want to support getting the stack out of the error multiple times (cause why not) +module.exports = function(err) { + + // save original stacktrace + var save = Error.prepareStackTrace; + + // replace capture with our function + Error.prepareStackTrace = function(err, trace) { + + // cache stack frames so we don't have to get them again + // use a non-enumerable property + Object.defineProperty(err, '_sb_callsites', { + value: trace + }); + + return (save || FormatStackTrace)(err, trace); + }; + + // force capture of the stack frames + err.stack; + + // someone already asked for the stack so we can't do this trick + // TODO fallback to string parsing? + if (!err._sb_callsites) { + return []; + } + + // return original capture function + Error.prepareStackTrace = save; + + return err._sb_callsites; +}; + diff --git a/node_modules/stackback/package.json b/node_modules/stackback/package.json new file mode 100644 index 0000000000000000000000000000000000000000..3e8b7b2c023d3535e0869b0959616cda4d654fc8 --- /dev/null +++ b/node_modules/stackback/package.json @@ -0,0 +1,23 @@ +{ + "name": "stackback", + "version": "0.0.2", + "description": "return list of CallSite objects from a captured stacktrace", + "main": "index.js", + "scripts": { + "test": "mocha --ui qunit" + }, + "repository": { + "type": "git", + "url": "git://github.com/shtylman/node-stackback.git" + }, + "keywords": [ + "stacktrace", + "trace", + "stack" + ], + "devDependencies": { + "mocha": "~1.6.0" + }, + "author": "Roman Shtylman ", + "license": "MIT" +} diff --git a/node_modules/stackback/test.js b/node_modules/stackback/test.js new file mode 100644 index 0000000000000000000000000000000000000000..212b414ab496cf76d2a6977bd935ce714508482f --- /dev/null +++ b/node_modules/stackback/test.js @@ -0,0 +1,24 @@ +var assert = require('assert'); +var stackback = require('./'); + +test('capture', function() { + var err = new Error(); + var stack = stackback(err); + assert.equal(stack[0].getFileName(), __filename); +}); + +// calling stackback on the same error twice should work +test('multiple calls', function() { + var err = new Error(); + var stack1 = stackback(err); + var stack2 = stackback(err); + assert.equal(stack1[0].getFileName(), __filename); + assert.deepEqual(stack1, stack2); +}); + +test('string', function() { + var err = new Error(); + stackback(err); + assert.equal(typeof err.stack, 'string'); +}); + diff --git a/node_modules/statuses/HISTORY.md b/node_modules/statuses/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..dc549b8216582796d92fb78868317155cc6d1044 --- /dev/null +++ b/node_modules/statuses/HISTORY.md @@ -0,0 +1,87 @@ +2.0.2 / 2025-06-06 +================== + + * Migrate to `String.prototype.slice()` + +2.0.1 / 2021-01-03 +================== + + * Fix returning values from `Object.prototype` + +2.0.0 / 2020-04-19 +================== + + * Drop support for Node.js 0.6 + * Fix messaging casing of `418 I'm a Teapot` + * Remove code 306 + * Remove `status[code]` exports; use `status.message[code]` + * Remove `status[msg]` exports; use `status.code[msg]` + * Rename `425 Unordered Collection` to standard `425 Too Early` + * Rename `STATUS_CODES` export to `message` + * Return status message for `statuses(code)` when given code + +1.5.0 / 2018-03-27 +================== + + * Add `103 Early Hints` + +1.4.0 / 2017-10-20 +================== + + * Add `STATUS_CODES` export + +1.3.1 / 2016-11-11 +================== + + * Fix return type in JSDoc + +1.3.0 / 2016-05-17 +================== + + * Add `421 Misdirected Request` + * perf: enable strict mode + +1.2.1 / 2015-02-01 +================== + + * Fix message for status 451 + - `451 Unavailable For Legal Reasons` + +1.2.0 / 2014-09-28 +================== + + * Add `208 Already Repored` + * Add `226 IM Used` + * Add `306 (Unused)` + * Add `415 Unable For Legal Reasons` + * Add `508 Loop Detected` + +1.1.1 / 2014-09-24 +================== + + * Add missing 308 to `codes.json` + +1.1.0 / 2014-09-21 +================== + + * Add `codes.json` for universal support + +1.0.4 / 2014-08-20 +================== + + * Package cleanup + +1.0.3 / 2014-06-08 +================== + + * Add 308 to `.redirect` category + +1.0.2 / 2014-03-13 +================== + + * Add `.retry` category + +1.0.1 / 2014-03-12 +================== + + * Initial release diff --git a/node_modules/statuses/LICENSE b/node_modules/statuses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..28a31618205d7dbeed5b966fe9d2c682bd9367f5 --- /dev/null +++ b/node_modules/statuses/LICENSE @@ -0,0 +1,23 @@ + +The MIT License (MIT) + +Copyright (c) 2014 Jonathan Ong +Copyright (c) 2016 Douglas Christopher Wilson + +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. diff --git a/node_modules/statuses/README.md b/node_modules/statuses/README.md new file mode 100644 index 0000000000000000000000000000000000000000..89d542f6a4022fa409b0c38875c1c15991081a23 --- /dev/null +++ b/node_modules/statuses/README.md @@ -0,0 +1,139 @@ +# statuses + +[![NPM Version][npm-version-image]][npm-url] +[![NPM Downloads][npm-downloads-image]][npm-url] +[![Node.js Version][node-version-image]][node-version-url] +[![Build Status][ci-image]][ci-url] +[![Test Coverage][coveralls-image]][coveralls-url] +[![OpenSSF Scorecard Badge][ossf-scorecard-badge]][ossf-scorecard-visualizer] + +HTTP status utility for node. + +This module provides a list of status codes and messages sourced from +a few different projects: + + * The [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml) + * The [Node.js project](https://nodejs.org/) + * The [NGINX project](https://www.nginx.com/) + * The [Apache HTTP Server project](https://httpd.apache.org/) + +## Installation + +This is a [Node.js](https://nodejs.org/en/) module available through the +[npm registry](https://www.npmjs.com/). Installation is done using the +[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): + +```sh +$ npm install statuses +``` + +## API + + + +```js +var status = require('statuses') +``` + +### status(code) + +Returns the status message string for a known HTTP status code. The code +may be a number or a string. An error is thrown for an unknown status code. + + + +```js +status(403) // => 'Forbidden' +status('403') // => 'Forbidden' +status(306) // throws +``` + +### status(msg) + +Returns the numeric status code for a known HTTP status message. The message +is case-insensitive. An error is thrown for an unknown status message. + + + +```js +status('forbidden') // => 403 +status('Forbidden') // => 403 +status('foo') // throws +``` + +### status.codes + +Returns an array of all the status codes as `Integer`s. + +### status.code[msg] + +Returns the numeric status code for a known status message (in lower-case), +otherwise `undefined`. + + + +```js +status['not found'] // => 404 +``` + +### status.empty[code] + +Returns `true` if a status code expects an empty body. + + + +```js +status.empty[200] // => undefined +status.empty[204] // => true +status.empty[304] // => true +``` + +### status.message[code] + +Returns the string message for a known numeric status code, otherwise +`undefined`. This object is the same format as the +[Node.js http module `http.STATUS_CODES`](https://nodejs.org/dist/latest/docs/api/http.html#http_http_status_codes). + + + +```js +status.message[404] // => 'Not Found' +``` + +### status.redirect[code] + +Returns `true` if a status code is a valid redirect status. + + + +```js +status.redirect[200] // => undefined +status.redirect[301] // => true +``` + +### status.retry[code] + +Returns `true` if you should retry the rest. + + + +```js +status.retry[501] // => undefined +status.retry[503] // => true +``` + +## License + +[MIT](LICENSE) + +[ci-image]: https://badgen.net/github/checks/jshttp/statuses/master?label=ci +[ci-url]: https://github.com/jshttp/statuses/actions?query=workflow%3Aci +[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/statuses/master +[coveralls-url]: https://coveralls.io/r/jshttp/statuses?branch=master +[node-version-image]: https://badgen.net/npm/node/statuses +[node-version-url]: https://nodejs.org/en/download +[npm-downloads-image]: https://badgen.net/npm/dm/statuses +[npm-url]: https://npmjs.org/package/statuses +[npm-version-image]: https://badgen.net/npm/v/statuses +[ossf-scorecard-badge]: https://api.securityscorecards.dev/projects/github.com/jshttp/statuses/badge +[ossf-scorecard-visualizer]: https://kooltheba.github.io/openssf-scorecard-api-visualizer/#/projects/github.com/jshttp/statuses diff --git a/node_modules/statuses/codes.json b/node_modules/statuses/codes.json new file mode 100644 index 0000000000000000000000000000000000000000..1333ed10bab28344b55c217d80ce4f6cc2555793 --- /dev/null +++ b/node_modules/statuses/codes.json @@ -0,0 +1,65 @@ +{ + "100": "Continue", + "101": "Switching Protocols", + "102": "Processing", + "103": "Early Hints", + "200": "OK", + "201": "Created", + "202": "Accepted", + "203": "Non-Authoritative Information", + "204": "No Content", + "205": "Reset Content", + "206": "Partial Content", + "207": "Multi-Status", + "208": "Already Reported", + "226": "IM Used", + "300": "Multiple Choices", + "301": "Moved Permanently", + "302": "Found", + "303": "See Other", + "304": "Not Modified", + "305": "Use Proxy", + "307": "Temporary Redirect", + "308": "Permanent Redirect", + "400": "Bad Request", + "401": "Unauthorized", + "402": "Payment Required", + "403": "Forbidden", + "404": "Not Found", + "405": "Method Not Allowed", + "406": "Not Acceptable", + "407": "Proxy Authentication Required", + "408": "Request Timeout", + "409": "Conflict", + "410": "Gone", + "411": "Length Required", + "412": "Precondition Failed", + "413": "Payload Too Large", + "414": "URI Too Long", + "415": "Unsupported Media Type", + "416": "Range Not Satisfiable", + "417": "Expectation Failed", + "418": "I'm a Teapot", + "421": "Misdirected Request", + "422": "Unprocessable Entity", + "423": "Locked", + "424": "Failed Dependency", + "425": "Too Early", + "426": "Upgrade Required", + "428": "Precondition Required", + "429": "Too Many Requests", + "431": "Request Header Fields Too Large", + "451": "Unavailable For Legal Reasons", + "500": "Internal Server Error", + "501": "Not Implemented", + "502": "Bad Gateway", + "503": "Service Unavailable", + "504": "Gateway Timeout", + "505": "HTTP Version Not Supported", + "506": "Variant Also Negotiates", + "507": "Insufficient Storage", + "508": "Loop Detected", + "509": "Bandwidth Limit Exceeded", + "510": "Not Extended", + "511": "Network Authentication Required" +} diff --git a/node_modules/statuses/index.js b/node_modules/statuses/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ea351c553520e1bc62d53b97a316194c48ac49e6 --- /dev/null +++ b/node_modules/statuses/index.js @@ -0,0 +1,146 @@ +/*! + * statuses + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ + +'use strict' + +/** + * Module dependencies. + * @private + */ + +var codes = require('./codes.json') + +/** + * Module exports. + * @public + */ + +module.exports = status + +// status code to message map +status.message = codes + +// status message (lower-case) to code map +status.code = createMessageToStatusCodeMap(codes) + +// array of status codes +status.codes = createStatusCodeList(codes) + +// status codes for redirects +status.redirect = { + 300: true, + 301: true, + 302: true, + 303: true, + 305: true, + 307: true, + 308: true +} + +// status codes for empty bodies +status.empty = { + 204: true, + 205: true, + 304: true +} + +// status codes for when you should retry the request +status.retry = { + 502: true, + 503: true, + 504: true +} + +/** + * Create a map of message to status code. + * @private + */ + +function createMessageToStatusCodeMap (codes) { + var map = {} + + Object.keys(codes).forEach(function forEachCode (code) { + var message = codes[code] + var status = Number(code) + + // populate map + map[message.toLowerCase()] = status + }) + + return map +} + +/** + * Create a list of all status codes. + * @private + */ + +function createStatusCodeList (codes) { + return Object.keys(codes).map(function mapCode (code) { + return Number(code) + }) +} + +/** + * Get the status code for given message. + * @private + */ + +function getStatusCode (message) { + var msg = message.toLowerCase() + + if (!Object.prototype.hasOwnProperty.call(status.code, msg)) { + throw new Error('invalid status message: "' + message + '"') + } + + return status.code[msg] +} + +/** + * Get the status message for given code. + * @private + */ + +function getStatusMessage (code) { + if (!Object.prototype.hasOwnProperty.call(status.message, code)) { + throw new Error('invalid status code: ' + code) + } + + return status.message[code] +} + +/** + * Get the status code. + * + * Given a number, this will throw if it is not a known status + * code, otherwise the code will be returned. Given a string, + * the string will be parsed for a number and return the code + * if valid, otherwise will lookup the code assuming this is + * the status message. + * + * @param {string|number} code + * @returns {number} + * @public + */ + +function status (code) { + if (typeof code === 'number') { + return getStatusMessage(code) + } + + if (typeof code !== 'string') { + throw new TypeError('code must be a number or string') + } + + // '403' + var n = parseInt(code, 10) + if (!isNaN(n)) { + return getStatusMessage(n) + } + + return getStatusCode(code) +} diff --git a/node_modules/statuses/package.json b/node_modules/statuses/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b5d016edd9c4eef0bb227af4a01c49e73c5f78dc --- /dev/null +++ b/node_modules/statuses/package.json @@ -0,0 +1,49 @@ +{ + "name": "statuses", + "description": "HTTP status utility", + "version": "2.0.2", + "contributors": [ + "Douglas Christopher Wilson ", + "Jonathan Ong (http://jongleberry.com)" + ], + "repository": "jshttp/statuses", + "license": "MIT", + "keywords": [ + "http", + "status", + "code" + ], + "files": [ + "HISTORY.md", + "index.js", + "codes.json", + "LICENSE" + ], + "devDependencies": { + "csv-parse": "4.16.3", + "eslint": "7.19.0", + "eslint-config-standard": "14.1.1", + "eslint-plugin-import": "2.31.0", + "eslint-plugin-markdown": "1.0.2", + "eslint-plugin-node": "11.1.0", + "eslint-plugin-promise": "4.3.1", + "eslint-plugin-standard": "4.1.0", + "mocha": "8.4.0", + "nyc": "15.1.0", + "raw-body": "2.5.2", + "stream-to-array": "2.3.0" + }, + "engines": { + "node": ">= 0.8" + }, + "scripts": { + "build": "node scripts/build.js", + "fetch": "node scripts/fetch-apache.js && node scripts/fetch-iana.js && node scripts/fetch-nginx.js && node scripts/fetch-node.js", + "lint": "eslint --plugin markdown --ext js,md .", + "test": "mocha --reporter spec --check-leaks --bail test/", + "test-ci": "nyc --reporter=lcov --reporter=text npm test", + "test-cov": "nyc --reporter=html --reporter=text npm test", + "update": "npm run fetch && npm run build", + "version": "node scripts/version-history.js && git add HISTORY.md" + } +} diff --git a/node_modules/std-env/LICENCE b/node_modules/std-env/LICENCE new file mode 100644 index 0000000000000000000000000000000000000000..db8fffe6a1f33b4b247463e60d9528b504a2eba8 --- /dev/null +++ b/node_modules/std-env/LICENCE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) Pooya Parsa + +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. + diff --git a/node_modules/std-env/README.md b/node_modules/std-env/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6a722f010625fa290d4d6cfc10814e0c77bd758b --- /dev/null +++ b/node_modules/std-env/README.md @@ -0,0 +1,91 @@ +# std-env + +[![npm version](https://img.shields.io/npm/v/std-env.svg?style=flat-square)](http://npmjs.com/package/std-env) +[![npm downloads](https://img.shields.io/npm/dm/std-env.svg?style=flat-square)](http://npmjs.com/package/std-env) +[![bundle size](https://img.shields.io/bundlephobia/min/std-env/latest.svg?style=flat-square)](https://bundlephobia.com/result?p=std-env) + +Runtime-agnostic JS utils for detecting environments, runtimes, CI providers, and AI coding agents. + +## Runtime Detection + +Detects the current JavaScript runtime based on global variables, following the [WinterCG Runtime Keys proposal](https://runtime-keys.proposal.wintercg.org/). + +```ts +import { runtime, runtimeInfo } from "std-env"; + +console.log(runtime); // "" | "node" | "deno" | "bun" | "workerd" ... +console.log(runtimeInfo); // { name: "node" } +``` + +Individual named exports: `isNode`, `isBun`, `isDeno`, `isNetlify`, `isEdgeLight`, `isWorkerd`, `isFastly` + +> [!NOTE] +> `isNode` is also `true` in Bun/Deno with Node.js compatibility mode. Use `runtime === "node"` for strict checks. + +See [./src/runtimes.ts](./src/runtimes.ts) for the full list. + +## Provider Detection + +Detects the current CI/CD provider based on environment variables. + +```ts +import { isCI, provider, providerInfo } from "std-env"; + +console.log({ isCI, provider, providerInfo }); +// { isCI: true, provider: "github_actions", providerInfo: { name: "github_actions", ci: true } } +``` + +Use `detectProvider()` to re-run detection. See [./src/providers.ts](./src/providers.ts) for the full list. + +## Agent Detection + +Detects if the environment is running inside an AI coding agent. + +```ts +import { isAgent, agent, agentInfo } from "std-env"; + +console.log({ isAgent, agent, agentInfo }); +// { isAgent: true, agent: "claude", agentInfo: { name: "claude" } } +``` + +Set the `AI_AGENT` env var to explicitly specify the agent name. Use `detectAgent()` to re-run detection. + +Supported agents: `cursor`, `claude`, `devin`, `replit`, `gemini`, `codex`, `auggie`, `opencode`, `kiro`, `goose`, `pi` + +## Flags + +```js +import { env, isDevelopment, isProduction } from "std-env"; +``` + +| Export | Description | +| ------------------ | ------------------------------------------------------------ | +| `hasTTY` | stdout TTY is available | +| `hasWindow` | Global `window` is available | +| `isCI` | Running in CI | +| `isColorSupported` | Terminal color output supported | +| `isDebug` | `DEBUG` env var is set | +| `isDevelopment` | `NODE_ENV` is `dev`/`development` or `MODE` is `development` | +| `isLinux` | Linux platform | +| `isMacOS` | macOS (darwin) platform | +| `isMinimal` | `MINIMAL` env is set, CI, test, or no TTY | +| `isProduction` | `NODE_ENV` or `MODE` is `production` | +| `isTest` | `NODE_ENV` is `test` or `TEST` env is set | +| `isWindows` | Windows platform | +| `platform` | Value of `process.platform` | +| `nodeVersion` | Node.js version string (e.g. `"22.0.0"`) | +| `nodeMajorVersion` | Node.js major version number (e.g. `22`) | + +See [./src/flags.ts](./src/flags.ts) for details. + +## Environment + +| Export | Description | +| --------- | ---------------------------------------------------- | +| `env` | Universal `process.env` (works across all runtimes) | +| `process` | Universal `process` shim (works across all runtimes) | +| `nodeENV` | Current `NODE_ENV` value (undefined if unset) | + +## License + +MIT diff --git a/node_modules/std-env/package.json b/node_modules/std-env/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a2d4f34cfc104a36841ca9b3550373be952399c6 --- /dev/null +++ b/node_modules/std-env/package.json @@ -0,0 +1,42 @@ +{ + "name": "std-env", + "version": "4.1.0", + "description": "Runtime agnostic JS utils", + "license": "MIT", + "repository": "unjs/std-env", + "files": [ + "dist" + ], + "type": "module", + "sideEffects": false, + "main": "./dist/index.mjs", + "types": "./dist/index.d.mts", + "exports": { + ".": "./dist/index.mjs" + }, + "scripts": { + "build": "obuild", + "dev": "vitest", + "lint": "oxlint . && oxfmt", + "lint:fix": "oxlint --fix . && oxfmt", + "prepack": "obuild", + "release": "pnpm test && pnpm build && changelogen --release --publish && git push --follow-tags", + "test": "pnpm lint && pnpm typecheck && vitest run --coverage", + "typecheck": "tsgo --noEmit" + }, + "devDependencies": { + "@types/node": "^25.2.3", + "@typescript/native-preview": "^7.0.0-dev.20260217.1", + "@vitest/coverage-v8": "^4.0.18", + "changelogen": "^0.6.2", + "esbuild": "^0.27.3", + "mitata": "^1.0.34", + "obuild": "^0.4.28", + "oxfmt": "^0.33.0", + "oxlint": "^1.48.0", + "rollup": "^4.57.1", + "typescript": "^5.9.3", + "vitest": "^4.0.18" + }, + "packageManager": "pnpm@10.30.0" +} diff --git a/node_modules/stop-iteration-iterator/.eslintrc b/node_modules/stop-iteration-iterator/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..20f1fabc4c34ae0fb6f1cf1d973677590d153c81 --- /dev/null +++ b/node_modules/stop-iteration-iterator/.eslintrc @@ -0,0 +1,14 @@ +{ + "root": true, + + "extends": "@ljharb", + + "globals": { + "StopIteration": false, + }, + + "rules": { + "func-name-matching": [2, "always"], + "id-length": 0, + }, +} diff --git a/node_modules/stop-iteration-iterator/.github/FUNDING.yml b/node_modules/stop-iteration-iterator/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..4f99ddc0878c5b995c1ed0542ec02dc3d83551d2 --- /dev/null +++ b/node_modules/stop-iteration-iterator/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/stop-iteration-iterator +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/stop-iteration-iterator/.nycrc b/node_modules/stop-iteration-iterator/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/node_modules/stop-iteration-iterator/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/stop-iteration-iterator/CHANGELOG.md b/node_modules/stop-iteration-iterator/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..6ff21b6325ac5605fbe6dcfd1a2849f7db7a5cf6 --- /dev/null +++ b/node_modules/stop-iteration-iterator/CHANGELOG.md @@ -0,0 +1,31 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.0](https://github.com/ljharb/stop-iteration-iterator/compare/v1.0.0...v1.1.0) - 2024-12-13 + +### Commits + +- [New] add types [`f0ee985`](https://github.com/ljharb/stop-iteration-iterator/commit/f0ee985afeccf2950e693757266c77baeaab50f5) +- [actions] split out node 10-20, and 20+ [`b49d910`](https://github.com/ljharb/stop-iteration-iterator/commit/b49d9101ff21b27e30ce6b2c52e121b36efaa7e8) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `npmignore`, `tape` [`2bdaff7`](https://github.com/ljharb/stop-iteration-iterator/commit/2bdaff787a45d4034c079bd308c4a9ba2b09950e) +- [types] clean up tsconfig [`c275b15`](https://github.com/ljharb/stop-iteration-iterator/commit/c275b15940ed12955e77bf2fd764ff507788637d) +- [meta] clean up changelog [`a3eeb9a`](https://github.com/ljharb/stop-iteration-iterator/commit/a3eeb9a763063e27a560f09d25b865f40e373154) +- [Robustness] use `es-errors` [`ca51cb8`](https://github.com/ljharb/stop-iteration-iterator/commit/ca51cb8d7ef259e4aa8e4a9289f0c187fc08d560) +- [Tests] replace `aud` with `npm audit` [`d4b8df0`](https://github.com/ljharb/stop-iteration-iterator/commit/d4b8df04328f133b65bec028c5f78715cd061357) +- [Deps] update `internal-slot` [`61ca626`](https://github.com/ljharb/stop-iteration-iterator/commit/61ca626be1bd5e9bb6051f70b32e3d49b8abcd6a) +- [Deps] update `internal-slot` [`cdabf84`](https://github.com/ljharb/stop-iteration-iterator/commit/cdabf8419d448faaacd1b5d87c839acb7a6eb899) +- [meta] add `sideEffects` flag [`a5f6cb6`](https://github.com/ljharb/stop-iteration-iterator/commit/a5f6cb6e9fa8859115e452c22d4ef90366dc4d0f) +- [Dev Deps] add missing peer dep [`6f6496e`](https://github.com/ljharb/stop-iteration-iterator/commit/6f6496ec5c47499f5e30b80268e2ce545a5469ba) + +## v1.0.0 - 2023-01-12 + +### Commits + +- Initial implementation, tests, readme [`43e8109`](https://github.com/ljharb/stop-iteration-iterator/commit/43e81099d2f2b63ff3a8a253ad13dd8279c9e2dc) +- Initial commit [`23929ce`](https://github.com/ljharb/stop-iteration-iterator/commit/23929ce525165bfe54f053284fd066dce8598486) +- npm init [`a9847ab`](https://github.com/ljharb/stop-iteration-iterator/commit/a9847ab637a7c223fb7478d47caf04e89ba283ff) +- Only apps should have lockfiles [`4e41f3f`](https://github.com/ljharb/stop-iteration-iterator/commit/4e41f3fbbaf8a1d32b12514d7296961e5df73e4b) diff --git a/node_modules/stop-iteration-iterator/LICENSE b/node_modules/stop-iteration-iterator/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b4213ac640ad53446325d2dab2c2bc8620406b72 --- /dev/null +++ b/node_modules/stop-iteration-iterator/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Jordan Harband + +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. diff --git a/node_modules/stop-iteration-iterator/README.md b/node_modules/stop-iteration-iterator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..851860db95c22430fcc89c916f713916c97df584 --- /dev/null +++ b/node_modules/stop-iteration-iterator/README.md @@ -0,0 +1,42 @@ +# stop-iteration-iterator [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +Firefox 17-26 iterators throw a StopIteration object to indicate "done". This normalizes it. + +# Usage + +```js +var stopIterationIterator = require('stop-iteration-iterator'); + +var s = new Set([1, 2]); + +var iterator = stopIterationIterator(s.keys()); + +iterator.next(); // { done: false, value: 1 } +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + + +[package-url]: https://npmjs.org/package/stop-iteration-iterator +[npm-version-svg]: https://versionbadg.es/ljharb/stop-iteration-iterator.svg +[deps-svg]: https://david-dm.org/ljharb/stop-iteration-iterator.svg +[deps-url]: https://david-dm.org/ljharb/stop-iteration-iterator +[dev-deps-svg]: https://david-dm.org/ljharb/stop-iteration-iterator/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/stop-iteration-iterator#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/stop-iteration-iterator.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/stop-iteration-iterator.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/stop-iteration-iterator.svg +[downloads-url]: https://npm-stat.com/charts.html?package=stop-iteration-iterator +[codecov-image]: https://codecov.io/gh/ljharb/stop-iteration-iterator/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/stop-iteration-iterator/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/stop-iteration-iterator +[actions-url]: https://github.com/ljharb/stop-iteration-iterator/actions diff --git a/node_modules/stop-iteration-iterator/index.d.ts b/node_modules/stop-iteration-iterator/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e0b92ff4f6caea0e4c85c5b5384719921e5f3696 --- /dev/null +++ b/node_modules/stop-iteration-iterator/index.d.ts @@ -0,0 +1,7 @@ +declare global { + const StopIteration: (object & { readonly __brand__?: unique symbol }) | undefined; +} + +declare function getStopIterationIterator(origIterator: { next(): IteratorResult }): Iterator; + +export = getStopIterationIterator; \ No newline at end of file diff --git a/node_modules/stop-iteration-iterator/index.js b/node_modules/stop-iteration-iterator/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d1d751da58bf339dfe8a2a24940b82812d801e66 --- /dev/null +++ b/node_modules/stop-iteration-iterator/index.js @@ -0,0 +1,46 @@ +'use strict'; + +var SLOT = require('internal-slot'); +var $SyntaxError = require('es-errors/syntax'); + +var $StopIteration = typeof StopIteration === 'object' ? StopIteration : null; + +/** @type {import('.')} */ +module.exports = function getStopIterationIterator(origIterator) { + if (!$StopIteration) { + throw new $SyntaxError('this environment lacks StopIteration'); + } + + SLOT.set(origIterator, '[[Done]]', false); + + /** @template T @typedef {T extends Iterator ? U : never} IteratorType */ + /** @typedef {IteratorType>} T */ + var siIterator = { + next: /** @type {() => IteratorResult} */ function next() { + // eslint-disable-next-line no-extra-parens + var iterator = /** @type {typeof origIterator} */ (SLOT.get(this, '[[Iterator]]')); + var done = !!SLOT.get(iterator, '[[Done]]'); + try { + return { + done: done, + // eslint-disable-next-line no-extra-parens + value: done ? void undefined : /** @type {T} */ (iterator.next()) + }; + } catch (e) { + SLOT.set(iterator, '[[Done]]', true); + if (e !== $StopIteration) { + throw e; + } + return { + done: true, + value: void undefined + }; + } + } + }; + + SLOT.set(siIterator, '[[Iterator]]', origIterator); + + // @ts-expect-error TODO FIXME + return siIterator; +}; diff --git a/node_modules/stop-iteration-iterator/package.json b/node_modules/stop-iteration-iterator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6046d2fb4882476b13f75bf4c545973ab6997f13 --- /dev/null +++ b/node_modules/stop-iteration-iterator/package.json @@ -0,0 +1,77 @@ +{ + "name": "stop-iteration-iterator", + "version": "1.1.0", + "description": "Firefox 17-26 iterators throw a StopIteration object to indicate \"done\". This normalizes it.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc && attw -P", + "pretest": "npm run lint", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/stop-iteration-iterator.git" + }, + "keywords": [ + "stopiteration", + "iterator", + "firefox" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/stop-iteration-iterator/issues" + }, + "homepage": "https://github.com/ljharb/stop-iteration-iterator#readme", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.1", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.2", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/stop-iteration-iterator/test/index.js b/node_modules/stop-iteration-iterator/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7ba13daab1ff91540e4a4ab3c634eb846177ff45 --- /dev/null +++ b/node_modules/stop-iteration-iterator/test/index.js @@ -0,0 +1,51 @@ +'use strict'; + +var test = require('tape'); + +var stopIterationIterator = require('../'); + +test('stopIterationIterator', function (t) { + t.equal(typeof stopIterationIterator, 'function', 'stopIterationIterator is a function'); + + t.test('no StopIteration support', { skip: typeof StopIteration === 'object' }, function (st) { + st['throws']( + // @ts-expect-error + function () { stopIterationIterator(); }, + SyntaxError, + 'throws a SyntaxError when StopIteration is not supported' + ); + + st.end(); + }); + + t.test('StopIteration support', { skip: typeof StopIteration !== 'object' }, function (st) { + // eslint-disable-next-line no-extra-parens + var s = /** @type {Set & { iterator(): SetIterator}} */ (new Set([1, 2])); + + var i = s.iterator(); + st.equal(i.next(), 1, 'first item is 1'); + st.equal(i.next(), 2, 'second item is 2'); + try { + i.next(); + st.fail(); + } catch (e) { + st.equal(e, StopIteration, 'StopIteration thrown'); + } + + // eslint-disable-next-line no-extra-parens + var m = /** @type {Map & { iterator(): MapIterator<[string, number]>}} */ (new Map([[1, 'a'], [2, 'b']])); + var mi = m.iterator(); + st.deepEqual(mi.next(), [1, 'a'], 'first item is 1 and a'); + st.deepEqual(mi.next(), [2, 'b'], 'second item is 2 and b'); + try { + mi.next(); + st.fail(); + } catch (e) { + st.equal(e, StopIteration, 'StopIteration thrown'); + } + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/stop-iteration-iterator/tsconfig.json b/node_modules/stop-iteration-iterator/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..17df18fee2abb31244d4a99c134cc6ce841c121b --- /dev/null +++ b/node_modules/stop-iteration-iterator/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "@ljharb/tsconfig", + "exclude": [ + "coverage", + ], +} \ No newline at end of file diff --git a/node_modules/streamsearch/.eslintrc.js b/node_modules/streamsearch/.eslintrc.js new file mode 100644 index 0000000000000000000000000000000000000000..be9311d02655a22381f13078bfe868bcbd85b3a6 --- /dev/null +++ b/node_modules/streamsearch/.eslintrc.js @@ -0,0 +1,5 @@ +'use strict'; + +module.exports = { + extends: '@mscdex/eslint-config', +}; diff --git a/node_modules/streamsearch/.github/workflows/ci.yml b/node_modules/streamsearch/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..29d51782c77a93f2a32774350fb6e6229ebc3408 --- /dev/null +++ b/node_modules/streamsearch/.github/workflows/ci.yml @@ -0,0 +1,24 @@ +name: CI + +on: + pull_request: + push: + branches: [ master ] + +jobs: + tests-linux: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: [10.x, 12.x, 14.x, 16.x] + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Install module + run: npm install + - name: Run tests + run: npm test diff --git a/node_modules/streamsearch/.github/workflows/lint.yml b/node_modules/streamsearch/.github/workflows/lint.yml new file mode 100644 index 0000000000000000000000000000000000000000..9f9e1f589a30be583a860f928382b3033c38749d --- /dev/null +++ b/node_modules/streamsearch/.github/workflows/lint.yml @@ -0,0 +1,23 @@ +name: lint + +on: + pull_request: + push: + branches: [ master ] + +env: + NODE_VERSION: 16.x + +jobs: + lint-js: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Use Node.js ${{ env.NODE_VERSION }} + uses: actions/setup-node@v1 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Install ESLint + ESLint configs/plugins + run: npm install --only=dev + - name: Lint files + run: npm run lint diff --git a/node_modules/streamsearch/LICENSE b/node_modules/streamsearch/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9ea90e03922d5e31b32e5ff84f4e51a6ca0760b5 --- /dev/null +++ b/node_modules/streamsearch/LICENSE @@ -0,0 +1,19 @@ +Copyright Brian White. All rights reserved. + +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. \ No newline at end of file diff --git a/node_modules/streamsearch/README.md b/node_modules/streamsearch/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c3934d1c7d57119aa31103bc6389838c646e2fc2 --- /dev/null +++ b/node_modules/streamsearch/README.md @@ -0,0 +1,95 @@ +Description +=========== + +streamsearch is a module for [node.js](http://nodejs.org/) that allows searching a stream using the Boyer-Moore-Horspool algorithm. + +This module is based heavily on the Streaming Boyer-Moore-Horspool C++ implementation by Hongli Lai [here](https://github.com/FooBarWidget/boyer-moore-horspool). + + +Requirements +============ + +* [node.js](http://nodejs.org/) -- v10.0.0 or newer + + +Installation +============ + + npm install streamsearch + +Example +======= + +```js + const { inspect } = require('util'); + + const StreamSearch = require('streamsearch'); + + const needle = Buffer.from('\r\n'); + const ss = new StreamSearch(needle, (isMatch, data, start, end) => { + if (data) + console.log('data: ' + inspect(data.toString('latin1', start, end))); + if (isMatch) + console.log('match!'); + }); + + const chunks = [ + 'foo', + ' bar', + '\r', + '\n', + 'baz, hello\r', + '\n world.', + '\r\n Node.JS rules!!\r\n\r\n', + ]; + for (const chunk of chunks) + ss.push(Buffer.from(chunk)); + + // output: + // + // data: 'foo' + // data: ' bar' + // match! + // data: 'baz, hello' + // match! + // data: ' world.' + // match! + // data: ' Node.JS rules!!' + // match! + // data: '' + // match! +``` + + +API +=== + +Properties +---------- + +* **maxMatches** - < _integer_ > - The maximum number of matches. Defaults to `Infinity`. + +* **matches** - < _integer_ > - The current match count. + + +Functions +--------- + +* **(constructor)**(< _mixed_ >needle, < _function_ >callback) - Creates and returns a new instance for searching for a _Buffer_ or _string_ `needle`. `callback` is called any time there is non-matching data and/or there is a needle match. `callback` will be called with the following arguments: + + 1. `isMatch` - _boolean_ - Indicates whether a match has been found + + 2. `data` - _mixed_ - If set, this contains data that did not match the needle. + + 3. `start` - _integer_ - The index in `data` where the non-matching data begins (inclusive). + + 4. `end` - _integer_ - The index in `data` where the non-matching data ends (exclusive). + + 5. `isSafeData` - _boolean_ - Indicates if it is safe to store a reference to `data` (e.g. as-is or via `data.slice()`) or not, as in some cases `data` may point to a Buffer whose contents change over time. + +* **destroy**() - _(void)_ - Emits any last remaining unmatched data that may still be buffered and then resets internal state. + +* **push**(< _Buffer_ >chunk) - _integer_ - Processes `chunk`, searching for a match. The return value is the last processed index in `chunk` + 1. + +* **reset**() - _(void)_ - Resets internal state. Useful for when you wish to start searching a new/different stream for example. + diff --git a/node_modules/streamsearch/lib/sbmh.js b/node_modules/streamsearch/lib/sbmh.js new file mode 100644 index 0000000000000000000000000000000000000000..510cae26e67a58d4c1cdfb4ed5afd80c0f50c782 --- /dev/null +++ b/node_modules/streamsearch/lib/sbmh.js @@ -0,0 +1,267 @@ +'use strict'; +/* + Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool +*/ +function memcmp(buf1, pos1, buf2, pos2, num) { + for (let i = 0; i < num; ++i) { + if (buf1[pos1 + i] !== buf2[pos2 + i]) + return false; + } + return true; +} + +class SBMH { + constructor(needle, cb) { + if (typeof cb !== 'function') + throw new Error('Missing match callback'); + + if (typeof needle === 'string') + needle = Buffer.from(needle); + else if (!Buffer.isBuffer(needle)) + throw new Error(`Expected Buffer for needle, got ${typeof needle}`); + + const needleLen = needle.length; + + this.maxMatches = Infinity; + this.matches = 0; + + this._cb = cb; + this._lookbehindSize = 0; + this._needle = needle; + this._bufPos = 0; + + this._lookbehind = Buffer.allocUnsafe(needleLen); + + // Initialize occurrence table. + this._occ = [ + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen, needleLen, needleLen, + needleLen, needleLen, needleLen, needleLen + ]; + + // Populate occurrence table with analysis of the needle, ignoring the last + // letter. + if (needleLen > 1) { + for (let i = 0; i < needleLen - 1; ++i) + this._occ[needle[i]] = needleLen - 1 - i; + } + } + + reset() { + this.matches = 0; + this._lookbehindSize = 0; + this._bufPos = 0; + } + + push(chunk, pos) { + let result; + if (!Buffer.isBuffer(chunk)) + chunk = Buffer.from(chunk, 'latin1'); + const chunkLen = chunk.length; + this._bufPos = pos || 0; + while (result !== chunkLen && this.matches < this.maxMatches) + result = feed(this, chunk); + return result; + } + + destroy() { + const lbSize = this._lookbehindSize; + if (lbSize) + this._cb(false, this._lookbehind, 0, lbSize, false); + this.reset(); + } +} + +function feed(self, data) { + const len = data.length; + const needle = self._needle; + const needleLen = needle.length; + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehindSize - 2] + let pos = -self._lookbehindSize; + const lastNeedleCharPos = needleLen - 1; + const lastNeedleChar = needle[lastNeedleCharPos]; + const end = len - needleLen; + const occ = self._occ; + const lookbehind = self._lookbehind; + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= end) { + const nextPos = pos + lastNeedleCharPos; + const ch = (nextPos < 0 + ? lookbehind[self._lookbehindSize + nextPos] + : data[nextPos]); + + if (ch === lastNeedleChar + && matchNeedle(self, data, pos, lastNeedleCharPos)) { + self._lookbehindSize = 0; + ++self.matches; + if (pos > -self._lookbehindSize) + self._cb(true, lookbehind, 0, self._lookbehindSize + pos, false); + else + self._cb(true, undefined, 0, 0, true); + + return (self._bufPos = pos + needleLen); + } + + pos += occ[ch]; + } + + // No match. + + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !matchNeedle(self, data, pos, len - pos)) + ++pos; + + if (pos < 0) { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = self._lookbehindSize + pos; + + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + self._cb(false, lookbehind, 0, bytesToCutOff, false); + } + + self._lookbehindSize -= bytesToCutOff; + lookbehind.copy(lookbehind, 0, bytesToCutOff, self._lookbehindSize); + lookbehind.set(data, self._lookbehindSize); + self._lookbehindSize += len; + + self._bufPos = len; + return len; + } + + // Discard lookbehind buffer. + self._cb(false, lookbehind, 0, self._lookbehindSize, false); + self._lookbehindSize = 0; + } + + pos += self._bufPos; + + const firstNeedleChar = needle[0]; + + // Lookbehind buffer is now empty. Perform Boyer-Moore-Horspool + // search with optimized character lookup code that only considers + // the current round's haystack data. + while (pos <= end) { + const ch = data[pos + lastNeedleCharPos]; + + if (ch === lastNeedleChar + && data[pos] === firstNeedleChar + && memcmp(needle, 0, data, pos, lastNeedleCharPos)) { + ++self.matches; + if (pos > 0) + self._cb(true, data, self._bufPos, pos, true); + else + self._cb(true, undefined, 0, 0, true); + + return (self._bufPos = pos + needleLen); + } + + pos += occ[ch]; + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while (pos < len) { + if (data[pos] !== firstNeedleChar + || !memcmp(data, pos, needle, 0, len - pos)) { + ++pos; + continue; + } + data.copy(lookbehind, 0, pos, len); + self._lookbehindSize = len - pos; + break; + } + + // Everything until `pos` is guaranteed not to contain needle data. + if (pos > 0) + self._cb(false, data, self._bufPos, pos < len ? pos : len, true); + + self._bufPos = len; + return len; +} + +function matchNeedle(self, data, pos, len) { + const lb = self._lookbehind; + const lbSize = self._lookbehindSize; + const needle = self._needle; + + for (let i = 0; i < len; ++i, ++pos) { + const ch = (pos < 0 ? lb[lbSize + pos] : data[pos]); + if (ch !== needle[i]) + return false; + } + return true; +} + +module.exports = SBMH; diff --git a/node_modules/streamsearch/package.json b/node_modules/streamsearch/package.json new file mode 100644 index 0000000000000000000000000000000000000000..51df8f9707cebd8469d793a8d90050baac1c4d1d --- /dev/null +++ b/node_modules/streamsearch/package.json @@ -0,0 +1,34 @@ +{ + "name": "streamsearch", + "version": "1.1.0", + "author": "Brian White ", + "description": "Streaming Boyer-Moore-Horspool searching for node.js", + "main": "./lib/sbmh.js", + "engines": { + "node": ">=10.0.0" + }, + "devDependencies": { + "@mscdex/eslint-config": "^1.1.0", + "eslint": "^7.32.0" + }, + "scripts": { + "test": "node test/test.js", + "lint": "eslint --cache --report-unused-disable-directives --ext=.js .eslintrc.js lib test", + "lint:fix": "npm run lint -- --fix" + }, + "keywords": [ + "stream", + "horspool", + "boyer-moore-horspool", + "boyer-moore", + "search" + ], + "licenses": [{ + "type": "MIT", + "url": "http://github.com/mscdex/streamsearch/raw/master/LICENSE" + }], + "repository": { + "type": "git", + "url": "http://github.com/mscdex/streamsearch.git" + } +} diff --git a/node_modules/streamsearch/test/test.js b/node_modules/streamsearch/test/test.js new file mode 100644 index 0000000000000000000000000000000000000000..39a04d7f834bea5e8da37c4cf56973a7b3217dd5 --- /dev/null +++ b/node_modules/streamsearch/test/test.js @@ -0,0 +1,70 @@ +'use strict'; + +const assert = require('assert'); + +const StreamSearch = require('../lib/sbmh.js'); + +[ + { + needle: '\r\n', + chunks: [ + 'foo', + ' bar', + '\r', + '\n', + 'baz, hello\r', + '\n world.', + '\r\n Node.JS rules!!\r\n\r\n', + ], + expect: [ + [false, 'foo'], + [false, ' bar'], + [ true, null], + [false, 'baz, hello'], + [ true, null], + [false, ' world.'], + [ true, null], + [ true, ' Node.JS rules!!'], + [ true, ''], + ], + }, + { + needle: '---foobarbaz', + chunks: [ + '---foobarbaz', + 'asdf', + '\r\n', + '---foobarba', + '---foobar', + 'ba', + '\r\n---foobarbaz--\r\n', + ], + expect: [ + [ true, null], + [false, 'asdf'], + [false, '\r\n'], + [false, '---foobarba'], + [false, '---foobarba'], + [ true, '\r\n'], + [false, '--\r\n'], + ], + }, +].forEach((test, i) => { + console.log(`Running test #${i + 1}`); + const { needle, chunks, expect } = test; + + const results = []; + const ss = new StreamSearch(Buffer.from(needle), + (isMatch, data, start, end) => { + if (data) + data = data.toString('latin1', start, end); + else + data = null; + results.push([isMatch, data]); + }); + + for (const chunk of chunks) + ss.push(Buffer.from(chunk)); + + assert.deepStrictEqual(results, expect); +}); diff --git a/node_modules/streamx/LICENSE b/node_modules/streamx/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..c728dc70b96897b4f56c18d41e2965a547f67cfc --- /dev/null +++ b/node_modules/streamx/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Mathias Buus + +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. diff --git a/node_modules/streamx/README.md b/node_modules/streamx/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3ce4305db62bb7f696a580a09a11c55ac230784a --- /dev/null +++ b/node_modules/streamx/README.md @@ -0,0 +1,550 @@ +# streamx + +An iteration of the Node.js core streams with a series of improvements. + +``` +npm install streamx +``` + +[![Build Status](https://github.com/streamxorg/streamx/workflows/Build%20Status/badge.svg)](https://github.com/streamxorg/streamx/actions?query=workflow%3A%22Build+Status%22) + +## Main improvements from Node.js core stream + +#### Proper lifecycle support. + +Streams have an `_open` function that is called before any read/write operation and a `_destroy` +function that is always run as the last part of the stream. + +This makes it easy to maintain state. + +#### Easy error handling + +Fully integrates a `.destroy()` function. When called the stream will wait for any +pending operation to finish and call the stream destroy logic. + +Close is _always_ the last event emitted and `destroy` is always run. + +#### `pipe()` error handles + +`pipe` accepts a callback that is called when the pipeline is fully drained. +It also error handles the streams provided and destroys both streams if either +of them fail. + +#### All streams are both binary and object mode streams + +A `map` function can be provided to map your input data into buffers +or other formats. To indicate how much buffer space each data item takes +an `byteLength` function can be provided as well. + +This removes the need for two modes of streams. + +#### Simplicity + +This is a full rewrite, all contained in one file. + +Lots of stream methods are simplified based on how I and devs I work with actually use streams in the wild. + +#### Backwards compat + +streamx aims to be compatible with Node.js streams whenever it is reasonable to do so. + +This means that streamx streams behave a lot like Node.js streams from the outside but still provides the +improvements above. + +#### Smaller browser footprint + +streamx has a much smaller footprint when compiled for the browser: + +``` +$ for x in stream{,x}; do echo $x: $(browserify -r $x | wc -c) bytes; done +stream: 173844 bytes +streamx: 46943 bytes +``` + +With optimizations turned on, the difference is even more stark: + +``` +$ for x in stream{,x}; do echo $x: $(browserify -r $x -p tinyify | wc -c) bytes; done +stream: 62649 bytes +streamx: 8460 bytes +$ for x in stream{,x}; do echo $x: $(browserify -r $x -p tinyify | gzip | wc -c) "bytes (gzipped)"; done +stream: 18053 bytes (gzipped) +streamx: 2806 bytes (gzipped) +``` + +#### AbortSignal support + +To make it easier to integrate streams in a `async/await` flow, all streams support a `signal` option +that accepts a [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) to as an +alternative means to `.destroy` streams. + +## Usage + +```js +const { Readable } = require('streamx') + +const rs = new Readable({ + read(cb) { + this.push('Cool data') + cb(null) + } +}) + +rs.on('data', (data) => console.log('data:', data)) +``` + +## API + +This streamx package contains 4 streams similar to Node.js core. + +## Readable Stream + +#### `rs = new stream.Readable([options])` + +Create a new readable stream. + +Options include: + +``` +{ + highWaterMark: 16384, // max buffer size in bytes + map: (data) => data, // optional function to map input data + byteLength: (data) => size, // optional function that calculates the byte size of input data + signal: abortController.signal, // optional AbortSignal that triggers `.destroy` when on `abort` + eagerOpen: false // eagerly open the stream +} +``` + +In addition you can pass the `open`, `read`, and `destroy` functions as shorthands in +the constructor instead of overwrite the methods below. + +The default byteLength function returns the byte length of buffers and `1024` +for any other object. This means the buffer will contain around 16 non buffers +or buffers worth 16kb when full if the defaults are used. + +If you set highWaterMark to `0` then all read ahead buffering on the stream +is disabled and it will only call `_read` when a user reads rather than ahead of time. + +#### `rs._read(cb)` + +This function is called when the stream wants you to push new data. +Overwrite this and add your own read logic. +You should call the callback when you are fully done with the read. + +Can also be set using `options.read` in the constructor. + +Note that this function differs from Node.js streams in that it takes +the "read finished" callback. + +#### `drained = rs.push(data)` + +Push new data to the stream. Returns true if the buffer is not full +and you should push more data if you can. + +If you call `rs.push(null)` you signal to the stream that no more +data will be pushed and that you want to end the stream. + +#### `data = rs.read()` + +Read a piece of data from the stream buffer. If the buffer is currently empty +`null` will be returned and you should wait for `readable` to be emitted before +trying again. If the stream has been ended it will also return `null`. + +Note that this method differs from Node.js streams in that it does not accept +an optional amounts of bytes to consume. + +#### `rs.unshift(data)` + +Add a piece of data to the front of the buffer. Use this if you read too much +data using the `rs.read()` function. + +#### `rs._open(cb)` + +This function is called once before the first read is issued. Use this function +to implement your own open logic. + +Can also be set using `options.open` in the constructor. + +#### `rs._destroy(cb)` + +This function is called just before the stream is fully destroyed. You should +use this to implement whatever teardown logic you need. The final part of the +stream life cycle is always to call destroy itself so this function will always +be called whether or not the stream ends gracefully or forcefully. + +Can also be set using `options.destroy` in the constructor. + +Note that the `_destroy` might be called without the open function being called +in case no read was ever performed on the stream. + +#### `rs._predestroy()` + +A simple hook that is called as soon as the first `stream.destroy()` call is invoked. + +Use this in case you need to cancel pending reads (if possible) instead of waiting for them to finish. + +Can also be set using `options.predestroy` in the constructor. + +#### `rs.destroy([error])` + +Forcefully destroy the stream. Will call `_destroy` as soon as all pending reads have finished. +Once the stream is fully destroyed `close` will be emitted. + +If you pass an error this error will be emitted just before `close` is, signifying a reason +as to why this stream was destroyed. + +#### `rs.pause()` + +Pauses the stream. You will only need to call this if you want to pause a resumed stream. + +Returns this stream instance. + +#### `rs.resume()` + +Will start reading data from the stream as fast as possible. + +If you do not call this, you need to use the `read()` method to read data or the `pipe()` method to +pipe the stream somewhere else or the `data` handler. + +If none of these option are used the stream will stay paused. + +Returns this stream instance. + +#### `rs.setEncoding(encoding)` + +Set an encoding to change how data is interpreted. E.g. `utf-8`. + +#### `bool = Readable.isPaused(rs)` + +Returns `true` if the stream is paused, else `false`. + +#### `writableStream = rs.pipe(writableStream, [callback])` + +Efficently pipe the readable stream to a writable stream (can be Node.js core stream or a stream from this package). +If you provide a callback the callback is called when the pipeline has fully finished with an optional error in case +it failed. + +To cancel the pipeline destroy either of the streams. + +#### `rs.on('readable')` + +Emitted when data is pushed to the stream if the buffer was previously empty. + +#### `rs.on('data', data)` + +Emitted when data is being read from the stream. If you attach a data handler you are implicitly resuming the stream. + +#### `rs.on('end')` + +Emitted when the readable stream has ended and no data is left in it's buffer. + +#### `rs.on('close')` + +Emitted when the readable stream has fully closed (i.e. it's destroy function has completed) + +#### `rs.on('error', err)` + +Emitted if any of the stream operations fail with an error. `close` is always emitted right after this. + +#### `rs.on('piping', dest)` + +Emitted when the readable stream is pipeing to a destination. + +#### `rs.on('open')` + +Emitted after `rs._open(cb)` execution. + +#### `rs.destroying` + +Boolean property indicating whether or not this stream has started to be destroyed. + +#### `rs.destroyed` + +Boolean property indicating whether or not this stream has been destroyed. + +#### `rs.readable` + +Returns `true` if the stream is an active streamx readable stream. Returns `undefined` if not. + +#### `bool = Readable.isBackpressured(rs)` + +Static method to check if a readable stream is currently under backpressure. + +#### `stream = Readable.from(arrayOrBufferOrStringOrAsyncIterator)` + +Static method to turn an array or buffer or string or AsyncIterator into a readable stream. + +## Writable Stream + +#### `ws = new stream.Writable([options])` + +Create a new writable stream. + +Options include: + +``` +{ + highWaterMark: 16384, // max buffer size in bytes + map: (data) => data, // optional function to map input data + byteLength: (data) => size, // optional function that calculates the byte size of input data + signal: abortController.signal // optional AbortSignal that triggers `.destroy` when on `abort` +} +``` + +In addition you can pass the `open`, `write`, `final`, and `destroy` functions as shorthands in +the constructor instead of overwrite the methods below. + +The default byteLength function returns the byte length of buffers and `1024` +for any other object. This means the buffer will contain around 16 non buffers +or buffers worth 16kb when full if the defaults are used. + +#### `ws._open(cb)` + +This function is called once before the first write is issued. Use this function +to implement your own open logic. + +Can also be set using `options.open` in the constructor. + +#### `ws._destroy(cb)` + +This function is called just before the stream is fully destroyed. You should +use this to implement whatever teardown logic you need. The final part of the +stream life cycle is always to call destroy itself so this function will always +be called whether or not the stream ends gracefully or forcefully. + +Can also be set using `options.destroy` in the constructor. + +Note that the `_destroy` might be called without the open function being called +in case no write was ever performed on the stream. + +#### `ws._predestroy()` + +A simple hook that is called as soon as the first `stream.destroy()` call is invoked. + +Use this in case you need to cancel pending writes (if possible) instead of waiting for them to finish. + +Can also be set using `options.predestroy` in the constructor. + +#### `ws.destroy([error])` + +Forcefully destroy the stream. Will call `_destroy` as soon as all pending reads have finished. +Once the stream is fully destroyed `close` will be emitted. + +If you pass an error this error will be emitted just before `close` is, signifying a reason +as to why this stream was destroyed. + +#### `drained = ws.write(data)` + +Write a piece of data to the stream. Returns `true` if the stream buffer is not full and you +should keep writing to it if you can. If `false` is returned the stream will emit `drain` +once it's buffer is fully drained. + +#### `ws._write(data, callback)` + +This function is called when the stream want to write some data. Use this to implement your own +write logic. When done call the callback and the stream will call it again if more data exists in the buffer. + +Can also be set using `options.write` in the constructor. + +#### `ws._writev(batch, callback)` + +Similar to `_write` but passes an array of all data in the current write buffer instead of the oldest one. +Useful if the destination you are writing the data to supports batching. + +Can also be set using `options.writev` in the constructor. + +#### `ws.end()` + +Gracefully end the writable stream. Call this when you no longer want to write to the stream. + +Once all writes have been fully drained `finish` will be emitted. + +Returns this stream instance. + +#### `ws.cork()` + +Buffer written data in memory. Useful for accumulating small chunks of data into a batch to be consumed by `writev`. + +#### `ws.uncork()` + +Disable `ws.cork()`. + +#### `ws._final(callback)` + +This function is called just before `finish` is emitted, i.e. when all writes have flushed but `ws.end()` +have been called. Use this to implement any logic that should happen after all writes but before finish. + +Can also be set using `options.final` in the constructor. + +#### `ws.on('finish')` + +Emitted when the stream has been ended and all writes have been drained. + +#### `ws.on('close')` + +Emitted when the readable stream has fully closed (i.e. it's destroy function has completed) + +#### `ws.on('error', err)` + +Emitted if any of the stream operations fail with an error. `close` is always emitted right after this. + +#### `ws.on('pipe', src)` + +Emitted when a readable stream is being piped to the writable one. + +#### `ws.on('open')` + +Emitted after `ws._open(cb)` execution. + +#### `ws.on('drain')` + +Emitted after all data was drained if `ws.write(data)` returned `false`. + +#### `ws.destroying` + +Boolean property indicating whether or not this stream has started to be destroyed. + +#### `ws.destroyed` + +Boolean property indicating whether or not this stream has been destroyed. + +#### `ws.writable` + +Returns `true` if the stream is an active streamx writable stream. Returns `undefined` if not. + +#### `bool = Writable.isBackpressured(ws)` + +Static method to check if a writable stream is currently under backpressure. + +#### `bool = await Writable.drained(ws)` + +Static helper to wait for a stream to drain the currently queued writes. +Returns true if they were drained and false otherwise if the stream was destroyed. + +## Duplex Stream + +#### `s = new stream.Duplex([options])` + +A duplex stream is a stream that is both readable and writable. + +Since JS does not support multiple inheritance it inherits directly from Readable +but implements the Writable API as well. + +If you want to provide only a map function for the readable side use `mapReadable` instead. +If you want to provide only a byteLength function for the readable side use `byteLengthReadable` instead. + +Same goes for the writable side but using `mapWritable` and `byteLengthWritable` instead. + +## Transform Stream + +A Transform stream is a duplex stream with an `._transform` template method that allows to +asynchronously map the input to a different output. + +The transform stream overrides the `_write` and `_read` operations of `Readable` and `Writable` but +still allows the setting of these options in the constructor. Usually it is unnecessary to pass +in `read` or `write`/`writev` or to override the corresponding `._read`, `._write` or `._writev` operation. + +#### `ts = new stream.Transform([options])` + +A transform stream is a duplex stream that maps the data written to it and emits that as readable data. + +Has the same options as a duplex stream except you can provide a `transform` function also. + +#### `ts._transform(data, callback)` + +Transform the incoming data. Call `callback(null, mappedData)` or use `ts.push(mappedData)` to +return data to the readable side of the stream. + +Per default the transform function just remits the incoming data making it act as a pass-through stream. + +## Pipeline + +`pipeline` allows to stream form a readable through a set of duplex streams to a writable entry. + +```js +const { pipeline, Readable, Transform, Writable } = require('streamx') +const lastStream = pipeline( + Readable.from([1, 2, 3]), + new Transform({ + transform (from, cb) { + this.push(from.toString()) + cb() + } + }), + new Writable({ + write (data, cb) { + console.log(data) + cb() + } + }) + error => { + // Callback once write has finished + } +) +``` + +#### `lastStream = stream.pipeline(...streams, [done])` + +Pipe all streams together and return the last stream piped to. +When the last stream finishes the pipeline ended succesfully. + +If any of the streams error, whether they are Node.js core streams +or streamx streams, all streams in the pipeline are shutdown. + +Optionally you can pass a done callback to know when the pipeline is done. + +#### `promise = stream.pipelinePromise(...streams)` + +Same as normal pipeline except instead of returning the last stream it returns +a promise representing the done callback. Note you should error handle this +promise if you use this version. + +## Helpers + +#### `bool = isStream(stream)` + +#### `bool = isStreamx(stream)` + +#### `bool = isDisturbed(stream)` + +Indicates if the stream has been opened or started to be destroyed. + +#### `bool = isEnding(stream)` + +Indicates if a readable stream has started it's ending process. + +#### `bool = isEnded(stream)` + +Indicates if a readable stream ended, so all it's readings. + +#### `bool = isFinishing(stream)` + +Indicates if a writable stream has started it's ending process. + +#### `bool = isFinished(stream)` + +Indicates if a writable stream ended, so all it's writings. + +#### `err = getStreamError(stream, [options])` + +Returns `null` if the stream has no errors. + +## Utilities + +Streamx aims to be minimal and stable. It therefore only contains a minimal set of utilities. +To help discover of other modules that help you build streamx apps, we link some useful utilities here + +- [stream-composer](https://github.com/mafintosh/stream-composer) - Compose streams like Node's `stream.compose` and the `duplexify` and `pumpify` modules. +- [teex](https://github.com/mafintosh/teex) - Clone a readable stream into multiple new readable instances. +- [merge-readable](https://github.com/holepunchto/merge-readable) - Merge multiple readers into a new readable with optional mapping of data + +## Contributing + +If you want to help contribute to streamx a good way to start is to help writing more test +cases, compatibility tests, documentation, or performance benchmarks. + +If in doubt open an issue :) + +## License + +MIT diff --git a/node_modules/streamx/index.d.ts b/node_modules/streamx/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7856f0ca2273a2a71ffd6fba21048468505b7055 --- /dev/null +++ b/node_modules/streamx/index.d.ts @@ -0,0 +1,198 @@ +import { BufferEncoding, EventMap, EventEmitter } from './runtime' + +interface StreamCallback { + (err: Error | null): void +} + +type Pipeline = [src: Readable, ...transforms: Duplex[], dest: S] + +declare function pipeline(streams: Pipeline, cb?: StreamCallback): S +declare function pipeline(...args: Pipeline): S +declare function pipeline(...args: [...Pipeline, cb: StreamCallback]): S + +declare function pipelinePromise(...args: Pipeline): Promise + +declare function isStream(stream: Stream): stream is Stream +declare function isStreamx(stream: Stream): boolean +declare function isEnding(stream: Stream): boolean +declare function isEnded(stream: Stream): boolean +declare function isFinishing(stream: Stream): boolean +declare function isFinished(stream: Stream): boolean +declare function isDisturbed(stream: Stream): boolean + +interface GetStreamErrorOptions { + all?: boolean +} + +declare function getStreamError(stream: Stream, opts?: GetStreamErrorOptions): Error | null + +interface StreamEvents extends EventMap { + close: [] + error: [err: Error] +} + +interface StreamOptions { + byteLength?(data: unknown): number + destroy?(this: S, cb: StreamCallback): void + eagerOpen?: boolean + highWaterMark?: number + map?(data: unknown): unknown + open?(this: S, cb: StreamCallback): void + predestroy?(this: S): void + signal?: AbortSignal +} + +interface Stream extends EventEmitter { + _open(cb: StreamCallback): void + _predestroy(): void + _destroy(cb: StreamCallback): void + + readonly readable: boolean + readonly writable: boolean + readonly destroyed: boolean + readonly destroying: boolean + + destroy(err?: Error | null): void +} + +declare class Stream { + constructor(opts?: StreamOptions) +} + +interface WritableEvents extends StreamEvents { + drain: [] + finish: [] + pipe: [src: Readable] +} + +interface WritableOptions extends StreamOptions { + byteLengthWritable?(data: unknown): number + final?(this: S, cb: StreamCallback): void + mapWritable?(data: unknown): unknown + write?(this: S, data: unknown, cb: StreamCallback): void + writev?(this: S, batch: unknown[], cb: StreamCallback): void +} + +interface Writable extends Stream { + _write(data: unknown, cb: StreamCallback): void + _writev(batch: unknown[], cb: StreamCallback): void + _final(cb: StreamCallback): void + + write(data: unknown): unknown + + end(data: unknown): this + + cork(): void + uncork(): void +} + +declare class Writable extends Stream { + constructor(opts?: WritableOptions) + + static isBackpressured(ws: Writable): boolean + + static drained(ws: Writable): Promise +} + +interface ReadableEvents extends StreamEvents { + data: [data: unknown] + end: [] + piping: [dest: Writable] + readable: [] +} + +interface ReadableOptions extends StreamOptions { + byteLengthReadable?(data: unknown): number + encoding?: BufferEncoding + mapReadable?(data: unknown): unknown + read?(this: S, cb: StreamCallback): void +} + +interface Readable + extends Stream, AsyncIterable { + _read(cb: StreamCallback): void + + push(data: unknown | null): boolean + unshift(data: unknown | null): void + read(): unknown | null + + resume(): this + pause(): this + + pipe(dest: S, cb?: StreamCallback): S + + setEncoding(encoding: BufferEncoding): this +} + +declare class Readable extends Stream { + constructor(opts?: ReadableOptions) + + static deferred(fn: () => Promise, opts?: TransformOptions): Transform + + static from(data: unknown | unknown[] | AsyncIterable, opts?: ReadableOptions): Readable + + static isBackpressured(rs: Readable): boolean + + static isPaused(rs: Readable): boolean +} + +interface DuplexEvents extends ReadableEvents, WritableEvents {} + +interface DuplexOptions extends ReadableOptions, WritableOptions {} + +interface Duplex extends Readable, Writable {} + +declare class Duplex extends Stream { + constructor(opts?: DuplexOptions) +} + +interface TransformCallback { + (err: Error | null, mappedData: unknown): void +} + +interface TransformEvents extends DuplexEvents {} + +interface TransformOptions extends DuplexOptions { + flush?(this: S, cb: StreamCallback): void + transform?(this: S, data: unknown, cb: TransformCallback): void +} + +interface Transform extends Duplex { + _flush(cb: StreamCallback): void + _transform(Data: unknown, cb: TransformCallback): void +} + +declare class Transform extends Duplex { + constructor(opts?: TransformOptions) +} + +export { + type Pipeline, + pipeline, + pipelinePromise, + isStream, + isStreamx, + isEnding, + isEnded, + isFinishing, + isFinished, + isDisturbed, + type GetStreamErrorOptions, + getStreamError, + type StreamEvents, + type StreamOptions, + Stream, + type WritableEvents, + type WritableOptions, + Writable, + type ReadableEvents, + type ReadableOptions, + Readable, + type DuplexEvents, + type DuplexOptions, + Duplex, + type TransformEvents, + type TransformOptions, + Transform, + Transform as PassThrough +} diff --git a/node_modules/streamx/index.js b/node_modules/streamx/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6b1b03e686064c62bf0e659b889efe2524bff099 --- /dev/null +++ b/node_modules/streamx/index.js @@ -0,0 +1,1314 @@ +const { EventEmitter } = require('events-universal') +const FIFO = require('fast-fifo') +const TextDecoder = require('text-decoder') + +const StreamError = require('./lib/errors.js') + +// if we do a future major, expect queue microtask to be there always, for now a bit defensive +const qmt = + typeof queueMicrotask === 'undefined' ? (fn) => global.process.nextTick(fn) : queueMicrotask + +// 29 bits used total (4 from shared, 14 from read, and 11 from write) +const MAX = (1 << 29) - 1 + +// Shared state +const OPENING = 0b0001 +const PREDESTROYING = 0b0010 +const DESTROYING = 0b0100 +const DESTROYED = 0b1000 + +const NOT_OPENING = MAX ^ OPENING +const NOT_PREDESTROYING = MAX ^ PREDESTROYING + +// Read state (4 bit offset from shared state) +const READ_ACTIVE = 0b00000000000001 << 4 +const READ_UPDATING = 0b00000000000010 << 4 +const READ_PRIMARY = 0b00000000000100 << 4 +const READ_QUEUED = 0b00000000001000 << 4 +const READ_RESUMED = 0b00000000010000 << 4 +const READ_PIPE_DRAINED = 0b00000000100000 << 4 +const READ_ENDING = 0b00000001000000 << 4 +const READ_EMIT_DATA = 0b00000010000000 << 4 +const READ_EMIT_READABLE = 0b00000100000000 << 4 +const READ_EMITTED_READABLE = 0b00001000000000 << 4 +const READ_DONE = 0b00010000000000 << 4 +const READ_NEXT_TICK = 0b00100000000000 << 4 +const READ_NEEDS_PUSH = 0b01000000000000 << 4 +const READ_READ_AHEAD = 0b10000000000000 << 4 + +// Combined read state +const READ_FLOWING = READ_RESUMED | READ_PIPE_DRAINED +const READ_ACTIVE_AND_NEEDS_PUSH = READ_ACTIVE | READ_NEEDS_PUSH +const READ_PRIMARY_AND_ACTIVE = READ_PRIMARY | READ_ACTIVE +const READ_EMIT_READABLE_AND_QUEUED = READ_EMIT_READABLE | READ_QUEUED +const READ_RESUMED_READ_AHEAD = READ_RESUMED | READ_READ_AHEAD + +const READ_NOT_ACTIVE = MAX ^ READ_ACTIVE +const READ_NON_PRIMARY = MAX ^ READ_PRIMARY +const READ_NON_PRIMARY_AND_PUSHED = MAX ^ (READ_PRIMARY | READ_NEEDS_PUSH) +const READ_PUSHED = MAX ^ READ_NEEDS_PUSH +const READ_PAUSED = MAX ^ READ_RESUMED +const READ_NOT_QUEUED = MAX ^ (READ_QUEUED | READ_EMITTED_READABLE) +const READ_NOT_ENDING = MAX ^ READ_ENDING +const READ_PIPE_NOT_DRAINED = MAX ^ READ_FLOWING +const READ_NOT_NEXT_TICK = MAX ^ READ_NEXT_TICK +const READ_NOT_UPDATING = MAX ^ READ_UPDATING +const READ_NO_READ_AHEAD = MAX ^ READ_READ_AHEAD +const READ_PAUSED_NO_READ_AHEAD = MAX ^ READ_RESUMED_READ_AHEAD + +// Write state (18 bit offset, 4 bit offset from shared state and 14 from read state) +const WRITE_ACTIVE = 0b00000000001 << 18 +const WRITE_UPDATING = 0b00000000010 << 18 +const WRITE_PRIMARY = 0b00000000100 << 18 +const WRITE_QUEUED = 0b00000001000 << 18 +const WRITE_UNDRAINED = 0b00000010000 << 18 +const WRITE_DONE = 0b00000100000 << 18 +const WRITE_EMIT_DRAIN = 0b00001000000 << 18 +const WRITE_NEXT_TICK = 0b00010000000 << 18 +const WRITE_WRITING = 0b00100000000 << 18 +const WRITE_FINISHING = 0b01000000000 << 18 +const WRITE_CORKED = 0b10000000000 << 18 + +const WRITE_NOT_ACTIVE = MAX ^ (WRITE_ACTIVE | WRITE_WRITING) +const WRITE_NON_PRIMARY = MAX ^ WRITE_PRIMARY +const WRITE_NOT_FINISHING = MAX ^ (WRITE_ACTIVE | WRITE_FINISHING) +const WRITE_DRAINED = MAX ^ WRITE_UNDRAINED +const WRITE_NOT_QUEUED = MAX ^ WRITE_QUEUED +const WRITE_NOT_NEXT_TICK = MAX ^ WRITE_NEXT_TICK +const WRITE_NOT_UPDATING = MAX ^ WRITE_UPDATING +const WRITE_NOT_CORKED = MAX ^ WRITE_CORKED + +// Combined shared state +const ACTIVE = READ_ACTIVE | WRITE_ACTIVE +const NOT_ACTIVE = MAX ^ ACTIVE +const DONE = READ_DONE | WRITE_DONE +const DESTROY_STATUS = DESTROYING | DESTROYED | PREDESTROYING +const OPEN_STATUS = DESTROY_STATUS | OPENING +const AUTO_DESTROY = DESTROY_STATUS | DONE +const NON_PRIMARY = WRITE_NON_PRIMARY & READ_NON_PRIMARY +const ACTIVE_OR_TICKING = WRITE_NEXT_TICK | READ_NEXT_TICK +const TICKING = ACTIVE_OR_TICKING & NOT_ACTIVE +const IS_OPENING = OPEN_STATUS | TICKING + +// Combined shared state and read state +const READ_PRIMARY_STATUS = OPEN_STATUS | READ_ENDING | READ_DONE +const READ_STATUS = OPEN_STATUS | READ_DONE | READ_QUEUED +const READ_ENDING_STATUS = OPEN_STATUS | READ_ENDING | READ_QUEUED +const READ_READABLE_STATUS = OPEN_STATUS | READ_EMIT_READABLE | READ_QUEUED | READ_EMITTED_READABLE +const SHOULD_NOT_READ = + OPEN_STATUS | READ_ACTIVE | READ_ENDING | READ_DONE | READ_NEEDS_PUSH | READ_READ_AHEAD +const READ_BACKPRESSURE_STATUS = DESTROY_STATUS | READ_ENDING | READ_DONE +const READ_UPDATE_SYNC_STATUS = READ_UPDATING | OPEN_STATUS | READ_NEXT_TICK | READ_PRIMARY +const READ_NEXT_TICK_OR_OPENING = READ_NEXT_TICK | OPENING + +// Combined write state +const WRITE_PRIMARY_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_DONE +const WRITE_QUEUED_AND_UNDRAINED = WRITE_QUEUED | WRITE_UNDRAINED +const WRITE_QUEUED_AND_ACTIVE = WRITE_QUEUED | WRITE_ACTIVE +const WRITE_DRAIN_STATUS = WRITE_QUEUED | WRITE_UNDRAINED | OPEN_STATUS | WRITE_ACTIVE +const WRITE_STATUS = OPEN_STATUS | WRITE_ACTIVE | WRITE_QUEUED | WRITE_CORKED +const WRITE_PRIMARY_AND_ACTIVE = WRITE_PRIMARY | WRITE_ACTIVE +const WRITE_ACTIVE_AND_WRITING = WRITE_ACTIVE | WRITE_WRITING +const WRITE_FINISHING_STATUS = OPEN_STATUS | WRITE_FINISHING | WRITE_QUEUED_AND_ACTIVE | WRITE_DONE +const WRITE_BACKPRESSURE_STATUS = WRITE_UNDRAINED | DESTROY_STATUS | WRITE_FINISHING | WRITE_DONE +const WRITE_UPDATE_SYNC_STATUS = WRITE_UPDATING | OPEN_STATUS | WRITE_NEXT_TICK | WRITE_PRIMARY +const WRITE_DROP_DATA = WRITE_FINISHING | WRITE_DONE | DESTROY_STATUS + +const asyncIterator = Symbol.asyncIterator || Symbol('asyncIterator') + +class WritableState { + constructor( + stream, + { highWaterMark = 16384, map = null, mapWritable, byteLength, byteLengthWritable } = {} + ) { + this.stream = stream + this.queue = new FIFO() + this.highWaterMark = highWaterMark + this.buffered = 0 + this.error = null + this.pipeline = null + this.drains = null // if we add more seldomly used helpers we might them into a subobject so its a single ptr + this.byteLength = byteLengthWritable || byteLength || defaultByteLength + this.map = mapWritable || map + this.afterWrite = afterWrite.bind(this) + this.afterUpdateNextTick = updateWriteNT.bind(this) + } + + get ending() { + return (this.stream._duplexState & WRITE_FINISHING) !== 0 + } + + get ended() { + return (this.stream._duplexState & WRITE_DONE) !== 0 + } + + push(data) { + if ((this.stream._duplexState & WRITE_DROP_DATA) !== 0) return false + if (this.map !== null) data = this.map(data) + + this.buffered += this.byteLength(data) + this.queue.push(data) + + if (this.buffered < this.highWaterMark) { + this.stream._duplexState |= WRITE_QUEUED + return true + } + + this.stream._duplexState |= WRITE_QUEUED_AND_UNDRAINED + return false + } + + shift() { + const data = this.queue.shift() + + this.buffered -= this.byteLength(data) + if (this.buffered === 0) this.stream._duplexState &= WRITE_NOT_QUEUED + + return data + } + + end(data) { + if (typeof data === 'function') { + this.stream.once('finish', data) + } else if (data !== undefined && data !== null) { + this.push(data) + } + + this.stream._duplexState = (this.stream._duplexState | WRITE_FINISHING) & WRITE_NON_PRIMARY + } + + autoBatch(data, cb) { + const buffer = [] + const stream = this.stream + + buffer.push(data) + while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED_AND_ACTIVE) { + buffer.push(stream._writableState.shift()) + } + + if ((stream._duplexState & OPEN_STATUS) !== 0) return cb(null) + stream._writev(buffer, cb) + } + + update() { + const stream = this.stream + + stream._duplexState |= WRITE_UPDATING + + do { + while ((stream._duplexState & WRITE_STATUS) === WRITE_QUEUED) { + const data = this.shift() + stream._duplexState |= WRITE_ACTIVE_AND_WRITING + stream._write(data, this.afterWrite) + } + + if ((stream._duplexState & WRITE_PRIMARY_AND_ACTIVE) === 0) this.updateNonPrimary() + } while (this.continueUpdate() === true) + + stream._duplexState &= WRITE_NOT_UPDATING + } + + updateNonPrimary() { + const stream = this.stream + + if ((stream._duplexState & WRITE_FINISHING_STATUS) === WRITE_FINISHING) { + stream._duplexState = stream._duplexState | WRITE_ACTIVE + stream._final(afterFinal.bind(this)) + return + } + + if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) { + if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) { + stream._duplexState |= ACTIVE + stream._destroy(afterDestroy.bind(this)) + } + return + } + + if ((stream._duplexState & IS_OPENING) === OPENING) { + stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING + stream._open(afterOpen.bind(this)) + } + } + + continueUpdate() { + if ((this.stream._duplexState & WRITE_NEXT_TICK) === 0) return false + this.stream._duplexState &= WRITE_NOT_NEXT_TICK + return true + } + + updateCallback() { + if ((this.stream._duplexState & WRITE_UPDATE_SYNC_STATUS) === WRITE_PRIMARY) { + this.update() + } else { + this.updateNextTick() + } + } + + updateNextTick() { + if ((this.stream._duplexState & WRITE_NEXT_TICK) !== 0) return + this.stream._duplexState |= WRITE_NEXT_TICK + if ((this.stream._duplexState & WRITE_UPDATING) === 0) qmt(this.afterUpdateNextTick) + } +} + +class ReadableState { + constructor( + stream, + { highWaterMark = 16384, map = null, mapReadable, byteLength, byteLengthReadable } = {} + ) { + this.stream = stream + this.queue = new FIFO() + this.highWaterMark = highWaterMark === 0 ? 1 : highWaterMark + this.buffered = 0 + this.readAhead = highWaterMark > 0 + this.error = null + this.pipeline = null + this.byteLength = byteLengthReadable || byteLength || defaultByteLength + this.map = mapReadable || map + this.pipeTo = null + this.afterRead = afterRead.bind(this) + this.afterUpdateNextTick = updateReadNT.bind(this) + } + + get ending() { + return (this.stream._duplexState & READ_ENDING) !== 0 + } + + get ended() { + return (this.stream._duplexState & READ_DONE) !== 0 + } + + pipe(pipeTo, cb) { + if (this.pipeTo !== null) throw StreamError.BAD_ARGUMENT('Can only pipe to one destination') + if (typeof cb !== 'function') cb = null + + this.stream._duplexState |= READ_PIPE_DRAINED + this.pipeTo = pipeTo + this.pipeline = new Pipeline(this.stream, pipeTo, cb) + + if (cb) this.stream.on('error', noop) // We already error handle this so supress crashes + + if (isStreamx(pipeTo)) { + pipeTo._writableState.pipeline = this.pipeline + if (cb) pipeTo.on('error', noop) // We already error handle this so supress crashes + pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) // TODO: just call finished from pipeTo itself + } else { + const onerror = this.pipeline.done.bind(this.pipeline, pipeTo) + const onclose = this.pipeline.done.bind(this.pipeline, pipeTo, null) // onclose has a weird bool arg + pipeTo.on('error', onerror) + pipeTo.on('close', onclose) + pipeTo.on('finish', this.pipeline.finished.bind(this.pipeline)) + } + + pipeTo.on('drain', afterDrain.bind(this)) + this.stream.emit('piping', pipeTo) + pipeTo.emit('pipe', this.stream) + } + + push(data) { + const stream = this.stream + + if (data === null) { + this.highWaterMark = 0 + stream._duplexState = (stream._duplexState | READ_ENDING) & READ_NON_PRIMARY_AND_PUSHED + return false + } + + if (this.map !== null) { + data = this.map(data) + if (data === null) { + stream._duplexState &= READ_PUSHED + return this.buffered < this.highWaterMark + } + } + + this.buffered += this.byteLength(data) + this.queue.push(data) + + stream._duplexState = (stream._duplexState | READ_QUEUED) & READ_PUSHED + + return this.buffered < this.highWaterMark + } + + shift() { + const data = this.queue.shift() + + this.buffered -= this.byteLength(data) + if (this.buffered === 0) { + this.stream._duplexState &= READ_NOT_QUEUED + } + + return data + } + + unshift(data) { + const pending = [this.map !== null ? this.map(data) : data] + while (this.buffered > 0) pending.push(this.shift()) + + for (let i = 0; i < pending.length - 1; i++) { + const data = pending[i] + this.buffered += this.byteLength(data) + this.queue.push(data) + } + + this.push(pending[pending.length - 1]) + } + + read() { + const stream = this.stream + + if ((stream._duplexState & READ_STATUS) === READ_QUEUED) { + const data = this.shift() + + if (this.pipeTo !== null && this.pipeTo.write(data) === false) { + stream._duplexState &= READ_PIPE_NOT_DRAINED + } + + if ((stream._duplexState & READ_EMIT_DATA) !== 0) { + stream.emit('data', data) + } + + return data + } + + if (this.readAhead === false) { + stream._duplexState |= READ_READ_AHEAD + this.updateNextTick() + } + + return null + } + + drain() { + const stream = this.stream + + while ( + (stream._duplexState & READ_STATUS) === READ_QUEUED && + (stream._duplexState & READ_FLOWING) !== 0 + ) { + const data = this.shift() + + if (this.pipeTo !== null && this.pipeTo.write(data) === false) { + stream._duplexState &= READ_PIPE_NOT_DRAINED + } + + if ((stream._duplexState & READ_EMIT_DATA) !== 0) { + stream.emit('data', data) + } + } + } + + update() { + const stream = this.stream + + stream._duplexState |= READ_UPDATING + + do { + this.drain() + + while ( + this.buffered < this.highWaterMark && + (stream._duplexState & SHOULD_NOT_READ) === READ_READ_AHEAD + ) { + stream._duplexState |= READ_ACTIVE_AND_NEEDS_PUSH + stream._read(this.afterRead) + this.drain() + } + + if ((stream._duplexState & READ_READABLE_STATUS) === READ_EMIT_READABLE_AND_QUEUED) { + stream._duplexState |= READ_EMITTED_READABLE + stream.emit('readable') + } + + if ((stream._duplexState & READ_PRIMARY_AND_ACTIVE) === 0) { + this.updateNonPrimary() + } + } while (this.continueUpdate() === true) + + stream._duplexState &= READ_NOT_UPDATING + } + + updateNonPrimary() { + const stream = this.stream + + if ((stream._duplexState & READ_ENDING_STATUS) === READ_ENDING) { + stream._duplexState = (stream._duplexState | READ_DONE) & READ_NOT_ENDING + stream.emit('end') + + if ((stream._duplexState & AUTO_DESTROY) === DONE) { + stream._duplexState |= DESTROYING + } + + if (this.pipeTo !== null) { + this.pipeTo.end() + } + } + + if ((stream._duplexState & DESTROY_STATUS) === DESTROYING) { + if ((stream._duplexState & ACTIVE_OR_TICKING) === 0) { + stream._duplexState |= ACTIVE + stream._destroy(afterDestroy.bind(this)) + } + return + } + + if ((stream._duplexState & IS_OPENING) === OPENING) { + stream._duplexState = (stream._duplexState | ACTIVE) & NOT_OPENING + stream._open(afterOpen.bind(this)) + } + } + + continueUpdate() { + if ((this.stream._duplexState & READ_NEXT_TICK) === 0) return false + this.stream._duplexState &= READ_NOT_NEXT_TICK + return true + } + + updateCallback() { + if ((this.stream._duplexState & READ_UPDATE_SYNC_STATUS) === READ_PRIMARY) { + this.update() + } else { + this.updateNextTick() + } + } + + updateNextTickIfOpen() { + if ((this.stream._duplexState & READ_NEXT_TICK_OR_OPENING) !== 0) return + this.stream._duplexState |= READ_NEXT_TICK + if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick) + } + + updateNextTick() { + if ((this.stream._duplexState & READ_NEXT_TICK) !== 0) return + this.stream._duplexState |= READ_NEXT_TICK + if ((this.stream._duplexState & READ_UPDATING) === 0) qmt(this.afterUpdateNextTick) + } +} + +class TransformState { + constructor(stream) { + this.data = null + this.afterTransform = afterTransform.bind(stream) + this.afterFinal = null + } +} + +class Pipeline { + constructor(src, dst, cb) { + this.from = src + this.to = dst + this.afterPipe = cb + this.error = null + this.pipeToFinished = false + } + + finished() { + this.pipeToFinished = true + } + + done(stream, err) { + if (err) this.error = err + + if (stream === this.to) { + this.to = null + + if (this.from !== null) { + if ((this.from._duplexState & READ_DONE) === 0 || !this.pipeToFinished) { + this.from.destroy(this.error || StreamError.PREMATURE_CLOSE('Writable stream closed')) + } + return + } + } + + if (stream === this.from) { + this.from = null + + if (this.to !== null) { + if ((stream._duplexState & READ_DONE) === 0) { + this.to.destroy(this.error || StreamError.PREMATURE_CLOSE('Readable stream closed')) + } + return + } + } + + if (this.afterPipe !== null) this.afterPipe(this.error) + this.to = this.from = this.afterPipe = null + } +} + +function afterDrain() { + this.stream._duplexState |= READ_PIPE_DRAINED + this.updateCallback() +} + +function afterFinal(err) { + const stream = this.stream + if (err) stream.destroy(err) + + if ((stream._duplexState & DESTROY_STATUS) === 0) { + stream._duplexState |= WRITE_DONE + stream.emit('finish') + } + + if ((stream._duplexState & AUTO_DESTROY) === DONE) { + stream._duplexState |= DESTROYING + } + + stream._duplexState &= WRITE_NOT_FINISHING + + // no need to wait the extra tick here, so we short circuit that + if ((stream._duplexState & WRITE_UPDATING) === 0) { + this.update() + } else { + this.updateNextTick() + } +} + +function afterDestroy(err) { + const stream = this.stream + + if (!err && !StreamError.isStreamDestroyed(this.error)) err = this.error + if (err) stream.emit('error', err) + + stream._duplexState |= DESTROYED + stream.emit('close') + + const rs = stream._readableState + const ws = stream._writableState + + if (rs !== null && rs.pipeline !== null) { + rs.pipeline.done(stream, err) + } + + if (ws !== null) { + while (ws.drains !== null && ws.drains.length > 0) { + ws.drains.shift().resolve(false) + } + + if (ws.pipeline !== null) { + ws.pipeline.done(stream, err) + } + } +} + +function afterWrite(err) { + const stream = this.stream + + if (err) stream.destroy(err) + stream._duplexState &= WRITE_NOT_ACTIVE + + if (this.drains !== null) tickDrains(this.drains) + + if ((stream._duplexState & WRITE_DRAIN_STATUS) === WRITE_UNDRAINED) { + stream._duplexState &= WRITE_DRAINED + + if ((stream._duplexState & WRITE_EMIT_DRAIN) === WRITE_EMIT_DRAIN) { + stream.emit('drain') + } + } + + this.updateCallback() +} + +function afterRead(err) { + if (err) this.stream.destroy(err) + this.stream._duplexState &= READ_NOT_ACTIVE + + if (this.readAhead === false && (this.stream._duplexState & READ_RESUMED) === 0) { + this.stream._duplexState &= READ_NO_READ_AHEAD + } + + this.updateCallback() +} + +function updateReadNT() { + if ((this.stream._duplexState & READ_UPDATING) === 0) { + this.stream._duplexState &= READ_NOT_NEXT_TICK + this.update() + } +} + +function updateWriteNT() { + if ((this.stream._duplexState & WRITE_UPDATING) === 0) { + this.stream._duplexState &= WRITE_NOT_NEXT_TICK + this.update() + } +} + +function tickDrains(drains) { + for (let i = 0; i < drains.length; i++) { + // drains.writes are monotonic, so if one is 0 its always the first one + if (--drains[i].writes === 0) { + drains.shift().resolve(true) + i-- + } + } +} + +function afterOpen(err) { + const stream = this.stream + + if (err) stream.destroy(err) + + if ((stream._duplexState & DESTROYING) === 0) { + if ((stream._duplexState & READ_PRIMARY_STATUS) === 0) { + stream._duplexState |= READ_PRIMARY + } + + if ((stream._duplexState & WRITE_PRIMARY_STATUS) === 0) { + stream._duplexState |= WRITE_PRIMARY + } + + stream.emit('open') + } + + stream._duplexState &= NOT_ACTIVE + + if (stream._writableState !== null) { + stream._writableState.updateCallback() + } + + if (stream._readableState !== null) { + stream._readableState.updateCallback() + } +} + +function afterTransform(err, data) { + if (data !== undefined && data !== null) this.push(data) + this._writableState.afterWrite(err) +} + +function newListener(name) { + if (this._readableState !== null) { + if (name === 'data') { + this._duplexState |= READ_EMIT_DATA | READ_RESUMED_READ_AHEAD + this._readableState.updateNextTick() + } + if (name === 'readable') { + this._duplexState |= READ_EMIT_READABLE + this._readableState.updateNextTick() + } + } + + if (this._writableState !== null) { + if (name === 'drain') { + this._duplexState |= WRITE_EMIT_DRAIN + this._writableState.updateNextTick() + } + } +} + +class Stream extends EventEmitter { + constructor(opts) { + super() + + this._duplexState = 0 + this._readableState = null + this._writableState = null + + if (opts) { + if (opts.open) this._open = opts.open + if (opts.destroy) this._destroy = opts.destroy + if (opts.predestroy) this._predestroy = opts.predestroy + if (opts.signal) opts.signal.addEventListener('abort', abort.bind(this)) + } + + this.on('newListener', newListener) + } + + _open(cb) { + cb(null) + } + + _destroy(cb) { + cb(null) + } + + _predestroy() { + // does nothing + } + + get readable() { + return this._readableState !== null ? true : undefined + } + + get writable() { + return this._writableState !== null ? true : undefined + } + + get destroyed() { + return (this._duplexState & DESTROYED) !== 0 + } + + get destroying() { + return (this._duplexState & DESTROY_STATUS) !== 0 + } + + destroy(err) { + if ((this._duplexState & DESTROY_STATUS) === 0) { + if (!err) err = StreamError.STREAM_DESTROYED() + this._duplexState = (this._duplexState | DESTROYING) & NON_PRIMARY + + if (this._readableState !== null) { + this._readableState.highWaterMark = 0 + this._readableState.error = err + } + + if (this._writableState !== null) { + this._writableState.highWaterMark = 0 + this._writableState.error = err + } + + this._duplexState |= PREDESTROYING + this._predestroy() + this._duplexState &= NOT_PREDESTROYING + + if (this._readableState !== null) { + this._readableState.updateNextTick() + } + + if (this._writableState !== null) { + this._writableState.updateNextTick() + } + } + } +} + +class Readable extends Stream { + constructor(opts) { + super(opts) + + this._duplexState |= OPENING | WRITE_DONE | READ_READ_AHEAD + this._readableState = new ReadableState(this, opts) + + if (opts) { + if (this._readableState.readAhead === false) this._duplexState &= READ_NO_READ_AHEAD + if (opts.read) this._read = opts.read + if (opts.eagerOpen) this._readableState.updateNextTick() + if (opts.encoding) this.setEncoding(opts.encoding) + } + } + + static deferred(fn, opts) { + const out = new PassThrough(opts) + + fn() + .then((src) => { + if (src === null) return out.end() + if (out.destroying) return + pipeline(src, out, noop) + }) + .catch((err) => out.destroy(err)) + + return out + } + + setEncoding(encoding) { + const dec = new TextDecoder(encoding) + const map = this._readableState.map || echo + this._readableState.map = mapOrSkip + return this + + function mapOrSkip(data) { + const next = dec.push(data) + return next === '' && (data.byteLength !== 0 || dec.remaining > 0) ? null : map(next) + } + } + + _read(cb) { + cb(null) + } + + pipe(dest, cb) { + this._readableState.updateNextTick() + this._readableState.pipe(dest, cb) + return dest + } + + read() { + this._readableState.updateNextTick() + return this._readableState.read() + } + + push(data) { + this._readableState.updateNextTickIfOpen() + return this._readableState.push(data) + } + + unshift(data) { + this._readableState.updateNextTickIfOpen() + return this._readableState.unshift(data) + } + + resume() { + this._duplexState |= READ_RESUMED_READ_AHEAD + this._readableState.updateNextTick() + return this + } + + pause() { + this._duplexState &= + this._readableState.readAhead === false ? READ_PAUSED_NO_READ_AHEAD : READ_PAUSED + return this + } + + static _fromAsyncIterator(ite, opts) { + let destroy + + const rs = new Readable({ + ...opts, + read(cb) { + ite.next().then(push).then(cb.bind(null, null)).catch(cb) + }, + predestroy() { + destroy = ite.return() + }, + destroy(cb) { + if (!destroy) return cb(null) + destroy.then(cb.bind(null, null)).catch(cb) + } + }) + + return rs + + function push(data) { + if (data.done) rs.push(null) + else rs.push(data.value) + } + } + + static from(data, opts) { + if (isReadStreamx(data)) return data + if (data[asyncIterator]) return this._fromAsyncIterator(data[asyncIterator](), opts) + if (!Array.isArray(data)) data = data === undefined ? [] : [data] + + let i = 0 + return new Readable({ + ...opts, + read(cb) { + this.push(i === data.length ? null : data[i++]) + cb(null) + } + }) + } + + static isBackpressured(rs) { + return ( + (rs._duplexState & READ_BACKPRESSURE_STATUS) !== 0 || + rs._readableState.buffered >= rs._readableState.highWaterMark + ) + } + + static isPaused(rs) { + return (rs._duplexState & READ_RESUMED) === 0 + } + + [asyncIterator]() { + const stream = this + + let error = null + let promiseResolve = null + let promiseReject = null + + this.on('error', (err) => { + error = err + }) + this.on('readable', onreadable) + this.on('close', onclose) + + return { + [asyncIterator]() { + return this + }, + next() { + return new Promise(function (resolve, reject) { + promiseResolve = resolve + promiseReject = reject + const data = stream.read() + if (data !== null) ondata(data) + else if ((stream._duplexState & DESTROYED) !== 0) ondata(null) + }) + }, + return() { + return destroy(null) + }, + throw(err) { + return destroy(err) + } + } + + function onreadable() { + if (promiseResolve !== null) ondata(stream.read()) + } + + function onclose() { + if (promiseResolve !== null) ondata(null) + } + + function ondata(data) { + if (promiseReject === null) return + if (error) { + promiseReject(error) + } else if (data === null && (stream._duplexState & READ_DONE) === 0) { + promiseReject(StreamError.STREAM_DESTROYED()) + } else { + promiseResolve({ value: data, done: data === null }) + } + promiseReject = promiseResolve = null + } + + function destroy(err) { + stream.destroy(err) + return new Promise((resolve, reject) => { + if (stream._duplexState & DESTROYED) return resolve({ value: undefined, done: true }) + stream.once('close', function () { + if (err) reject(err) + else resolve({ value: undefined, done: true }) + }) + }) + } + } +} + +class Writable extends Stream { + constructor(opts) { + super(opts) + + this._duplexState |= OPENING | READ_DONE + this._writableState = new WritableState(this, opts) + + if (opts) { + if (opts.writev) this._writev = opts.writev + if (opts.write) this._write = opts.write + if (opts.final) this._final = opts.final + if (opts.eagerOpen) this._writableState.updateNextTick() + } + } + + cork() { + this._duplexState |= WRITE_CORKED + } + + uncork() { + this._duplexState &= WRITE_NOT_CORKED + this._writableState.updateNextTick() + } + + _writev(batch, cb) { + cb(null) + } + + _write(data, cb) { + this._writableState.autoBatch(data, cb) + } + + _final(cb) { + cb(null) + } + + static isBackpressured(ws) { + return (ws._duplexState & WRITE_BACKPRESSURE_STATUS) !== 0 + } + + static drained(ws) { + if (ws.destroyed) return Promise.resolve(false) + + const state = ws._writableState + const pending = isWritev(ws) ? Math.min(1, state.queue.length) : state.queue.length + const writes = pending + (ws._duplexState & WRITE_WRITING ? 1 : 0) + if (writes === 0) return Promise.resolve(true) + + if (state.drains === null) state.drains = [] + return new Promise((resolve) => { + state.drains.push({ writes, resolve }) + }) + } + + write(data) { + this._writableState.updateNextTick() + return this._writableState.push(data) + } + + end(data) { + this._writableState.updateNextTick() + this._writableState.end(data) + return this + } +} + +class Duplex extends Readable { + // and Writable + constructor(opts) { + super(opts) + + this._duplexState = OPENING | (this._duplexState & READ_READ_AHEAD) + this._writableState = new WritableState(this, opts) + + if (opts) { + if (opts.writev) this._writev = opts.writev + if (opts.write) this._write = opts.write + if (opts.final) this._final = opts.final + } + } + + cork() { + this._duplexState |= WRITE_CORKED + } + + uncork() { + this._duplexState &= WRITE_NOT_CORKED + this._writableState.updateNextTick() + } + + _writev(batch, cb) { + cb(null) + } + + _write(data, cb) { + this._writableState.autoBatch(data, cb) + } + + _final(cb) { + cb(null) + } + + write(data) { + this._writableState.updateNextTick() + return this._writableState.push(data) + } + + end(data) { + this._writableState.updateNextTick() + this._writableState.end(data) + return this + } +} + +class Transform extends Duplex { + constructor(opts) { + super(opts) + this._transformState = new TransformState(this) + + if (opts) { + if (opts.transform) this._transform = opts.transform + if (opts.flush) this._flush = opts.flush + } + } + + _write(data, cb) { + if (this._readableState.buffered >= this._readableState.highWaterMark) { + this._transformState.data = data + } else { + this._transform(data, this._transformState.afterTransform) + } + } + + _read(cb) { + if (this._transformState.data !== null) { + const data = this._transformState.data + this._transformState.data = null + cb(null) + this._transform(data, this._transformState.afterTransform) + } else { + cb(null) + } + } + + destroy(err) { + super.destroy(err) + if (this._transformState.data !== null) { + this._transformState.data = null + this._transformState.afterTransform() + } + } + + _transform(data, cb) { + cb(null, data) + } + + _flush(cb) { + cb(null) + } + + _final(cb) { + this._transformState.afterFinal = cb + this._flush(transformAfterFlush.bind(this)) + } +} + +class PassThrough extends Transform {} + +function transformAfterFlush(err, data) { + const cb = this._transformState.afterFinal + if (err) return cb(err) + + if (data !== null && data !== undefined) this.push(data) + this.push(null) + cb(null) +} + +function pipelinePromise(...streams) { + return new Promise((resolve, reject) => { + return pipeline(...streams, (err) => { + if (err) return reject(err) + resolve() + }) + }) +} + +function pipeline(stream, ...streams) { + const all = Array.isArray(stream) ? [...stream, ...streams] : [stream, ...streams] + const done = all.length && typeof all[all.length - 1] === 'function' ? all.pop() : null + + if (all.length < 2) throw StreamError.BAD_ARGUMENT('Pipeline requires at least 2 streams') + + let src = all[0] + let dest = null + let error = null + + for (let i = 1; i < all.length; i++) { + dest = all[i] + + if (isStreamx(src)) { + src.pipe(dest, onerror) + } else { + errorHandle(src, true, i > 1, onerror) + src.pipe(dest) + } + + src = dest + } + + if (done) { + let fin = false + + const autoDestroy = + isStreamx(dest) || !!(dest._writableState && dest._writableState.autoDestroy) + + dest.on('error', (err) => { + if (error === null) error = err + }) + + dest.on('finish', () => { + fin = true + if (!autoDestroy) done(error) + }) + + if (autoDestroy) { + dest.on('close', () => done(error || (fin ? null : StreamError.PREMATURE_CLOSE()))) + } + } + + return dest + + function errorHandle(s, rd, wr, onerror) { + s.on('error', onerror) + s.on('close', onclose) + + function onclose() { + if (rd && s._readableState && !s._readableState.ended) { + return onerror(StreamError.PREMATURE_CLOSE()) + } + if (wr && s._writableState && !s._writableState.ended) { + return onerror(StreamError.PREMATURE_CLOSE()) + } + } + } + + function onerror(err) { + if (!err || error) return + error = err + + for (const s of all) { + s.destroy(err) + } + } +} + +function echo(s) { + return s +} + +function isStream(stream) { + return !!stream._readableState || !!stream._writableState +} + +function isStreamx(stream) { + return typeof stream._duplexState === 'number' && isStream(stream) +} + +function isEnding(stream) { + return !!stream._readableState && stream._readableState.ending +} + +function isEnded(stream) { + return !!stream._readableState && stream._readableState.ended +} + +function isFinishing(stream) { + return !!stream._writableState && stream._writableState.ending +} + +function isFinished(stream) { + return !!stream._writableState && stream._writableState.ended +} + +function getStreamError(stream, opts = {}) { + const err = + (stream._readableState && stream._readableState.error) || + (stream._writableState && stream._writableState.error) + + // avoid implicit errors by default + return !opts.all && StreamError.isStreamDestroyed(err) ? null : err +} + +function isReadStreamx(stream) { + return isStreamx(stream) && stream.readable +} + +function isDisturbed(stream) { + return ( + (stream._duplexState & OPENING) !== OPENING || + (stream._duplexState & DESTROYING) === DESTROYING || + (stream._duplexState & ACTIVE_OR_TICKING) !== 0 + ) +} + +function isTypedArray(data) { + return typeof data === 'object' && data !== null && typeof data.byteLength === 'number' +} + +function defaultByteLength(data) { + return isTypedArray(data) ? data.byteLength : 1024 +} + +function noop() {} + +function abort() { + this.destroy(StreamError.ABORTED()) +} + +function isWritev(s) { + return s._writev !== Writable.prototype._writev && s._writev !== Duplex.prototype._writev +} + +module.exports = { + pipeline, + pipelinePromise, + isStream, + isStreamx, + isEnding, + isEnded, + isFinishing, + isFinished, + isDisturbed, + getStreamError, + Stream, + Writable, + Readable, + Duplex, + Transform, + // Export PassThrough for compatibility with Node.js core's stream module + PassThrough +} diff --git a/node_modules/streamx/lib/errors.d.ts b/node_modules/streamx/lib/errors.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e3464f5f9e0e0c727f0df7209f623633f03803c4 --- /dev/null +++ b/node_modules/streamx/lib/errors.d.ts @@ -0,0 +1,13 @@ +declare class StreamError extends Error { + readonly code: string + + static isStreamDestroyed(err: Error | null): boolean + static isPrematureClose(err: Error | null): boolean + static isAborted(err: Error | null): boolean + + static STREAM_DESTROYED(): StreamError + static PREMATURE_CLOSE(): StreamError + static ABORTED(): StreamError +} + +export = StreamError diff --git a/node_modules/streamx/lib/errors.js b/node_modules/streamx/lib/errors.js new file mode 100644 index 0000000000000000000000000000000000000000..1a19df942a425b5aa1ef12226d026ad1d2a148af --- /dev/null +++ b/node_modules/streamx/lib/errors.js @@ -0,0 +1,47 @@ +module.exports = class StreamError extends Error { + constructor(msg, code, fn = StreamError) { + super(msg) + + this.code = code + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, fn) + } + } + + static isStreamDestroyed(err) { + return err && err.code === 'STREAM_DESTROYED' + } + + static isPrematureClose(err) { + return err && err.code === 'PREMATURE_CLOSE' + } + + static isAborted(err) { + return err && err.code === 'ABORTED' + } + + static isBadArgument(err) { + return err && err.code === 'BAD_ARGUMENT' + } + + get name() { + return 'StreamError' + } + + static STREAM_DESTROYED() { + return new StreamError('Stream was destroyed', 'STREAM_DESTROYED', StreamError.STREAM_DESTROYED) + } + + static PREMATURE_CLOSE(msg = 'Premature close') { + return new StreamError(msg, 'PREMATURE_CLOSE', StreamError.PREMATURE_CLOSE) + } + + static ABORTED() { + return new StreamError('Stream aborted', 'ABORTED', StreamError.ABORTED) + } + + static BAD_ARGUMENT(msg = 'Bad argument') { + return new StreamError(msg, 'BAD_ARGUMENT', StreamError.BAD_ARGUMENT) + } +} diff --git a/node_modules/streamx/package.json b/node_modules/streamx/package.json new file mode 100644 index 0000000000000000000000000000000000000000..7657f46508bc5fb65d33fd84163394a08b0acdab --- /dev/null +++ b/node_modules/streamx/package.json @@ -0,0 +1,51 @@ +{ + "name": "streamx", + "version": "2.28.0", + "description": "An iteration of the Node.js core streams with a series of improvements", + "main": "index.js", + "exports": { + ".": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "./package": "./package.json", + "./errors": { + "types": "./lib/errors.d.ts", + "default": "./lib/errors" + } + }, + "dependencies": { + "events-universal": "^1.0.0", + "fast-fifo": "^1.3.2", + "text-decoder": "^1.1.0" + }, + "devDependencies": { + "b4a": "^1.6.6", + "brittle": "^3.1.1", + "end-of-stream": "^1.4.4", + "lunte": "^1.8.0", + "prettier": "^3.6.2", + "prettier-config-holepunch": "^2.0.0" + }, + "files": [ + "index.js", + "index.d.ts", + "runtime.d.ts", + "lib" + ], + "scripts": { + "format": "prettier . --write", + "test": "brittle test/all.js && brittle-bare test/all.js", + "lint": "prettier . --check && lunte" + }, + "repository": { + "type": "git", + "url": "https://github.com/mafintosh/streamx.git" + }, + "author": "Mathias Buus (@mafintosh)", + "license": "MIT", + "bugs": { + "url": "https://github.com/mafintosh/streamx/issues" + }, + "homepage": "https://github.com/mafintosh/streamx" +} diff --git a/node_modules/streamx/runtime.d.ts b/node_modules/streamx/runtime.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..204685a3699249d18955bdf307c3d84045ced71d --- /dev/null +++ b/node_modules/streamx/runtime.d.ts @@ -0,0 +1,55 @@ +type BufferEncoding = + | 'ascii' + | 'base64' + | 'binary' + | 'hex' + | 'latin1' + | 'ucs-2' + | 'ucs2' + | 'utf-16le' + | 'utf-8' + | 'utf16le' + | 'utf8' + +interface EventMap { + [event: string | symbol]: unknown[] +} + +interface EventHandler { + (...args: A): R +} + +interface EventEmitter { + addListener(name: E, fn: EventHandler): this + + addOnceListener(name: E, fn: EventHandler): this + + prependListener(name: E, fn: EventHandler): this + + prependOnceListener(name: E, fn: EventHandler): this + + removeListener(name: E, fn: EventHandler): this + + removeAllListeners(name?: E): this + + on(name: E, fn: EventHandler): this + + once(name: E, fn: EventHandler): this + + off(name: E, fn: EventHandler): this + + emit(name: E, ...args: M[E]): boolean + + listeners(name: E): EventHandler + + rawListeners(name: E): EventHandler[] + + eventNames(): (keyof M)[] + + listenerCount(name: E): number + + getMaxListeners(): number + setMaxListeners(n: number): void +} + +export { BufferEncoding, EventMap, EventEmitter } diff --git a/node_modules/strict-event-emitter/README.md b/node_modules/strict-event-emitter/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c972baacd488a347733c713f49b85b03d60b2ef5 --- /dev/null +++ b/node_modules/strict-event-emitter/README.md @@ -0,0 +1,79 @@ +# Strict Event Emitter + +A type-safe implementation of `EventEmitter` for browser and Node.js. + +## Motivation + +Despite event emitters potentially accepting any runtime value, defining a strict event contract is crucial when developing complex event-driven architectures. Unfortunately, the native type definitions for Node's `EventEmitter` annotate event names as `string`, which forbids any stricter type validation. + +```js +// index.js +const emitter = new EventEmitter() + +// Let's say our application expects a "ping" +// event with the number payload. +emitter.on('ping', (n: number) => {}) + +// We can, however, emit a different event by mistake. +emitter.emit('pong', 1) + +// Or even the correct event with the wrong data. +emitter.emit('ping', 'wait, not a number') +``` + +The purpose of this library is to provide an `EventEmitter` instance that can accept a generic describing the expected events contract. + +```ts +import { Emitter } from 'strict-event-emitter' + +// Define a strict events contract where keys +// represent event names and values represent +// the list of arguments expected in ".emit()". +type Events = { + ping: [number] +} + +const emitter = new Emitter() +emitter.addListener('ping', (n) => { + // "n" argument type is inferred as "number'. +}) + +emitter.emit('ping', 10) // OK +emitter.emit('unknown', 10) // TypeError (invalid event name) +emitter.emit('ping', 'wait, not a number') // TypeError (invalid data) +``` + +This library is also a custom `EventEmitter` implementation, which makes it compatible with other environments, like browsers or React Native. + +## Getting started + +### Install + +```bash +npm install strict-event-emitter +``` + +### Use + +```ts +import { Emitter } from 'strict-event-emitter' + +// 1. Define an interface that describes your events. +// Set event names as the keys, and their expected payloads as values. +interface Events { + connect: [id: string] + disconnect: [id: string] +} + +// 2. Create a strict emitter and pass the previously defined "Events" +// as its first generic argument. +const emitter = new Emitter() + +// 3. Use the "emitter" the same way you'd use the regular "EventEmitter" instance. +emitter.addListener('connect', (id) => {}) +emitter.emit('connect', 'abc-123') +``` + +## License + +MIT diff --git a/node_modules/strict-event-emitter/lib/index.d.ts b/node_modules/strict-event-emitter/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7068ce7ba148a872781e2ff1ce8160a77e05fb50 --- /dev/null +++ b/node_modules/strict-event-emitter/lib/index.d.ts @@ -0,0 +1,81 @@ +declare type EventMap = { + [eventName: string]: Array; +}; +declare type InternalEventNames = 'newListener' | 'removeListener'; +declare type InternalListener = Listener<[ + eventName: keyof Events, + listener: Listener> +]>; +declare type Listener> = (...data: Data) => void; +/** + * Node.js-compatible implementation of `EventEmitter`. + * + * @example + * const emitter = new Emitter<{ hello: [string] }>() + * emitter.on('hello', (name) => console.log(name)) + * emitter.emit('hello', 'John') + */ +declare class Emitter { + private events; + private maxListeners; + private hasWarnedAboutPotentialMemoryLeak; + static defaultMaxListeners: number; + static listenerCount(emitter: Emitter, eventName: keyof Events): number; + constructor(); + private _emitInternalEvent; + private _getListeners; + private _removeListener; + private _wrapOnceListener; + setMaxListeners(maxListeners: number): this; + /** + * Returns the current max listener value for the `Emitter` which is + * either set by `emitter.setMaxListeners(n)` or defaults to + * `Emitter.defaultMaxListeners`. + */ + getMaxListeners(): number; + /** + * Returns an array listing the events for which the emitter has registered listeners. + * The values in the array will be strings or Symbols. + */ + eventNames(): Array; + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, + * in the order they were registered, passing the supplied arguments to each. + * Returns `true` if the event has listeners, `false` otherwise. + * + * @example + * const emitter = new Emitter<{ hello: [string] }>() + * emitter.emit('hello', 'John') + */ + emit(eventName: EventName, ...data: Events[EventName]): boolean; + addListener(eventName: InternalEventNames, listener: InternalListener): this; + addListener(eventName: EventName, listener: Listener): this; + on(eventName: InternalEventNames, listener: InternalListener): this; + on(eventName: EventName, listener: Listener): this; + once(eventName: InternalEventNames, listener: InternalListener): this; + once(eventName: EventName, listener: Listener): this; + prependListener(eventName: InternalEventNames, listener: InternalListener): this; + prependListener(eventName: EventName, listener: Listener): this; + prependOnceListener(eventName: InternalEventNames, listener: InternalListener): this; + prependOnceListener(eventName: EventName, listener: Listener): this; + removeListener(eventName: InternalEventNames, listener: InternalListener): this; + removeListener(eventName: EventName, listener: Listener): this; + off(eventName: InternalEventNames, listener: InternalListener): this; + off(eventName: EventName, listener: Listener): this; + removeAllListeners(eventName?: InternalEventNames): this; + removeAllListeners(eventName?: EventName): this; + listeners(eventName: InternalEventNames): Array>; + listeners(eventName: EventName): Array>; + listenerCount(eventName: InternalEventNames): number; + listenerCount(eventName: EventName): number; + rawListeners(eventName: EventName): Array>; +} + +declare class MemoryLeakError extends Error { + readonly emitter: Emitter; + readonly type: string | number | symbol; + readonly count: number; + constructor(emitter: Emitter, type: string | number | symbol, count: number); +} + +export { Emitter, EventMap, InternalEventNames, InternalListener, Listener, MemoryLeakError }; diff --git a/node_modules/strict-event-emitter/lib/index.js b/node_modules/strict-event-emitter/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1d4bc820d2122dd6551334b1d1d533c43b7ce15f --- /dev/null +++ b/node_modules/strict-event-emitter/lib/index.js @@ -0,0 +1,198 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Emitter: () => Emitter, + MemoryLeakError: () => MemoryLeakError +}); +module.exports = __toCommonJS(src_exports); + +// src/MemoryLeakError.ts +var MemoryLeakError = class extends Error { + constructor(emitter, type, count) { + super( + `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit` + ); + this.emitter = emitter; + this.type = type; + this.count = count; + this.name = "MaxListenersExceededWarning"; + } +}; + +// src/Emitter.ts +var _Emitter = class { + static listenerCount(emitter, eventName) { + return emitter.listenerCount(eventName); + } + constructor() { + this.events = /* @__PURE__ */ new Map(); + this.maxListeners = _Emitter.defaultMaxListeners; + this.hasWarnedAboutPotentialMemoryLeak = false; + } + _emitInternalEvent(internalEventName, eventName, listener) { + this.emit( + internalEventName, + ...[eventName, listener] + ); + } + _getListeners(eventName) { + return Array.prototype.concat.apply([], this.events.get(eventName)) || []; + } + _removeListener(listeners, listener) { + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); + } + return []; + } + _wrapOnceListener(eventName, listener) { + const onceListener = (...data) => { + this.removeListener(eventName, onceListener); + return listener.apply(this, data); + }; + Object.defineProperty(onceListener, "name", { value: listener.name }); + return onceListener; + } + setMaxListeners(maxListeners) { + this.maxListeners = maxListeners; + return this; + } + /** + * Returns the current max listener value for the `Emitter` which is + * either set by `emitter.setMaxListeners(n)` or defaults to + * `Emitter.defaultMaxListeners`. + */ + getMaxListeners() { + return this.maxListeners; + } + /** + * Returns an array listing the events for which the emitter has registered listeners. + * The values in the array will be strings or Symbols. + */ + eventNames() { + return Array.from(this.events.keys()); + } + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, + * in the order they were registered, passing the supplied arguments to each. + * Returns `true` if the event has listeners, `false` otherwise. + * + * @example + * const emitter = new Emitter<{ hello: [string] }>() + * emitter.emit('hello', 'John') + */ + emit(eventName, ...data) { + const listeners = this._getListeners(eventName); + listeners.forEach((listener) => { + listener.apply(this, data); + }); + return listeners.length > 0; + } + addListener(eventName, listener) { + this._emitInternalEvent("newListener", eventName, listener); + const nextListeners = this._getListeners(eventName).concat(listener); + this.events.set(eventName, nextListeners); + if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) { + this.hasWarnedAboutPotentialMemoryLeak = true; + const memoryLeakWarning = new MemoryLeakError( + this, + eventName, + this.listenerCount(eventName) + ); + console.warn(memoryLeakWarning); + } + return this; + } + on(eventName, listener) { + return this.addListener(eventName, listener); + } + once(eventName, listener) { + return this.addListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + prependListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + const nextListeners = [listener].concat(listeners); + this.events.set(eventName, nextListeners); + } else { + this.events.set(eventName, listeners.concat(listener)); + } + return this; + } + prependOnceListener(eventName, listener) { + return this.prependListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + removeListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + this._removeListener(listeners, listener); + this.events.set(eventName, listeners); + this._emitInternalEvent("removeListener", eventName, listener); + } + return this; + } + /** + * Alias for `emitter.removeListener()`. + * + * @example + * emitter.off('hello', listener) + */ + off(eventName, listener) { + return this.removeListener(eventName, listener); + } + removeAllListeners(eventName) { + if (eventName) { + this.events.delete(eventName); + } else { + this.events.clear(); + } + return this; + } + /** + * Returns a copy of the array of listeners for the event named `eventName`. + */ + listeners(eventName) { + return Array.from(this._getListeners(eventName)); + } + /** + * Returns the number of listeners listening to the event named `eventName`. + */ + listenerCount(eventName) { + return this._getListeners(eventName).length; + } + rawListeners(eventName) { + return this.listeners(eventName); + } +}; +var Emitter = _Emitter; +Emitter.defaultMaxListeners = 10; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Emitter, + MemoryLeakError +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/strict-event-emitter/lib/index.js.map b/node_modules/strict-event-emitter/lib/index.js.map new file mode 100644 index 0000000000000000000000000000000000000000..6dd965299dba60a299b38037fa8e7173110d1c47 --- /dev/null +++ b/node_modules/strict-event-emitter/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/MemoryLeakError.ts","../src/Emitter.ts"],"sourcesContent":["export * from './Emitter'\nexport * from './MemoryLeakError'\n","import type { Emitter } from './Emitter'\n\nexport class MemoryLeakError extends Error {\n constructor(\n public readonly emitter: Emitter,\n public readonly type: string | number | symbol,\n public readonly count: number\n ) {\n super(\n `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`\n )\n this.name = 'MaxListenersExceededWarning'\n }\n}\n","import { MemoryLeakError } from './MemoryLeakError'\n\nexport type EventMap = {\n [eventName: string]: Array\n}\n\nexport type InternalEventNames = 'newListener' | 'removeListener'\n\nexport type InternalListener = Listener<\n [eventName: keyof Events, listener: Listener>]\n>\n\nexport type Listener> = (...data: Data) => void\n\n/**\n * Node.js-compatible implementation of `EventEmitter`.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.on('hello', (name) => console.log(name))\n * emitter.emit('hello', 'John')\n */\nexport class Emitter {\n private events: Map>>\n private maxListeners: number\n private hasWarnedAboutPotentialMemoryLeak: boolean\n\n static defaultMaxListeners = 10\n\n static listenerCount(\n emitter: Emitter,\n eventName: keyof Events\n ): number {\n return emitter.listenerCount(eventName)\n }\n\n constructor() {\n this.events = new Map()\n this.maxListeners = Emitter.defaultMaxListeners\n this.hasWarnedAboutPotentialMemoryLeak = false\n }\n\n private _emitInternalEvent(\n internalEventName: InternalEventNames,\n eventName: keyof Events,\n listener: Listener>\n ): void {\n this.emit(\n internalEventName,\n // Anything to make TypeScript happy.\n ...([eventName, listener] as Events['newListener'] &\n Events['removeListener'])\n )\n }\n\n private _getListeners(\n eventName: EventName\n ): Array>> {\n // Always return a copy of the listeners array\n // so they are fixed at the time of the \"_getListeners\" call.\n return Array.prototype.concat.apply([], this.events.get(eventName)) || []\n }\n\n private _removeListener(\n listeners: Array>,\n listener: Listener\n ): Array> {\n const index = listeners.indexOf(listener)\n\n if (index > -1) {\n listeners.splice(index, 1)\n }\n\n return []\n }\n\n private _wrapOnceListener(\n eventName: EventName,\n listener: Listener\n ): Listener {\n const onceListener = (...data: Events[keyof Events]) => {\n this.removeListener(eventName, onceListener)\n\n /**\n * @note Return the result of the original listener.\n * This way this wrapped preserves listeners that are async.\n */\n return listener.apply(this, data)\n }\n\n // Inherit the name of the original listener.\n Object.defineProperty(onceListener, 'name', { value: listener.name })\n\n return onceListener\n }\n\n public setMaxListeners(maxListeners: number): this {\n this.maxListeners = maxListeners\n return this\n }\n\n /**\n * Returns the current max listener value for the `Emitter` which is\n * either set by `emitter.setMaxListeners(n)` or defaults to\n * `Emitter.defaultMaxListeners`.\n */\n public getMaxListeners(): number {\n return this.maxListeners\n }\n\n /**\n * Returns an array listing the events for which the emitter has registered listeners.\n * The values in the array will be strings or Symbols.\n */\n public eventNames(): Array {\n return Array.from(this.events.keys())\n }\n\n /**\n * Synchronously calls each of the listeners registered for the event named `eventName`,\n * in the order they were registered, passing the supplied arguments to each.\n * Returns `true` if the event has listeners, `false` otherwise.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.emit('hello', 'John')\n */\n public emit(\n eventName: EventName,\n ...data: Events[EventName]\n ): boolean {\n const listeners = this._getListeners(eventName)\n listeners.forEach((listener) => {\n listener.apply(this, data)\n })\n\n return listeners.length > 0\n }\n\n public addListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public addListener(\n eventName: EventName,\n listener: Listener\n ): this\n public addListener(\n eventName: InternalEventNames | keyof Events,\n listener: InternalListener | Listener\n ): this {\n // Emit the `newListener` event before adding the listener.\n this._emitInternalEvent('newListener', eventName, listener)\n\n const nextListeners = this._getListeners(eventName).concat(listener)\n this.events.set(eventName, nextListeners)\n\n if (\n this.maxListeners > 0 &&\n this.listenerCount(eventName) > this.maxListeners &&\n !this.hasWarnedAboutPotentialMemoryLeak\n ) {\n this.hasWarnedAboutPotentialMemoryLeak = true\n\n const memoryLeakWarning = new MemoryLeakError(\n this,\n eventName,\n this.listenerCount(eventName)\n )\n console.warn(memoryLeakWarning)\n }\n\n return this\n }\n\n public on(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public on(\n eventName: EventName,\n listener: Listener\n ): this\n public on(\n eventName: 'removeListener' | EventName,\n listener: Listener\n ): this {\n return this.addListener(eventName, listener)\n }\n\n public once(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public once(\n eventName: EventName,\n listener: Listener\n ): this\n public once(\n eventName: InternalEventNames | EventName,\n listener: Listener\n ): this {\n return this.addListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public prependListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n const nextListeners = [listener].concat(listeners)\n this.events.set(eventName, nextListeners)\n } else {\n this.events.set(eventName, listeners.concat(listener))\n }\n\n return this\n }\n\n public prependOnceListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependOnceListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependOnceListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.prependListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public removeListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public removeListener(\n eventName: EventName,\n listener: Listener\n ): this\n public removeListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n this._removeListener(listeners, listener)\n this.events.set(eventName, listeners)\n\n // Emit the `removeListener` event after removing the listener.\n this._emitInternalEvent('removeListener', eventName, listener)\n }\n\n return this\n }\n\n public off(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public off(\n eventName: EventName,\n listener: Listener\n ): this\n /**\n * Alias for `emitter.removeListener()`.\n *\n * @example\n * emitter.off('hello', listener)\n */\n public off(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.removeListener(eventName, listener)\n }\n\n public removeAllListeners(eventName?: InternalEventNames): this\n public removeAllListeners(\n eventName?: EventName\n ): this\n public removeAllListeners(\n eventName?: InternalEventNames | keyof Events\n ): this {\n if (eventName) {\n this.events.delete(eventName)\n } else {\n this.events.clear()\n }\n\n return this\n }\n\n public listeners(eventName: InternalEventNames): Array>\n public listeners(\n eventName: EventName\n ): Array>\n /**\n * Returns a copy of the array of listeners for the event named `eventName`.\n */\n public listeners(eventName: InternalEventNames | keyof Events) {\n return Array.from(this._getListeners(eventName))\n }\n\n public listenerCount(eventName: InternalEventNames): number\n public listenerCount(\n eventName: EventName\n ): number\n /**\n * Returns the number of listeners listening to the event named `eventName`.\n */\n public listenerCount(eventName: InternalEventNames | keyof Events): number {\n return this._getListeners(eventName).length\n }\n\n public rawListeners(\n eventName: EventName\n ): Array> {\n return this.listeners(eventName)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACkB,SACA,MACA,OAChB;AACA;AAAA,MACE,+CAA+C,SAAS,KAAK,SAAS;AAAA,IACxE;AANgB;AACA;AACA;AAKhB,SAAK,OAAO;AAAA,EACd;AACF;;;ACSO,IAAM,WAAN,MAAuC;AAAA,EAO5C,OAAO,cACL,SACA,WACQ;AACR,WAAO,QAAQ,cAAmB,SAAS;AAAA,EAC7C;AAAA,EAEA,cAAc;AACZ,SAAK,SAAS,oBAAI,IAAI;AACtB,SAAK,eAAe,SAAQ;AAC5B,SAAK,oCAAoC;AAAA,EAC3C;AAAA,EAEQ,mBACN,mBACA,WACA,UACM;AACN,SAAK;AAAA,MACH;AAAA,MAEA,GAAI,CAAC,WAAW,QAAQ;AAAA,IAE1B;AAAA,EACF;AAAA,EAEQ,cACN,WACiC;AAGjC,WAAO,MAAM,UAAU,OAAO,MAAM,CAAC,GAAG,KAAK,OAAO,IAAI,SAAS,CAAC,KAAK,CAAC;AAAA,EAC1E;AAAA,EAEQ,gBACN,WACA,UACoC;AACpC,UAAM,QAAQ,UAAU,QAAQ,QAAQ;AAExC,QAAI,QAAQ,IAAI;AACd,gBAAU,OAAO,OAAO,CAAC;AAAA,IAC3B;AAEA,WAAO,CAAC;AAAA,EACV;AAAA,EAEQ,kBACN,WACA,UAC6B;AAC7B,UAAM,eAAe,IAAI,SAA+B;AACtD,WAAK,eAAe,WAAW,YAAY;AAM3C,aAAO,SAAS,MAAM,MAAM,IAAI;AAAA,IAClC;AAGA,WAAO,eAAe,cAAc,QAAQ,EAAE,OAAO,SAAS,KAAK,CAAC;AAEpE,WAAO;AAAA,EACT;AAAA,EAEO,gBAAgB,cAA4B;AACjD,SAAK,eAAe;AACpB,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,kBAA0B;AAC/B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMO,aAAkC;AACvC,WAAO,MAAM,KAAK,KAAK,OAAO,KAAK,CAAC;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWO,KACL,cACG,MACM;AACT,UAAM,YAAY,KAAK,cAAc,SAAS;AAC9C,cAAU,QAAQ,CAAC,aAAa;AAC9B,eAAS,MAAM,MAAM,IAAI;AAAA,IAC3B,CAAC;AAED,WAAO,UAAU,SAAS;AAAA,EAC5B;AAAA,EAUO,YACL,WACA,UACM;AAEN,SAAK,mBAAmB,eAAe,WAAW,QAAQ;AAE1D,UAAM,gBAAgB,KAAK,cAAc,SAAS,EAAE,OAAO,QAAQ;AACnE,SAAK,OAAO,IAAI,WAAW,aAAa;AAExC,QACE,KAAK,eAAe,KACpB,KAAK,cAAc,SAAS,IAAI,KAAK,gBACrC,CAAC,KAAK,mCACN;AACA,WAAK,oCAAoC;AAEzC,YAAM,oBAAoB,IAAI;AAAA,QAC5B;AAAA,QACA;AAAA,QACA,KAAK,cAAc,SAAS;AAAA,MAC9B;AACA,cAAQ,KAAK,iBAAiB;AAAA,IAChC;AAEA,WAAO;AAAA,EACT;AAAA,EAUO,GACL,WACA,UACM;AACN,WAAO,KAAK,YAAY,WAAW,QAAQ;AAAA,EAC7C;AAAA,EAUO,KACL,WACA,UACM;AACN,WAAO,KAAK;AAAA,MACV;AAAA,MACA,KAAK,kBAAkB,WAAW,QAAQ;AAAA,IAC5C;AAAA,EACF;AAAA,EAUO,gBACL,WACA,UACM;AACN,UAAM,YAAY,KAAK,cAAc,SAAS;AAE9C,QAAI,UAAU,SAAS,GAAG;AACxB,YAAM,gBAAgB,CAAC,QAAQ,EAAE,OAAO,SAAS;AACjD,WAAK,OAAO,IAAI,WAAW,aAAa;AAAA,IAC1C,OAAO;AACL,WAAK,OAAO,IAAI,WAAW,UAAU,OAAO,QAAQ,CAAC;AAAA,IACvD;AAEA,WAAO;AAAA,EACT;AAAA,EAUO,oBACL,WACA,UACM;AACN,WAAO,KAAK;AAAA,MACV;AAAA,MACA,KAAK,kBAAkB,WAAW,QAAQ;AAAA,IAC5C;AAAA,EACF;AAAA,EAUO,eACL,WACA,UACM;AACN,UAAM,YAAY,KAAK,cAAc,SAAS;AAE9C,QAAI,UAAU,SAAS,GAAG;AACxB,WAAK,gBAAgB,WAAW,QAAQ;AACxC,WAAK,OAAO,IAAI,WAAW,SAAS;AAGpC,WAAK,mBAAmB,kBAAkB,WAAW,QAAQ;AAAA,IAC/D;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBO,IACL,WACA,UACM;AACN,WAAO,KAAK,eAAe,WAAW,QAAQ;AAAA,EAChD;AAAA,EAMO,mBACL,WACM;AACN,QAAI,WAAW;AACb,WAAK,OAAO,OAAO,SAAS;AAAA,IAC9B,OAAO;AACL,WAAK,OAAO,MAAM;AAAA,IACpB;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EASO,UAAU,WAA8C;AAC7D,WAAO,MAAM,KAAK,KAAK,cAAc,SAAS,CAAC;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA,EASO,cAAc,WAAsD;AACzE,WAAO,KAAK,cAAc,SAAS,EAAE;AAAA,EACvC;AAAA,EAEO,aACL,WACoC;AACpC,WAAO,KAAK,UAAU,SAAS;AAAA,EACjC;AACF;AA7TO,IAAM,UAAN;AAAM,QAKJ,sBAAsB;","names":[]} \ No newline at end of file diff --git a/node_modules/strict-event-emitter/lib/index.mjs b/node_modules/strict-event-emitter/lib/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d68faf826181af771158237f8d4ce5a95a08974c --- /dev/null +++ b/node_modules/strict-event-emitter/lib/index.mjs @@ -0,0 +1,171 @@ +// src/MemoryLeakError.ts +var MemoryLeakError = class extends Error { + constructor(emitter, type, count) { + super( + `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit` + ); + this.emitter = emitter; + this.type = type; + this.count = count; + this.name = "MaxListenersExceededWarning"; + } +}; + +// src/Emitter.ts +var _Emitter = class { + static listenerCount(emitter, eventName) { + return emitter.listenerCount(eventName); + } + constructor() { + this.events = /* @__PURE__ */ new Map(); + this.maxListeners = _Emitter.defaultMaxListeners; + this.hasWarnedAboutPotentialMemoryLeak = false; + } + _emitInternalEvent(internalEventName, eventName, listener) { + this.emit( + internalEventName, + ...[eventName, listener] + ); + } + _getListeners(eventName) { + return Array.prototype.concat.apply([], this.events.get(eventName)) || []; + } + _removeListener(listeners, listener) { + const index = listeners.indexOf(listener); + if (index > -1) { + listeners.splice(index, 1); + } + return []; + } + _wrapOnceListener(eventName, listener) { + const onceListener = (...data) => { + this.removeListener(eventName, onceListener); + return listener.apply(this, data); + }; + Object.defineProperty(onceListener, "name", { value: listener.name }); + return onceListener; + } + setMaxListeners(maxListeners) { + this.maxListeners = maxListeners; + return this; + } + /** + * Returns the current max listener value for the `Emitter` which is + * either set by `emitter.setMaxListeners(n)` or defaults to + * `Emitter.defaultMaxListeners`. + */ + getMaxListeners() { + return this.maxListeners; + } + /** + * Returns an array listing the events for which the emitter has registered listeners. + * The values in the array will be strings or Symbols. + */ + eventNames() { + return Array.from(this.events.keys()); + } + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, + * in the order they were registered, passing the supplied arguments to each. + * Returns `true` if the event has listeners, `false` otherwise. + * + * @example + * const emitter = new Emitter<{ hello: [string] }>() + * emitter.emit('hello', 'John') + */ + emit(eventName, ...data) { + const listeners = this._getListeners(eventName); + listeners.forEach((listener) => { + listener.apply(this, data); + }); + return listeners.length > 0; + } + addListener(eventName, listener) { + this._emitInternalEvent("newListener", eventName, listener); + const nextListeners = this._getListeners(eventName).concat(listener); + this.events.set(eventName, nextListeners); + if (this.maxListeners > 0 && this.listenerCount(eventName) > this.maxListeners && !this.hasWarnedAboutPotentialMemoryLeak) { + this.hasWarnedAboutPotentialMemoryLeak = true; + const memoryLeakWarning = new MemoryLeakError( + this, + eventName, + this.listenerCount(eventName) + ); + console.warn(memoryLeakWarning); + } + return this; + } + on(eventName, listener) { + return this.addListener(eventName, listener); + } + once(eventName, listener) { + return this.addListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + prependListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + const nextListeners = [listener].concat(listeners); + this.events.set(eventName, nextListeners); + } else { + this.events.set(eventName, listeners.concat(listener)); + } + return this; + } + prependOnceListener(eventName, listener) { + return this.prependListener( + eventName, + this._wrapOnceListener(eventName, listener) + ); + } + removeListener(eventName, listener) { + const listeners = this._getListeners(eventName); + if (listeners.length > 0) { + this._removeListener(listeners, listener); + this.events.set(eventName, listeners); + this._emitInternalEvent("removeListener", eventName, listener); + } + return this; + } + /** + * Alias for `emitter.removeListener()`. + * + * @example + * emitter.off('hello', listener) + */ + off(eventName, listener) { + return this.removeListener(eventName, listener); + } + removeAllListeners(eventName) { + if (eventName) { + this.events.delete(eventName); + } else { + this.events.clear(); + } + return this; + } + /** + * Returns a copy of the array of listeners for the event named `eventName`. + */ + listeners(eventName) { + return Array.from(this._getListeners(eventName)); + } + /** + * Returns the number of listeners listening to the event named `eventName`. + */ + listenerCount(eventName) { + return this._getListeners(eventName).length; + } + rawListeners(eventName) { + return this.listeners(eventName); + } +}; +var Emitter = _Emitter; +Emitter.defaultMaxListeners = 10; +export { + Emitter, + MemoryLeakError +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/strict-event-emitter/lib/index.mjs.map b/node_modules/strict-event-emitter/lib/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..26936046f3a77146abe223b67f555d4854c36b31 --- /dev/null +++ b/node_modules/strict-event-emitter/lib/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/MemoryLeakError.ts","../src/Emitter.ts"],"sourcesContent":["import type { Emitter } from './Emitter'\n\nexport class MemoryLeakError extends Error {\n constructor(\n public readonly emitter: Emitter,\n public readonly type: string | number | symbol,\n public readonly count: number\n ) {\n super(\n `Possible EventEmitter memory leak detected. ${count} ${type.toString()} listeners added. Use emitter.setMaxListeners() to increase limit`\n )\n this.name = 'MaxListenersExceededWarning'\n }\n}\n","import { MemoryLeakError } from './MemoryLeakError'\n\nexport type EventMap = {\n [eventName: string]: Array\n}\n\nexport type InternalEventNames = 'newListener' | 'removeListener'\n\nexport type InternalListener = Listener<\n [eventName: keyof Events, listener: Listener>]\n>\n\nexport type Listener> = (...data: Data) => void\n\n/**\n * Node.js-compatible implementation of `EventEmitter`.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.on('hello', (name) => console.log(name))\n * emitter.emit('hello', 'John')\n */\nexport class Emitter {\n private events: Map>>\n private maxListeners: number\n private hasWarnedAboutPotentialMemoryLeak: boolean\n\n static defaultMaxListeners = 10\n\n static listenerCount(\n emitter: Emitter,\n eventName: keyof Events\n ): number {\n return emitter.listenerCount(eventName)\n }\n\n constructor() {\n this.events = new Map()\n this.maxListeners = Emitter.defaultMaxListeners\n this.hasWarnedAboutPotentialMemoryLeak = false\n }\n\n private _emitInternalEvent(\n internalEventName: InternalEventNames,\n eventName: keyof Events,\n listener: Listener>\n ): void {\n this.emit(\n internalEventName,\n // Anything to make TypeScript happy.\n ...([eventName, listener] as Events['newListener'] &\n Events['removeListener'])\n )\n }\n\n private _getListeners(\n eventName: EventName\n ): Array>> {\n // Always return a copy of the listeners array\n // so they are fixed at the time of the \"_getListeners\" call.\n return Array.prototype.concat.apply([], this.events.get(eventName)) || []\n }\n\n private _removeListener(\n listeners: Array>,\n listener: Listener\n ): Array> {\n const index = listeners.indexOf(listener)\n\n if (index > -1) {\n listeners.splice(index, 1)\n }\n\n return []\n }\n\n private _wrapOnceListener(\n eventName: EventName,\n listener: Listener\n ): Listener {\n const onceListener = (...data: Events[keyof Events]) => {\n this.removeListener(eventName, onceListener)\n\n /**\n * @note Return the result of the original listener.\n * This way this wrapped preserves listeners that are async.\n */\n return listener.apply(this, data)\n }\n\n // Inherit the name of the original listener.\n Object.defineProperty(onceListener, 'name', { value: listener.name })\n\n return onceListener\n }\n\n public setMaxListeners(maxListeners: number): this {\n this.maxListeners = maxListeners\n return this\n }\n\n /**\n * Returns the current max listener value for the `Emitter` which is\n * either set by `emitter.setMaxListeners(n)` or defaults to\n * `Emitter.defaultMaxListeners`.\n */\n public getMaxListeners(): number {\n return this.maxListeners\n }\n\n /**\n * Returns an array listing the events for which the emitter has registered listeners.\n * The values in the array will be strings or Symbols.\n */\n public eventNames(): Array {\n return Array.from(this.events.keys())\n }\n\n /**\n * Synchronously calls each of the listeners registered for the event named `eventName`,\n * in the order they were registered, passing the supplied arguments to each.\n * Returns `true` if the event has listeners, `false` otherwise.\n *\n * @example\n * const emitter = new Emitter<{ hello: [string] }>()\n * emitter.emit('hello', 'John')\n */\n public emit(\n eventName: EventName,\n ...data: Events[EventName]\n ): boolean {\n const listeners = this._getListeners(eventName)\n listeners.forEach((listener) => {\n listener.apply(this, data)\n })\n\n return listeners.length > 0\n }\n\n public addListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public addListener(\n eventName: EventName,\n listener: Listener\n ): this\n public addListener(\n eventName: InternalEventNames | keyof Events,\n listener: InternalListener | Listener\n ): this {\n // Emit the `newListener` event before adding the listener.\n this._emitInternalEvent('newListener', eventName, listener)\n\n const nextListeners = this._getListeners(eventName).concat(listener)\n this.events.set(eventName, nextListeners)\n\n if (\n this.maxListeners > 0 &&\n this.listenerCount(eventName) > this.maxListeners &&\n !this.hasWarnedAboutPotentialMemoryLeak\n ) {\n this.hasWarnedAboutPotentialMemoryLeak = true\n\n const memoryLeakWarning = new MemoryLeakError(\n this,\n eventName,\n this.listenerCount(eventName)\n )\n console.warn(memoryLeakWarning)\n }\n\n return this\n }\n\n public on(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public on(\n eventName: EventName,\n listener: Listener\n ): this\n public on(\n eventName: 'removeListener' | EventName,\n listener: Listener\n ): this {\n return this.addListener(eventName, listener)\n }\n\n public once(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public once(\n eventName: EventName,\n listener: Listener\n ): this\n public once(\n eventName: InternalEventNames | EventName,\n listener: Listener\n ): this {\n return this.addListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public prependListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n const nextListeners = [listener].concat(listeners)\n this.events.set(eventName, nextListeners)\n } else {\n this.events.set(eventName, listeners.concat(listener))\n }\n\n return this\n }\n\n public prependOnceListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public prependOnceListener(\n eventName: EventName,\n listener: Listener\n ): this\n public prependOnceListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.prependListener(\n eventName,\n this._wrapOnceListener(eventName, listener)\n )\n }\n\n public removeListener(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public removeListener(\n eventName: EventName,\n listener: Listener\n ): this\n public removeListener(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n const listeners = this._getListeners(eventName)\n\n if (listeners.length > 0) {\n this._removeListener(listeners, listener)\n this.events.set(eventName, listeners)\n\n // Emit the `removeListener` event after removing the listener.\n this._emitInternalEvent('removeListener', eventName, listener)\n }\n\n return this\n }\n\n public off(\n eventName: InternalEventNames,\n listener: InternalListener\n ): this\n public off(\n eventName: EventName,\n listener: Listener\n ): this\n /**\n * Alias for `emitter.removeListener()`.\n *\n * @example\n * emitter.off('hello', listener)\n */\n public off(\n eventName: InternalEventNames | keyof Events,\n listener: Listener\n ): this {\n return this.removeListener(eventName, listener)\n }\n\n public removeAllListeners(eventName?: InternalEventNames): this\n public removeAllListeners(\n eventName?: EventName\n ): this\n public removeAllListeners(\n eventName?: InternalEventNames | keyof Events\n ): this {\n if (eventName) {\n this.events.delete(eventName)\n } else {\n this.events.clear()\n }\n\n return this\n }\n\n public listeners(eventName: InternalEventNames): Array>\n public listeners(\n eventName: EventName\n ): Array>\n /**\n * Returns a copy of the array of listeners for the event named `eventName`.\n */\n public listeners(eventName: InternalEventNames | keyof Events) {\n return Array.from(this._getListeners(eventName))\n }\n\n public listenerCount(eventName: InternalEventNames): number\n public listenerCount(\n eventName: EventName\n ): number\n /**\n * Returns the number of listeners listening to the event named `eventName`.\n */\n public listenerCount(eventName: InternalEventNames | keyof Events): number {\n return this._getListeners(eventName).length\n }\n\n public rawListeners(\n eventName: EventName\n ): Array> {\n return this.listeners(eventName)\n }\n}\n"],"mappings":";AAEO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YACkB,SACA,MACA,OAChB;AACA;AAAA,MACE,+CAA+C,SAAS,KAAK,SAAS;AAAA,IACxE;AANgB;AACA;AACA;AAKhB,SAAK,OAAO;AAAA,EACd;AACF;;;ACSO,IAAM,WAAN,MAAuC;AAAA,EAO5C,OAAO,cACL,SACA,WACQ;AACR,WAAO,QAAQ,cAAmB,SAAS;AAAA,EAC7C;AAAA,EAEA,cAAc;AACZ,SAAK,SAAS,oBAAI,IAAI;AACtB,SAAK,eAAe,SAAQ;AAC5B,SAAK,oCAAoC;AAAA,EAC3C;AAAA,EAEQ,mBACN,mBACA,WACA,UACM;AACN,SAAK;AAAA,MACH;AAAA,MAEA,GAAI,CAAC,WAAW,QAAQ;AAAA,IAE1B;AAAA,EACF;AAAA,EAEQ,cACN,WACiC;AAGjC,WAAO,MAAM,UAAU,OAAO,MAAM,CAAC,GAAG,KAAK,OAAO,IAAI,SAAS,CAAC,KAAK,CAAC;AAAA,EAC1E;AAAA,EAEQ,gBACN,WACA,UACoC;AACpC,UAAM,QAAQ,UAAU,QAAQ,QAAQ;AAExC,QAAI,QAAQ,IAAI;AACd,gBAAU,OAAO,OAAO,CAAC;AAAA,IAC3B;AAEA,WAAO,CAAC;AAAA,EACV;AAAA,EAEQ,kBACN,WACA,UAC6B;AAC7B,UAAM,eAAe,IAAI,SAA+B;AACtD,WAAK,eAAe,WAAW,YAAY;AAM3C,aAAO,SAAS,MAAM,MAAM,IAAI;AAAA,IAClC;AAGA,WAAO,eAAe,cAAc,QAAQ,EAAE,OAAO,SAAS,KAAK,CAAC;AAEpE,WAAO;AAAA,EACT;AAAA,EAEO,gBAAgB,cAA4B;AACjD,SAAK,eAAe;AACpB,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOO,kBAA0B;AAC/B,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA,EAMO,aAAkC;AACvC,WAAO,MAAM,KAAK,KAAK,OAAO,KAAK,CAAC;AAAA,EACtC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWO,KACL,cACG,MACM;AACT,UAAM,YAAY,KAAK,cAAc,SAAS;AAC9C,cAAU,QAAQ,CAAC,aAAa;AAC9B,eAAS,MAAM,MAAM,IAAI;AAAA,IAC3B,CAAC;AAED,WAAO,UAAU,SAAS;AAAA,EAC5B;AAAA,EAUO,YACL,WACA,UACM;AAEN,SAAK,mBAAmB,eAAe,WAAW,QAAQ;AAE1D,UAAM,gBAAgB,KAAK,cAAc,SAAS,EAAE,OAAO,QAAQ;AACnE,SAAK,OAAO,IAAI,WAAW,aAAa;AAExC,QACE,KAAK,eAAe,KACpB,KAAK,cAAc,SAAS,IAAI,KAAK,gBACrC,CAAC,KAAK,mCACN;AACA,WAAK,oCAAoC;AAEzC,YAAM,oBAAoB,IAAI;AAAA,QAC5B;AAAA,QACA;AAAA,QACA,KAAK,cAAc,SAAS;AAAA,MAC9B;AACA,cAAQ,KAAK,iBAAiB;AAAA,IAChC;AAEA,WAAO;AAAA,EACT;AAAA,EAUO,GACL,WACA,UACM;AACN,WAAO,KAAK,YAAY,WAAW,QAAQ;AAAA,EAC7C;AAAA,EAUO,KACL,WACA,UACM;AACN,WAAO,KAAK;AAAA,MACV;AAAA,MACA,KAAK,kBAAkB,WAAW,QAAQ;AAAA,IAC5C;AAAA,EACF;AAAA,EAUO,gBACL,WACA,UACM;AACN,UAAM,YAAY,KAAK,cAAc,SAAS;AAE9C,QAAI,UAAU,SAAS,GAAG;AACxB,YAAM,gBAAgB,CAAC,QAAQ,EAAE,OAAO,SAAS;AACjD,WAAK,OAAO,IAAI,WAAW,aAAa;AAAA,IAC1C,OAAO;AACL,WAAK,OAAO,IAAI,WAAW,UAAU,OAAO,QAAQ,CAAC;AAAA,IACvD;AAEA,WAAO;AAAA,EACT;AAAA,EAUO,oBACL,WACA,UACM;AACN,WAAO,KAAK;AAAA,MACV;AAAA,MACA,KAAK,kBAAkB,WAAW,QAAQ;AAAA,IAC5C;AAAA,EACF;AAAA,EAUO,eACL,WACA,UACM;AACN,UAAM,YAAY,KAAK,cAAc,SAAS;AAE9C,QAAI,UAAU,SAAS,GAAG;AACxB,WAAK,gBAAgB,WAAW,QAAQ;AACxC,WAAK,OAAO,IAAI,WAAW,SAAS;AAGpC,WAAK,mBAAmB,kBAAkB,WAAW,QAAQ;AAAA,IAC/D;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAgBO,IACL,WACA,UACM;AACN,WAAO,KAAK,eAAe,WAAW,QAAQ;AAAA,EAChD;AAAA,EAMO,mBACL,WACM;AACN,QAAI,WAAW;AACb,WAAK,OAAO,OAAO,SAAS;AAAA,IAC9B,OAAO;AACL,WAAK,OAAO,MAAM;AAAA,IACpB;AAEA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EASO,UAAU,WAA8C;AAC7D,WAAO,MAAM,KAAK,KAAK,cAAc,SAAS,CAAC;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA,EASO,cAAc,WAAsD;AACzE,WAAO,KAAK,cAAc,SAAS,EAAE;AAAA,EACvC;AAAA,EAEO,aACL,WACoC;AACpC,WAAO,KAAK,UAAU,SAAS;AAAA,EACjC;AACF;AA7TO,IAAM,UAAN;AAAM,QAKJ,sBAAsB;","names":[]} \ No newline at end of file diff --git a/node_modules/strict-event-emitter/package.json b/node_modules/strict-event-emitter/package.json new file mode 100644 index 0000000000000000000000000000000000000000..54a40577dd875aa198f5c2f8bee2201718c1b5f8 --- /dev/null +++ b/node_modules/strict-event-emitter/package.json @@ -0,0 +1,41 @@ +{ + "name": "strict-event-emitter", + "version": "0.5.1", + "description": "Type-safe implementation of EventEmitter for browser and Node.js", + "main": "lib/index.js", + "module": "lib/index.mjs", + "typings": "lib/index.d.ts", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "require": "./lib/index.js", + "default": "./lib/index.mjs" + } + }, + "repository": "git@github.com:open-draft/strict-event-emitter.git", + "author": "Artem Zakharchenko ", + "license": "MIT", + "files": [ + "lib" + ], + "devDependencies": { + "@ossjs/release": "^0.8.0", + "@types/events": "^3.0.0", + "@types/jest": "^29.2.4", + "jest": "^29.3.1", + "jest-extended": "^3.2.0", + "rimraf": "^3.0.2", + "ts-jest": "^29.0.3", + "ts-node": "^9.1.1", + "tsup": "^6.2.3", + "typescript": "4.8" + }, + "scripts": { + "dev": "tsc -w", + "test": "jest", + "test:ts": "tsc -p test/typings.tsconfig.json", + "clean": "rimraf ./lib", + "build": "pnpm clean && tsup", + "release": "release publish" + } +} \ No newline at end of file diff --git a/node_modules/string-width/index.d.ts b/node_modules/string-width/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..459f9b84c002b73a9d0399501946802afa0efd4a --- /dev/null +++ b/node_modules/string-width/index.d.ts @@ -0,0 +1,39 @@ +export type Options = { + /** + Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2). + + @default true + + > Ambiguous characters behave like wide or narrow characters depending on the context (language tag, script identification, associated font, source of data, or explicit markup; all can provide the context). __If the context cannot be established reliably, they should be treated as narrow characters by default.__ + > - http://www.unicode.org/reports/tr11/ + */ + readonly ambiguousIsNarrow?: boolean; + + /** + Whether [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) should be counted. + + @default false + */ + readonly countAnsiEscapeCodes?: boolean; +}; + +/** +Get the visual width of a string - the number of columns required to display it. + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +@example +``` +import stringWidth from 'string-width'; + +stringWidth('a'); +//=> 1 + +stringWidth('古'); +//=> 2 + +stringWidth('\u001B[1m古\u001B[22m'); +//=> 2 +``` +*/ +export default function stringWidth(string: string, options?: Options): number; diff --git a/node_modules/string-width/index.js b/node_modules/string-width/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8a24115cedc830107314135eac2d070089beed48 --- /dev/null +++ b/node_modules/string-width/index.js @@ -0,0 +1,82 @@ +import stripAnsi from 'strip-ansi'; +import {eastAsianWidth} from 'get-east-asian-width'; +import emojiRegex from 'emoji-regex'; + +const segmenter = new Intl.Segmenter(); + +const defaultIgnorableCodePointRegex = /^\p{Default_Ignorable_Code_Point}$/u; + +export default function stringWidth(string, options = {}) { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + const { + ambiguousIsNarrow = true, + countAnsiEscapeCodes = false, + } = options; + + if (!countAnsiEscapeCodes) { + string = stripAnsi(string); + } + + if (string.length === 0) { + return 0; + } + + let width = 0; + const eastAsianWidthOptions = {ambiguousAsWide: !ambiguousIsNarrow}; + + for (const {segment: character} of segmenter.segment(string)) { + const codePoint = character.codePointAt(0); + + // Ignore control characters + if (codePoint <= 0x1F || (codePoint >= 0x7F && codePoint <= 0x9F)) { + continue; + } + + // Ignore zero-width characters + if ( + (codePoint >= 0x20_0B && codePoint <= 0x20_0F) // Zero-width space, non-joiner, joiner, left-to-right mark, right-to-left mark + || codePoint === 0xFE_FF // Zero-width no-break space + ) { + continue; + } + + // Ignore combining characters + if ( + (codePoint >= 0x3_00 && codePoint <= 0x3_6F) // Combining diacritical marks + || (codePoint >= 0x1A_B0 && codePoint <= 0x1A_FF) // Combining diacritical marks extended + || (codePoint >= 0x1D_C0 && codePoint <= 0x1D_FF) // Combining diacritical marks supplement + || (codePoint >= 0x20_D0 && codePoint <= 0x20_FF) // Combining diacritical marks for symbols + || (codePoint >= 0xFE_20 && codePoint <= 0xFE_2F) // Combining half marks + ) { + continue; + } + + // Ignore surrogate pairs + if (codePoint >= 0xD8_00 && codePoint <= 0xDF_FF) { + continue; + } + + // Ignore variation selectors + if (codePoint >= 0xFE_00 && codePoint <= 0xFE_0F) { + continue; + } + + // This covers some of the above cases, but we still keep them for performance reasons. + if (defaultIgnorableCodePointRegex.test(character)) { + continue; + } + + // TODO: Use `/\p{RGI_Emoji}/v` when targeting Node.js 20. + if (emojiRegex().test(character)) { + width += 2; + continue; + } + + width += eastAsianWidth(codePoint, eastAsianWidthOptions); + } + + return width; +} diff --git a/node_modules/string-width/license b/node_modules/string-width/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/string-width/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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. diff --git a/node_modules/string-width/package.json b/node_modules/string-width/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cafec041efe7b4592bc8b674dbc15b9a672db95e --- /dev/null +++ b/node_modules/string-width/package.json @@ -0,0 +1,64 @@ +{ + "name": "string-width", + "version": "7.2.0", + "description": "Get the visual width of a string - the number of columns required to display it", + "license": "MIT", + "repository": "sindresorhus/string-width", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": { + "types": "./index.d.ts", + "default": "./index.js" + }, + "sideEffects": false, + "engines": { + "node": ">=18" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "string", + "character", + "unicode", + "width", + "visual", + "column", + "columns", + "fullwidth", + "full-width", + "full", + "ansi", + "escape", + "codes", + "cli", + "command-line", + "terminal", + "console", + "cjk", + "chinese", + "japanese", + "korean", + "fixed-width", + "east-asian-width" + ], + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "devDependencies": { + "ava": "^5.3.1", + "tsd": "^0.29.0", + "xo": "^0.56.0" + } +} diff --git a/node_modules/string-width/readme.md b/node_modules/string-width/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..1cccd008c825f2795c95bb817eabb1441d24de40 --- /dev/null +++ b/node_modules/string-width/readme.md @@ -0,0 +1,66 @@ +# string-width + +> Get the visual width of a string - the number of columns required to display it + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +Useful to be able to measure the actual width of command-line output. + +## Install + +```sh +npm install string-width +``` + +## Usage + +```js +import stringWidth from 'string-width'; + +stringWidth('a'); +//=> 1 + +stringWidth('古'); +//=> 2 + +stringWidth('\u001B[1m古\u001B[22m'); +//=> 2 +``` + +## API + +### stringWidth(string, options?) + +#### string + +Type: `string` + +The string to be counted. + +#### options + +Type: `object` + +##### ambiguousIsNarrow + +Type: `boolean`\ +Default: `true` + +Count [ambiguous width characters](https://www.unicode.org/reports/tr11/#Ambiguous) as having narrow width (count of 1) instead of wide width (count of 2). + +> Ambiguous characters behave like wide or narrow characters depending on the context (language tag, script identification, associated font, source of data, or explicit markup; all can provide the context). **If the context cannot be established reliably, they should be treated as narrow characters by default.** +> - http://www.unicode.org/reports/tr11/ + +##### countAnsiEscapeCodes + +Type: `boolean`\ +Default: `false` + +Whether [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) should be counted. + +## Related + +- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module +- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string +- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string +- [get-east-asian-width](https://github.com/sindresorhus/get-east-asian-width) - Determine the East Asian Width of a Unicode character diff --git a/node_modules/string.prototype.matchall/.editorconfig b/node_modules/string.prototype.matchall/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..bc228f8269443bf772b437890dde7756a3e8a894 --- /dev/null +++ b/node_modules/string.prototype.matchall/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/string.prototype.matchall/.eslintrc b/node_modules/string.prototype.matchall/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..0a87f1e5bab53c6a14f7f10276f2e1e9baffc651 --- /dev/null +++ b/node_modules/string.prototype.matchall/.eslintrc @@ -0,0 +1,49 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 12], + "func-name-matching": 0, + "id-length": 0, + "max-nested-callbacks": [2, 3], + "max-params": [2, 4], + "max-statements-per-line": [2, { "max": 2 }], + "max-statements": [2, 24], + "new-cap": [2, { + "capIsNewExceptions": [ + "AdvanceStringIndex", + "Call", + "Construct", + "CreateIterResultObject", + "CreateRegExpStringIterator", + "Get", + "GetIntrinsic", + "GetMethod", + "Invoke", + "IsRegExp", + "OrdinaryObjectCreate", + "RegExpExec", + "RequireObjectCoercible", + "Set", + "SpeciesConstructor", + "ToBoolean", + "ToLength", + "ToString", + "Type", + ], + }], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"], + }, + + "overrides": [ + { + "files": "test/**", + "extends": "@ljharb/eslint-config/tests", + "rules": { + "max-lines-per-function": 0, + }, + }, + ], +} diff --git a/node_modules/string.prototype.matchall/.github/FUNDING.yml b/node_modules/string.prototype.matchall/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..48a1cbc59280a37e13ec6b30c3882bc01df822d4 --- /dev/null +++ b/node_modules/string.prototype.matchall/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/string.prototype.matchall +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/string.prototype.matchall/.nycrc b/node_modules/string.prototype.matchall/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/string.prototype.matchall/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/string.prototype.matchall/CHANGELOG.md b/node_modules/string.prototype.matchall/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..9042104a927d5a25f2f9a22272c40cc492a643d3 --- /dev/null +++ b/node_modules/string.prototype.matchall/CHANGELOG.md @@ -0,0 +1,178 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v4.0.12](https://github.com/ljharb/String.prototype.matchAll/compare/v4.0.11...v4.0.12) - 2024-12-19 + +### Commits + +- [actions] split out node 10-20, and 20+ [`ec6bcb6`](https://github.com/ljharb/String.prototype.matchAll/commit/ec6bcb6ff1af451de6ca7fddafe789ba7d2deeff) +- [Deps] update `call-bind`, `es-abstract`, `get-intrinsic`, `gopd`, `has-symbols`, `internal-slot`, `regexp.prototype.flags`, `side-channel` [`993a80c`](https://github.com/ljharb/String.prototype.matchAll/commit/993a80c0acdcf2a1ca0035801ee81ce05db226d7) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `auto-changelog`, `mock-property`, `object-inspect`, `object.assign`, `tape` [`50e0c52`](https://github.com/ljharb/String.prototype.matchAll/commit/50e0c527292947681df9e876c7aa456a840e9a76) +- [Refactor] use `call-bound` directly [`72c0fe1`](https://github.com/ljharb/String.prototype.matchAll/commit/72c0fe1964d3c26d63d2e5c0cfd27596bf44823d) +- [Tests] replace `aud` with `npm audit` [`3a4bccb`](https://github.com/ljharb/String.prototype.matchAll/commit/3a4bccb517c3951016dda3ab645d9a4ccefc2226) +- [readme] remove dead badges [`ae4bdb2`](https://github.com/ljharb/String.prototype.matchAll/commit/ae4bdb291f05e595d6119aa7d78827f6fdff2281) +- [Dev Deps] add missing peer dep [`14ceede`](https://github.com/ljharb/String.prototype.matchAll/commit/14ceedee27fe8346ac1562fe17bcd8d752993c29) + +## [v4.0.11](https://github.com/ljharb/String.prototype.matchAll/compare/v4.0.10...v4.0.11) - 2024-03-19 + +### Commits + +- [Deps] update `call-bind`, `define-properties`, `es-abstract`, `get-intrinsic`, `internal-slot`, `regexp.prototype.flags`, `set-function-name`, `side-channel` [`628a475`](https://github.com/ljharb/String.prototype.matchAll/commit/628a475a656424c9f2b126e6c4f5a8764de60f31) +- [Dev Deps] update `aud`, `mock-property`, `npmignore`, `object-inspect`, `object.assign`, `object.entries`, `tape` [`21b67f2`](https://github.com/ljharb/String.prototype.matchAll/commit/21b67f259fe1899f1e063d19e6c4da918fbd35df) +- [actions] remove redundant finisher [`27e8b80`](https://github.com/ljharb/String.prototype.matchAll/commit/27e8b801c80ded69384102bb61c604a128d42e57) +- [Robustness] better cache original RegExp [`92e9c59`](https://github.com/ljharb/String.prototype.matchAll/commit/92e9c597e3c80aae4ed5e34b4de988b6df015b83) +- [Robustness] use `es-errors` [`f6de643`](https://github.com/ljharb/String.prototype.matchAll/commit/f6de6430a9a04d41e4bec86f2d57281c4b9daa41) +- [Refactor] use `gopd` [`965a357`](https://github.com/ljharb/String.prototype.matchAll/commit/965a357a8f6ab24b81da5a7e949b643c788daf15) +- [Refactor] use `es-object-atoms` where possible [`1d15123`](https://github.com/ljharb/String.prototype.matchAll/commit/1d1512306e4a7ea58c5f696666b368bb86eb7c5c) +- [meta] add missing `engines.node` [`04bdb31`](https://github.com/ljharb/String.prototype.matchAll/commit/04bdb31ecdcbf45851d607f4ab3f152c7cc2951e) + +## [v4.0.10](https://github.com/ljharb/String.prototype.matchAll/compare/v4.0.9...v4.0.10) - 2023-09-12 + +### Commits + +- [Refactor] use `set-function-name` [`a851cbb`](https://github.com/ljharb/String.prototype.matchAll/commit/a851cbb5f2ca6708adf4ad90526c70e7d4b34390) + +## [v4.0.9](https://github.com/ljharb/String.prototype.matchAll/compare/v4.0.8...v4.0.9) - 2023-08-28 + +### Commits + +- [Deps] update `define-properties`, `es-abstract`, `get-intrinsic`, `internal-slot`, `regexp.prototype.flags` [`819a5dd`](https://github.com/ljharb/String.prototype.matchAll/commit/819a5ddcef535b27ad76b817a58ff96847f5585b) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `es6-shim`, `object-inspect`, `object.entries`, `tape` [`6f479ee`](https://github.com/ljharb/String.prototype.matchAll/commit/6f479ee4e4263e7ce9932cfcc24be5707dcf0edc) + +## [v4.0.8](https://github.com/ljharb/String.prototype.matchAll/compare/v4.0.7...v4.0.8) - 2022-11-07 + +### Commits + +- [meta] use `npmignore` to autogenerate an npmignore file [`a08a8a1`](https://github.com/ljharb/String.prototype.matchAll/commit/a08a8a17c73814580b26775f7d11dd184abfe00b) +- [Deps] update `define-properties`, `es-abstract`, `get-intrinsic`, `regexp.prototype.flags` [`6273f0f`](https://github.com/ljharb/String.prototype.matchAll/commit/6273f0fd008727933e347789ff8f618036bb2297) +- [Tests] use `mock-property` [`94e83a3`](https://github.com/ljharb/String.prototype.matchAll/commit/94e83a37cd89898a2426f7b028280e6823e9d4a4) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `es5-shim`, `functions-have-names`, `object-inspect`, `object.assign`, `object.entries`, `tape` [`8024497`](https://github.com/ljharb/String.prototype.matchAll/commit/8024497753c39a832f1febc5b91b845d06ca32a7) +- [actions] update rebase action to use reusable workflow [`028abc0`](https://github.com/ljharb/String.prototype.matchAll/commit/028abc0a0f283671072515feaaa98bd3372e84b3) +- [Tests] use `for-each` instead of `foreach` [`f68b771`](https://github.com/ljharb/String.prototype.matchAll/commit/f68b771da3f9f4c759d12322e5e2ce76b4de2c0e) + +## [v4.0.7](https://github.com/ljharb/String.prototype.matchAll/compare/v4.0.6...v4.0.7) - 2022-03-18 + +### Commits + +- [actions] reuse common workflows [`798d359`](https://github.com/ljharb/String.prototype.matchAll/commit/798d359ac36a7543ab4cb4b14f7544b7687d6a9b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `es5-shim`, `object-inspect`, `tape` [`8733fa4`](https://github.com/ljharb/String.prototype.matchAll/commit/8733fa45b7bf5115cb08ba6d4866b14f6b637919) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `safe-publish-latest`, `tape` [`2f0ac7d`](https://github.com/ljharb/String.prototype.matchAll/commit/2f0ac7de6a6b585f1bd6a32c0426d27926366334) +- [actions] update codecov uploader [`40ea9ce`](https://github.com/ljharb/String.prototype.matchAll/commit/40ea9ce1b5a4f8bfbe5637e4edb63e693ff78020) +- [Robustness] use call-bound `indexOf` [`b035fdc`](https://github.com/ljharb/String.prototype.matchAll/commit/b035fdcd6b65263b41ad24786cde4217083c13db) +- [Deps] update `has-symbols`, `regexp.prototype.flags` [`95768f2`](https://github.com/ljharb/String.prototype.matchAll/commit/95768f258a8d30630f56ec862b2e356c980f57c6) + +## [v4.0.6](https://github.com/ljharb/String.prototype.matchAll/compare/v4.0.5...v4.0.6) - 2021-10-04 + +### Commits + +- [Refactor] use `CreateRegExpStringIterator` from `es-abstract` [`5c2cf33`](https://github.com/ljharb/String.prototype.matchAll/commit/5c2cf338f3568d696c978f9e1e51903d229b5fef) +- [patch] remove unused helpers [`280f47e`](https://github.com/ljharb/String.prototype.matchAll/commit/280f47ee3a36e7830e37192b8c6a958026f779f6) +- [meta] add `auto-changelog` [`2d26eda`](https://github.com/ljharb/String.prototype.matchAll/commit/2d26eda3a451cd42a4fea8028f1fb237f330bcee) +- [Deps] update `es-abstract` [`857c8b0`](https://github.com/ljharb/String.prototype.matchAll/commit/857c8b032e6e9cde53af54aec7d91d75cb0cd262) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `es5-shim`, `object-inspect`, `object.entries`, `tape` [`9349ea2`](https://github.com/ljharb/String.prototype.matchAll/commit/9349ea2382066187aae146a2c1cf456c5473cf32) + +## [v4.0.5](https://github.com/ljharb/String.prototype.matchAll/compare/v4.0.4...v4.0.5) - 2021-05-25 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`a6a7af2`](https://github.com/ljharb/String.prototype.matchAll/commit/a6a7af2304add692d429a8a5a4f44914d5b4a9b6) +- [readme] update badges, spec year [`9532ccc`](https://github.com/ljharb/String.prototype.matchAll/commit/9532ccc593cd686232717287b94be9abf497198f) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `object-inspect` [`8ea3e71`](https://github.com/ljharb/String.prototype.matchAll/commit/8ea3e71d40716fa857743a315df243270e53a49e) +- [Deps] update `es-abstract`, `has-symbols` [`e906e75`](https://github.com/ljharb/String.prototype.matchAll/commit/e906e7583b3f1e4efc3fc1f87fb0bd5742191a5e) +- [Dev Deps] update `eslint`, `tape` [`fcf2270`](https://github.com/ljharb/String.prototype.matchAll/commit/fcf227050a83bac350c7e451f57151da80783523) +- [actions] update workflows [`ba642c5`](https://github.com/ljharb/String.prototype.matchAll/commit/ba642c573af408f6106666d9a3f9261b1c99b505) +- [Refactor] use `get-intrinsic` directly [`fca987f`](https://github.com/ljharb/String.prototype.matchAll/commit/fca987f8b1abd375d752d081ee4516a6b8f6c912) +- [meta] use `prepublishOnly` script for npm 7+ [`4c5ba45`](https://github.com/ljharb/String.prototype.matchAll/commit/4c5ba452acf2ae5af9792a58f01e7cb9b839a5c3) +- [Deps] update `es-abstract` [`39d34df`](https://github.com/ljharb/String.prototype.matchAll/commit/39d34df9a615fe723411dd3fc91be49be6521ef1) + + + +4.0.4 / 2021-02-21 +================== + * [readme] fix repo URLs; remove travis badge + * [meta] gitignore coverage output + * [Deps] update `call-bind`, `es-abstract`, `internal-slot`, `regexp.prototype.flags`, `side-channel` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es5-shim`, `functions-have-names`, `object-inspect`, `object.entries`, `tape` + * [Tests] increase coverage + * [actions] update workflows + +4.0.3 / 2020-11-19 +================== + * [meta] do not publish github action workflow files + * [Deps] update `es-abstract`, `side-channel`; use `call-bind` where applicable; remove `function-bind` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `es5-shim`, `es6-shim`, `functions-have-names`, `object-inspect`, `object.assign`, `object.entries`, `tape` + * [actions] add "Allow Edits" workflow + * [actions] switch Automatic Rebase workflow to `pull_request_target` event + * [Tests] migrate tests to Github Actions + * [Tests] run `nyc` on all tests + * [Tests] run `es-shim-api` in postlint; use `tape` runner + * [Tests] only audit prod deps + +4.0.2 / 2019-12-22 +================== + * [Refactor] use `internal-slot` + * [Refactor] use `side-channel` instead of "hidden" helper + * [Deps] update `es-abstract`, `internal-slot`, `regexp.prototype.flags`, `side-channel` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` + +4.0.1 / 2019-12-13 +================== + * [Refactor] use split-up `es-abstract` (61% bundle size decrease) + * [Fix] fix error message: matchAll requires *global* + * [Deps] update `es-abstract`, `has-symbols` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `functions-have-names`, `object-inspect`, `evalmd`, `object.entries`; add `safe-publish-latest` + * [meta] add `funding` field + * [Tests] use shared travis-ci configs + * [actions] add automatic rebasing / merge commit blocking + +4.0.0 / 2019-10-03 +================== + * [Breaking] throw on non-global/nullish flags + * [Deps] update `es-abstract` + +3.0.2 / 2019-10-02 +================== + * [Fix] ensure that `flagsGetter` is only used when there is no `flags` property on the regex + * [Fix] `RegExp.prototype[Symbol.matchAll]`: ToString the `flags` property + * [Refactor] provide a consistent way to determine the polyfill for `RegExp.prototype[Symbol.matchAll]` + * [meta] create FUNDING.yml + * [Deps] update `es-abstract` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `evalmd`, `functions-have-names`, `es5-shim`, `es6-shim`, `object.entries`, `tape` + * [Tests] up to `node` `v12.11`, `v11.15`, `v10.16`, `v8.16`, `v6.17` + * [Tests] use `functions-have-names` + * [Tests] bump audit level, due to https://github.com/reggi/evalmd/issues/13 + * [Tests] use `npx aud` instead of `npm audit` with hoops + +3.0.1 / 2018-12-11 +================== + * [Fix] update spec to follow committee feedback + * [Deps] update `define-properties` + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `es5-shim`, `es6-shim`, `tape` + * [Tests] use `npm audit` instead of `nsp` + * [Tests] up to `node` `v11.4`, `v10.14`, `v8.14`, `v6.15` + +3.0.0 / 2018-05-31 +================== + * [Breaking] update to match latest spec + * [Deps] update `es-abstract` + * [Dev Deps] update `eslint`, `nsp`, `object-inspect`, `tape` + * [Tests] up to `node` `v10.3`, `v9.11`, `v8.11`, `v6.14`, `v4.9` + * [Tests] regexes now have a "groups" property in ES2018 + * [Tests] run evalmd in prelint + +2.0.0 / 2018-01-24 +================== + * [Breaking] change to handle nonmatching regexes + * [Breaking] non-regex arguments that are thus coerced to RegExp now get the global flag + * [Deps] update `es-abstract`, `regexp.prototype.flags` + * [Dev Deps] update `es5-shim`, `eslint`, `object.assign` + * [Tests] up to `node` `v9.4`, `v8.9`, `v6.12`; pin included builds to LTS + * [Tests] improve and correct tests and failure messages + +1.0.0 / 2017-09-28 +================== + * Initial release diff --git a/node_modules/string.prototype.matchall/LICENSE b/node_modules/string.prototype.matchall/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b43df444e518288ceef6eaa9badd33388191b1d3 --- /dev/null +++ b/node_modules/string.prototype.matchall/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +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. + diff --git a/node_modules/string.prototype.matchall/README.md b/node_modules/string.prototype.matchall/README.md new file mode 100644 index 0000000000000000000000000000000000000000..020cf5ccdd726c96e6481d75026077ad93b71ca4 --- /dev/null +++ b/node_modules/string.prototype.matchall/README.md @@ -0,0 +1,73 @@ +# string.prototype.matchall [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +ES2020 spec-compliant shim for String.prototype.matchAll. Invoke its "shim" method to shim `String.prototype.matchAll` if it is unavailable or noncompliant. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment, and complies with the [spec](https://tc39.es/ecma262/#sec-string.prototype.matchall). + +Most common usage: +```js +const assert = require('assert'); +const matchAll = require('string.prototype.matchall'); + +const str = 'aabc'; +const nonRegexStr = 'ab'; +const globalRegex = /[ac]/g; +const nonGlobalRegex = /[bc]/i; + +// non-regex arguments are coerced into a global regex +assert.deepEqual( + [...matchAll(str, nonRegexStr)], + [...matchAll(str, new RegExp(nonRegexStr, 'g'))] +); + +assert.deepEqual([...matchAll(str, globalRegex)], [ + Object.assign(['a'], { index: 0, input: str, groups: undefined }), + Object.assign(['a'], { index: 1, input: str, groups: undefined }), + Object.assign(['c'], { index: 3, input: str, groups: undefined }), +]); + +assert.throws(() => matchAll(str, nonGlobalRegex)); // non-global regexes throw + +matchAll.shim(); // will be a no-op if not needed + +// non-regex arguments are coerced into a global regex +assert.deepEqual( + [...str.matchAll(nonRegexStr)], + [...str.matchAll(new RegExp(nonRegexStr, 'g'))] +); + +assert.deepEqual([...str.matchAll(globalRegex)], [ + Object.assign(['a'], { index: 0, input: str, groups: undefined }), + Object.assign(['a'], { index: 1, input: str, groups: undefined }), + Object.assign(['c'], { index: 3, input: str, groups: undefined }), +]); + +assert.throws(() => matchAll(str, nonGlobalRegex)); // non-global regexes throw + +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/string.prototype.matchall +[npm-version-svg]: https://versionbadg.es/es-shims/String.prototype.matchAll.svg +[deps-svg]: https://david-dm.org/es-shims/String.prototype.matchAll.svg +[deps-url]: https://david-dm.org/es-shims/String.prototype.matchAll +[dev-deps-svg]: https://david-dm.org/es-shims/String.prototype.matchAll/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/String.prototype.matchAll#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/string.prototype.matchall.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/string.prototype.matchall.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/string.prototype.matchall.svg +[downloads-url]: https://npm-stat.com/charts.html?package=string.prototype.matchall +[codecov-image]: https://codecov.io/gh/es-shims/String.prototype.matchAll/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/String.prototype.matchAll/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/String.prototype.matchAll +[actions-url]: https://github.com/es-shims/String.prototype.matchAll/actions diff --git a/node_modules/string.prototype.matchall/auto.js b/node_modules/string.prototype.matchall/auto.js new file mode 100644 index 0000000000000000000000000000000000000000..8ebf606cb02ff3a8c6ef786afa37d21a19254f46 --- /dev/null +++ b/node_modules/string.prototype.matchall/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/string.prototype.matchall/implementation.js b/node_modules/string.prototype.matchall/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..818d8c5611a15d58810f2e5ffe28fe9bba6612f4 --- /dev/null +++ b/node_modules/string.prototype.matchall/implementation.js @@ -0,0 +1,59 @@ +'use strict'; + +var Call = require('es-abstract/2024/Call'); +var Get = require('es-abstract/2024/Get'); +var GetMethod = require('es-abstract/2024/GetMethod'); +var IsRegExp = require('es-abstract/2024/IsRegExp'); +var ToString = require('es-abstract/2024/ToString'); +var RequireObjectCoercible = require('es-object-atoms/RequireObjectCoercible'); +var callBound = require('call-bound'); +var hasSymbols = require('has-symbols')(); +var flagsGetter = require('regexp.prototype.flags'); +var GetIntrinsic = require('get-intrinsic'); +var $TypeError = require('es-errors/type'); + +var $RegExp = GetIntrinsic('%RegExp%'); +var $indexOf = callBound('String.prototype.indexOf'); + +var regexpMatchAllPolyfill = require('./polyfill-regexp-matchall'); + +var getMatcher = function getMatcher(regexp) { // eslint-disable-line consistent-return + var matcherPolyfill = regexpMatchAllPolyfill(); + if (hasSymbols && typeof Symbol.matchAll === 'symbol') { + var matcher = GetMethod(regexp, Symbol.matchAll); + if (matcher === $RegExp.prototype[Symbol.matchAll] && matcher !== matcherPolyfill) { + return matcherPolyfill; + } + return matcher; + } + // fallback for pre-Symbol.matchAll environments + if (IsRegExp(regexp)) { + return matcherPolyfill; + } +}; + +module.exports = function matchAll(regexp) { + var O = RequireObjectCoercible(this); + + if (typeof regexp !== 'undefined' && regexp !== null) { + var isRegExp = IsRegExp(regexp); + if (isRegExp) { + // workaround for older engines that lack RegExp.prototype.flags + var flags = 'flags' in regexp ? Get(regexp, 'flags') : flagsGetter(regexp); + RequireObjectCoercible(flags); + if ($indexOf(ToString(flags), 'g') < 0) { + throw new $TypeError('matchAll requires a global regular expression'); + } + } + + var matcher = getMatcher(regexp); + if (typeof matcher !== 'undefined') { + return Call(matcher, regexp, [O]); + } + } + + var S = ToString(O); + // var rx = RegExpCreate(regexp, 'g'); + var rx = new $RegExp(regexp, 'g'); + return Call(getMatcher(rx), rx, [S]); +}; diff --git a/node_modules/string.prototype.matchall/index.js b/node_modules/string.prototype.matchall/index.js new file mode 100644 index 0000000000000000000000000000000000000000..8532354d2a78f6e4f98566c7707fca202c17ed85 --- /dev/null +++ b/node_modules/string.prototype.matchall/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var callBind = require('call-bind'); +var define = require('define-properties'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var boundMatchAll = callBind(implementation); + +define(boundMatchAll, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = boundMatchAll; diff --git a/node_modules/string.prototype.matchall/package.json b/node_modules/string.prototype.matchall/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d27ad4169c444caca34687a361075f74fcc7bd25 --- /dev/null +++ b/node_modules/string.prototype.matchall/package.json @@ -0,0 +1,98 @@ +{ + "name": "string.prototype.matchall", + "version": "4.0.12", + "description": "Spec-compliant polyfill for String.prototype.matchAll", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "tests-only": "nyc tape 'test/**/*.js'", + "prelint": "evalmd *.md", + "lint": "eslint .", + "postlint": "es-shim-api --bound", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/es-shims/String.prototype.matchAll.git" + }, + "keywords": [ + "ES2020", + "ES", + "String.prototype.matchAll", + "matchAll", + "match", + "regex", + "regexp", + "regular", + "expression", + "matches" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/es-shims/String.prototype.matchAll/issues" + }, + "homepage": "https://github.com/es-shims/String.prototype.matchAll#readme", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.6", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.6", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "internal-slot": "^1.1.0", + "regexp.prototype.flags": "^1.5.3", + "set-function-name": "^2.0.2", + "side-channel": "^1.1.0" + }, + "devDependencies": { + "@es-shims/api": "^2.5.1", + "@ljharb/eslint-config": "^21.1.1", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "es5-shim": "^4.6.7", + "es6-shim": "^0.35.8", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "for-each": "^0.3.3", + "functions-have-names": "^1.2.3", + "in-publish": "^2.0.1", + "mock-property": "^1.1.0", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "object-inspect": "^1.13.3", + "object.assign": "^4.1.7", + "object.entries": "^1.1.8", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true, + "startingVersion": "v4.0.5" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/string.prototype.matchall/polyfill-regexp-matchall.js b/node_modules/string.prototype.matchall/polyfill-regexp-matchall.js new file mode 100644 index 0000000000000000000000000000000000000000..6c39bafad9ec05fbe243070a0c1c0f05cab343cf --- /dev/null +++ b/node_modules/string.prototype.matchall/polyfill-regexp-matchall.js @@ -0,0 +1,11 @@ +'use strict'; + +var hasSymbols = require('has-symbols')(); +var regexpMatchAll = require('./regexp-matchall'); + +module.exports = function getRegExpMatchAllPolyfill() { + if (!hasSymbols || typeof Symbol.matchAll !== 'symbol' || typeof RegExp.prototype[Symbol.matchAll] !== 'function') { + return regexpMatchAll; + } + return RegExp.prototype[Symbol.matchAll]; +}; diff --git a/node_modules/string.prototype.matchall/polyfill.js b/node_modules/string.prototype.matchall/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..c9e0df4ad5c16c5849a680435d4cbb23dc518c9a --- /dev/null +++ b/node_modules/string.prototype.matchall/polyfill.js @@ -0,0 +1,14 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = function getPolyfill() { + if (String.prototype.matchAll) { + try { + ''.matchAll(RegExp.prototype); + } catch (e) { + return String.prototype.matchAll; + } + } + return implementation; +}; diff --git a/node_modules/string.prototype.matchall/regexp-matchall.js b/node_modules/string.prototype.matchall/regexp-matchall.js new file mode 100644 index 0000000000000000000000000000000000000000..37c1ba0d3a702e6bd2ae2ff3966a7600d7869d3a --- /dev/null +++ b/node_modules/string.prototype.matchall/regexp-matchall.js @@ -0,0 +1,59 @@ +'use strict'; + +// var Construct = require('es-abstract/2024/Construct'); +var CreateRegExpStringIterator = require('es-abstract/2024/CreateRegExpStringIterator'); +var Get = require('es-abstract/2024/Get'); +var Set = require('es-abstract/2024/Set'); +var SpeciesConstructor = require('es-abstract/2024/SpeciesConstructor'); +var ToLength = require('es-abstract/2024/ToLength'); +var ToString = require('es-abstract/2024/ToString'); +var Type = require('es-abstract/2024/Type'); +var flagsGetter = require('regexp.prototype.flags'); +var setFunctionName = require('set-function-name'); +var callBound = require('call-bound'); +var GetIntrinsic = require('get-intrinsic'); +var $TypeError = require('es-errors/type'); + +var $indexOf = callBound('String.prototype.indexOf'); + +var OrigRegExp = GetIntrinsic('%RegExp%'); + +var supportsConstructingWithFlags = 'flags' in OrigRegExp.prototype; + +var constructRegexWithFlags = function constructRegex(C, R) { + var matcher; + // workaround for older engines that lack RegExp.prototype.flags + var flags = 'flags' in R ? Get(R, 'flags') : ToString(flagsGetter(R)); + if (supportsConstructingWithFlags && typeof flags === 'string') { + matcher = new C(R, flags); + } else if (C === OrigRegExp) { + // workaround for older engines that can not construct a RegExp with flags + matcher = new C(R.source, flags); + } else { + matcher = new C(R, flags); + } + return { flags: flags, matcher: matcher }; +}; + +var regexMatchAll = setFunctionName(function SymbolMatchAll(string) { + var R = this; + if (Type(R) !== 'Object') { + throw new $TypeError('"this" value must be an Object'); + } + var S = ToString(string); + var C = SpeciesConstructor(R, OrigRegExp); + + var tmp = constructRegexWithFlags(C, R); + // var flags = ToString(Get(R, 'flags')); + var flags = tmp.flags; + // var matcher = Construct(C, [R, flags]); + var matcher = tmp.matcher; + + var lastIndex = ToLength(Get(R, 'lastIndex')); + Set(matcher, 'lastIndex', lastIndex, true); + var global = $indexOf(flags, 'g') > -1; + var fullUnicode = $indexOf(flags, 'u') > -1; + return CreateRegExpStringIterator(matcher, S, global, fullUnicode); +}, '[Symbol.matchAll]', true); + +module.exports = regexMatchAll; diff --git a/node_modules/string.prototype.matchall/shim.js b/node_modules/string.prototype.matchall/shim.js new file mode 100644 index 0000000000000000000000000000000000000000..0e4395db8c58697fd0df2c96a0051576b0b0a5ba --- /dev/null +++ b/node_modules/string.prototype.matchall/shim.js @@ -0,0 +1,50 @@ +'use strict'; + +var define = require('define-properties'); +var hasSymbols = require('has-symbols')(); +var gOPD = require('gopd'); + +var getPolyfill = require('./polyfill'); +var regexpMatchAllPolyfill = require('./polyfill-regexp-matchall'); + +var defineP = Object.defineProperty; + +module.exports = function shimMatchAll() { + var polyfill = getPolyfill(); + define( + String.prototype, + { matchAll: polyfill }, + { matchAll: function () { return String.prototype.matchAll !== polyfill; } } + ); + if (hasSymbols) { + // eslint-disable-next-line no-restricted-properties + var symbol = Symbol.matchAll || (Symbol['for'] ? Symbol['for']('Symbol.matchAll') : Symbol('Symbol.matchAll')); + define( + Symbol, + { matchAll: symbol }, + { matchAll: function () { return Symbol.matchAll !== symbol; } } + ); + + if (defineP && gOPD) { + var desc = gOPD(Symbol, symbol); + if (!desc || desc.configurable) { + defineP(Symbol, symbol, { + configurable: false, + enumerable: false, + value: symbol, + writable: false + }); + } + } + + var regexpMatchAll = regexpMatchAllPolyfill(); + var func = {}; + func[symbol] = regexpMatchAll; + var predicate = {}; + predicate[symbol] = function () { + return RegExp.prototype[symbol] !== regexpMatchAll; + }; + define(RegExp.prototype, func, predicate); + } + return polyfill; +}; diff --git a/node_modules/string.prototype.matchall/test/index.js b/node_modules/string.prototype.matchall/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..86daec8968906bf8dcfedfb0f8a5881aadfdd0b0 --- /dev/null +++ b/node_modules/string.prototype.matchall/test/index.js @@ -0,0 +1,13 @@ +'use strict'; + +var matchAllShim = require('../'); +var regexMatchAll = require('../regexp-matchall'); +var test = require('tape'); + +var runTests = require('./tests'); + +test('as a function', function (t) { + runTests(matchAllShim, regexMatchAll, t); + + t.end(); +}); diff --git a/node_modules/string.prototype.matchall/test/shimmed.js b/node_modules/string.prototype.matchall/test/shimmed.js new file mode 100644 index 0000000000000000000000000000000000000000..da2b0a5842f44cefb3091eb75b5e14c8f420b65f --- /dev/null +++ b/node_modules/string.prototype.matchall/test/shimmed.js @@ -0,0 +1,71 @@ +'use strict'; + +require('es5-shim'); +require('es6-shim'); +require('../auto'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); +var hasSymbols = require('has-symbols')(); +var mockProperty = require('mock-property'); + +var regexMatchAll = require('../regexp-matchall'); + +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); +var functionNamesConfigurable = require('functions-have-names').functionsHaveConfigurableNames(); + +var runTests = require('./tests'); + +test('shimmed', function (t) { + t.equal(String.prototype.matchAll.length, 1, 'String#matchAll has a length of 1'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(String.prototype.matchAll.name, 'matchAll', 'String#matchAll has name "matchAll"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(String.prototype, 'matchAll'), 'String#matchAll is not enumerable'); + et.end(); + }); + + t.test('Symbol.matchAll', { skip: !hasSymbols }, function (st) { + st.equal(typeof Symbol.matchAll, 'symbol', 'Symbol.matchAll is a symbol'); + + st.equal(typeof RegExp.prototype[Symbol.matchAll], 'function', 'Symbol.matchAll function is on RegExp.prototype'); + + st.test('Function name', { skip: !functionsHaveNames }, function (s2t) { + if (functionNamesConfigurable) { + s2t.equal(RegExp.prototype[Symbol.matchAll].name, '[Symbol.matchAll]', 'RegExp.prototype[Symbol.matchAll] has name "[Symbol.matchAll]"'); + } else { + s2t.equal(RegExp.prototype[Symbol.matchAll].name, 'SymbolMatchAll', 'RegExp.prototype[Symbol.matchAll] has best guess name "SymbolMatchAll"'); + } + s2t.end(); + }); + + st.test('no symbol present', function (s2t) { + s2t.doesNotThrow(function () { 'abc'.matchAll('b'); }, 'does not throw on string input, with the symbol on regex prototype'); + + s2t.teardown(mockProperty(RegExp.prototype, Symbol.matchAll, { + nonEnumerable: true, + value: undefined, + nonWritable: false + })); + + s2t['throws'](function () { 'abc'.matchAll('b'); }, 'throws on string input, without the symbol on regex prototype'); + + s2t.end(); + }); + + st.end(); + }); + + runTests( + callBind(String.prototype.matchAll), + callBind(hasSymbols ? RegExp.prototype[Symbol.matchAll] : regexMatchAll), + t + ); + + t.end(); +}); diff --git a/node_modules/string.prototype.matchall/test/tests.js b/node_modules/string.prototype.matchall/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..484ceebab13b7192dfe787ceceedfdc1e1c1e73d --- /dev/null +++ b/node_modules/string.prototype.matchall/test/tests.js @@ -0,0 +1,247 @@ +'use strict'; + +var forEach = require('for-each'); +var has = Object.prototype.hasOwnProperty; +var assign = require('object.assign'); +var define = require('define-properties'); +var entries = require('object.entries'); +var inspect = require('object-inspect'); + +var hasSticky = typeof (/a/).sticky === 'boolean'; +var hasGroups = 'groups' in (/a/).exec('a'); + +var groups = function groups(matchObject) { + return hasGroups ? assign(matchObject, { groups: matchObject.groups }, matchObject) : matchObject; +}; + +var arraySpread = function arraySpread(iterator) { + if (Array.isArray(iterator)) { return iterator; } + var result; + var values = []; + do { + result = iterator.next(); + values.push(result); + } while (!result.done); + return values; +}; + +var testResults = function (t, iterator, expectedResults, item) { + var prefix = arguments.length > 3 ? inspect(item) + ': ' : ''; + var results = arraySpread(iterator); + var expecteds = arraySpread(expectedResults); + t.test(prefix + 'actual vs expected result lengths', function (st) { + st.equal(results.length, expecteds.length, 'actual and expected result counts are the same'); + st.end(); + }); + t.test(prefix + 'actual vs expected results', { skip: results.length !== expecteds.length }, function (st) { + forEach(expecteds, function (expected, index) { + var result = results.shift(); + st.equal(result.done, expected.done, 'result ' + (index + 1) + ' is ' + (expected.done ? '' : 'not ') + 'done'); + st.test('result ' + (index + 1), { skip: result.done !== expected.done }, function (s2t) { + if (expected.done) { + s2t.equal(result.value, undefined, 'result ' + (index + 1) + ' value is undefined'); + } else { + s2t.equal(Array.isArray(result.value), true, 'result ' + (index + 1) + ' value is an array'); + s2t.deepEqual(entries(result.value || {}), entries(expected.value || {}), 'result ' + (index + 1) + ' has the same entries'); + s2t.deepEqual(result.value, expected.value, 'result ' + (index + 1) + ' value is expected value'); + } + s2t.end(); + }); + }); + }); +}; + +module.exports = function (matchAll, regexMatchAll, t) { + t.test('non-regexes', function (st) { + var notRegexes = [ + [null, [{ value: undefined, done: true }]], + [undefined, [ + { value: assign([''], groups({ index: 0, input: 'abc' })), done: false }, + { value: assign([''], groups({ index: 1, input: 'abc' })), done: false }, + { value: assign([''], groups({ index: 2, input: 'abc' })), done: false }, + { value: assign([''], groups({ index: 3, input: 'abc' })), done: false }, + { value: undefined, done: true } + ]], + [NaN, [{ value: undefined, done: true }]], + [42, [{ value: undefined, done: true }]], + [new Date(), [{ value: undefined, done: true }]], + [{}, [ + { value: assign(['b'], groups({ index: 1, input: 'abc' })), done: false }, + { value: assign(['c'], groups({ index: 2, input: 'abc' })), done: false }, + { value: undefined, done: true } + ]], + [[], [ + { value: assign([''], groups({ index: 0, input: 'abc' })), done: false }, + { value: assign([''], groups({ index: 1, input: 'abc' })), done: false }, + { value: assign([''], groups({ index: 2, input: 'abc' })), done: false }, + { value: assign([''], groups({ index: 3, input: 'abc' })), done: false }, + { value: undefined, done: true } + ]] + ]; + var str = 'abc'; + forEach(notRegexes, function (notRegex) { + testResults(st, matchAll(str, notRegex[0]), notRegex[1], notRegex[0]); + }); + st.end(); + }); + + t.test('passing a string instead of a regex', function (st) { + var str = 'aabcaba'; + testResults(st, matchAll(str, 'a'), matchAll(str, /a/g)); + st.end(); + }); + + t.test('ToString-able objects', function (st) { + var str = 'aabc'; + var strObj = { toString: function () { return str; } }; + var regex = /[ac]/g; + var expectedResults = [ + { value: assign(['a'], groups({ index: 0, input: str })), done: false }, + { value: assign(['a'], groups({ index: 1, input: str })), done: false }, + { value: assign(['c'], groups({ index: 3, input: str })), done: false }, + { value: undefined, done: true } + ]; + testResults(st, matchAll(strObj, regex), expectedResults); + st.end(); + }); + + t.test('#flags', function (st) { + st.test('without a flags property', function (s2t) { + var str = 'aabc'; + var regex = /[ac]/g; + if (define.supportsDescriptors) { + Object.defineProperty(regex, 'flags', { value: undefined }); + } + s2t.equal(regex.flags, undefined, 'regex has an undefined "flags" property'); + s2t['throws']( + function () { matchAll(str, regex); }, + 'undefined flags throws' + ); + s2t.end(); + }); + + st.test('with a static flags property', function (s2t) { + var str = 'AaBC'; + var regex = /[ac]/; + define(regex, { flags: 'ig' }, { flags: function () { return true; } }); + try { + define(regex, { global: true }, { global: function () { return true; } }); + s2t.equal(regex.global, true); + } catch (e) { + s2t.comment('# SKIP in node < 6, `global` is not configurable on regexes'); + return s2t.end(); + } + s2t.equal(regex.flags, 'ig'); + var expectedResults = [ + { value: assign(['A'], groups({ index: 0, input: str })), done: false }, + { value: assign(['a'], groups({ index: 1, input: str })), done: false }, + { value: assign(['C'], groups({ index: 3, input: str })), done: false }, + { value: undefined, done: true } + ]; + testResults(s2t, matchAll(str, regex), expectedResults); + return s2t.end(); + }); + + st.test('respects flags', function (s2t) { + var str = 'A\na\nb\nC'; + var regex = /^[ac]/img; + var expectedResults = [ + { value: assign(['A'], groups({ index: 0, input: str })), done: false }, + { value: assign(['a'], groups({ index: 2, input: str })), done: false }, + { value: assign(['C'], groups({ index: 6, input: str })), done: false }, + { value: undefined, done: true } + ]; + testResults(s2t, matchAll(str, regex), expectedResults); + s2t.end(); + }); + + st.test('throws with a non-global regex', function (s2t) { + var str = 'AaBbCc'; + var regex = /[bc]/i; + s2t['throws']( + function () { matchAll(str, regex); }, + TypeError, + 'a non-global regex throws' + ); + s2t.end(); + }); + + st.test('works with a global non-sticky regex', function (s2t) { + var str = 'AaBbCc'; + var regex = /[bc]/gi; + var expectedResults = [ + { value: assign(['B'], groups({ index: 2, input: str })), done: false }, + { value: assign(['b'], groups({ index: 3, input: str })), done: false }, + { value: assign(['C'], groups({ index: 4, input: str })), done: false }, + { value: assign(['c'], groups({ index: 5, input: str })), done: false }, + { value: undefined, done: true } + ]; + testResults(s2t, matchAll(str, regex), expectedResults); + s2t.end(); + }); + }); + + t.test('returns an iterator', function (st) { + var str = 'aabc'; + var iterator = matchAll(str, /[ac]/g); + st.ok(iterator, 'iterator is truthy'); + st.equal(has.call(iterator, 'next'), false, 'iterator does not have own property "next"'); + for (var key in iterator) { + st.fail('iterator has enumerable properties: ' + key); + } + var expectedResults = [ + { value: assign(['a'], groups({ index: 0, input: str })), done: false }, + { value: assign(['a'], groups({ index: 1, input: str })), done: false }, + { value: assign(['c'], groups({ index: 3, input: str })), done: false }, + { value: undefined, done: true } + ]; + testResults(st, iterator, expectedResults); + st.end(); + }); + + t.test('zero-width matches', function (st) { + var str = 'abcde'; + + st.test('global', function (s2t) { + var expectedResults = [ + { value: assign([''], groups({ index: 1, input: str })), done: false }, + { value: assign([''], groups({ index: 2, input: str })), done: false }, + { value: assign([''], groups({ index: 3, input: str })), done: false }, + { value: assign([''], groups({ index: 4, input: str })), done: false }, + { value: undefined, done: true } + ]; + testResults(s2t, matchAll(str, /\B/g), expectedResults); + s2t.end(); + }); + + st.test('sticky', { skip: !hasSticky }, function (s2t) { + var expectedResults = [ + { value: undefined, done: true } + ]; + + /* eslint no-invalid-regexp: [2, { "allowConstructorFlags": ["y"] }] */ + var regex = new RegExp('\\B', 'y'); + s2t['throws']( + function () { matchAll(str, regex); }, + TypeError, + 'non-global sticky regex throws' + ); + + /* eslint no-invalid-regexp: [2, { "allowConstructorFlags": ["y"] }] */ + testResults(s2t, matchAll(str, new RegExp('\\B', 'gy')), expectedResults); + + s2t.end(); + }); + + st.test('unflagged', function (s2t) { + s2t['throws']( + function () { matchAll(str, /\B/); }, + TypeError, + 'unflagged regex throws' + ); + s2t.end(); + }); + + st.end(); + }); +}; diff --git a/node_modules/string.prototype.trim/.eslintrc b/node_modules/string.prototype.trim/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..2bbc53b115bb16a170207e07e97a4d1a13851c33 --- /dev/null +++ b/node_modules/string.prototype.trim/.eslintrc @@ -0,0 +1,25 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "RequireObjectCoercible", + "ToString", + ], + }], + "no-invalid-this": 1, + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "id-length": 0, + }, + }, + ], +} diff --git a/node_modules/string.prototype.trim/.nycrc b/node_modules/string.prototype.trim/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/string.prototype.trim/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/string.prototype.trim/CHANGELOG.md b/node_modules/string.prototype.trim/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..e8903b4aaea57884321c1759ec981a0ac04bf7de --- /dev/null +++ b/node_modules/string.prototype.trim/CHANGELOG.md @@ -0,0 +1,214 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.11](https://github.com/es-shims/String.prototype.trim/compare/v1.2.10...v1.2.11) - 2026-06-05 + +### Commits + +- [Fix] make right-trim linear for all inputs, not just non-trailing-whitespace [`2c66b5e`](https://github.com/es-shims/String.prototype.trim/commit/2c66b5e9f102e872873877f2bbf1bd3f70a7ad12) +- [Refactor] Handle pathological strings better [`91e5eb6`](https://github.com/es-shims/String.prototype.trim/commit/91e5eb62998a7ea8d4e25c96b55c2dd709a9b21f) +- [actions] update workflows [`09b9c7d`](https://github.com/es-shims/String.prototype.trim/commit/09b9c7d8efbb08607f60fa117671ae9eda45bff8) +- [Dev Deps] update `@ericcornelissen/assert-time`, `@ljharb/eslint-config`, `auto-changelog`, `eslint`, `for-each`, `has-strict-mode`, `npmignore` [`816817a`](https://github.com/es-shims/String.prototype.trim/commit/816817a5aa1bfbc5ec994be5de6ec28cf4efa48b) +- [Deps] update `call-bind`, `call-bound`, `es-abstract`, `es-object-atoms` [`733f19d`](https://github.com/es-shims/String.prototype.trim/commit/733f19d4aa049db208e209e94107a81008bd2e0c) +- [readme] remove dead badges [`738a1e6`](https://github.com/es-shims/String.prototype.trim/commit/738a1e6451b80df057b86de43842bf5407b3ce5b) +- [readme] replace runkit CI badge with shields.io check-runs badge [`3c6a604`](https://github.com/es-shims/String.prototype.trim/commit/3c6a6045bbeb90fb90e41e69c89a5568f39f5418) + +## [v1.2.10](https://github.com/es-shims/String.prototype.trim/compare/v1.2.9...v1.2.10) - 2024-12-11 + +### Commits + +- [actions] split out node 10-20, and 20+ [`335d99a`](https://github.com/es-shims/String.prototype.trim/commit/335d99a408ee623eb60ca53af13da1813d3ee1b8) +- [Refactor] use `define-data-property` and `has-property-descriptors` directly [`2e0c2e9`](https://github.com/es-shims/String.prototype.trim/commit/2e0c2e9979c9368b13a90a31ae79ca8b1f2fa01a) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `auto-changelog`, `tape` [`138d3db`](https://github.com/es-shims/String.prototype.trim/commit/138d3db824e6fed5a0f9c81ae06534ef4e20b969) +- [Deps] update `call-bind`, `es-abstract` [`3a06731`](https://github.com/es-shims/String.prototype.trim/commit/3a0673152cc347f42feed04a6936d824ffb2bb57) +- [Refactor] use `call-bound` directly [`9499206`](https://github.com/es-shims/String.prototype.trim/commit/9499206837e054fac9b48db0f63c09dd1e955e11) +- [Tests] replace `aud` with `npm audit` [`c88a935`](https://github.com/es-shims/String.prototype.trim/commit/c88a935c098d8a9809812af68c1fc51ab65854cb) +- [Dev Deps] add missing dev dep [`9667c7d`](https://github.com/es-shims/String.prototype.trim/commit/9667c7d04de2dff034cde13f41aca9e203947d43) +- [Dev Deps] add missing peer dep [`6417c72`](https://github.com/es-shims/String.prototype.trim/commit/6417c727c94acb568ad4f5b4674996401f5ee531) + +## [v1.2.9](https://github.com/es-shims/String.prototype.trim/compare/v1.2.8...v1.2.9) - 2024-03-16 + +### Commits + +- [Refactor] use `es-object-atoms`; update `call-bind`, `define-properties`, `es-abstract` [`f6fe1af`](https://github.com/es-shims/String.prototype.trim/commit/f6fe1af4cb9381757971b294afc845e3b2e7c1e9) +- [Dev Deps] update `aud`, `npmignore`, `tape` [`d4e2b81`](https://github.com/es-shims/String.prototype.trim/commit/d4e2b81878478d7090826b73d52bc42f117a2189) + +## [v1.2.8](https://github.com/es-shims/String.prototype.trim/compare/v1.2.7...v1.2.8) - 2023-09-07 + +### Commits + +- [Tests] add passing test cases [`2ab172c`](https://github.com/es-shims/String.prototype.trim/commit/2ab172c3ddeec62fb4f6ead3c7e10d24e340ecad) +- [Deps] update `es-abstract` [`8c16598`](https://github.com/es-shims/String.prototype.trim/commit/8c16598aba57e30c5e8446f91fb998a5790c1f81) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `tape` [`2b99fad`](https://github.com/es-shims/String.prototype.trim/commit/2b99fad6f32386b5bf1b304acb0fdd2a73c77a95) +- [Dev Deps] update `@ljharb/eslint-config`, `@ljharb/eslint-config`, `aud`, `tape` [`97be2b5`](https://github.com/es-shims/String.prototype.trim/commit/97be2b55a3902753f50fadc2e9df6b7ff0f0f669) +- [Deps] update `define-properties`, `es-abstract` [`1fdc65f`](https://github.com/es-shims/String.prototype.trim/commit/1fdc65ff4b9c73cc9d132832943a89a57f1f93a5) + +## [v1.2.7](https://github.com/es-shims/String.prototype.trim/compare/v1.2.6...v1.2.7) - 2022-11-07 + +### Commits + +- [meta] use `npmignore` to autogenerate an npmignore file [`3e6de84`](https://github.com/es-shims/String.prototype.trim/commit/3e6de84f959c1ecc44e894aa1a64a8eb5007f3f5) +- [actions] update rebase action to use reusable workflow [`b725a04`](https://github.com/es-shims/String.prototype.trim/commit/b725a0499b832e69dfe5121bb643464a659ba8ff) +- [Deps] update `es-abstract` [`b707a17`](https://github.com/es-shims/String.prototype.trim/commit/b707a1747363f361665c50eda5eb952a86755e8c) +- [Dev Deps] update `aud`, `tape` [`5295419`](https://github.com/es-shims/String.prototype.trim/commit/5295419b0bbaf8035696ef3a24a8625ee743ec7f) + +## [v1.2.6](https://github.com/es-shims/String.prototype.trim/compare/v1.2.5...v1.2.6) - 2022-04-24 + +### Commits + +- [actions] reuse common workflows [`dbfc093`](https://github.com/es-shims/String.prototype.trim/commit/dbfc0932e7b2fad166245599310a1d84a1be0882) +- [Fix] as of unicode v6, the mongolian vowel separator is no longer whitespace [`56bbb86`](https://github.com/es-shims/String.prototype.trim/commit/56bbb86b8e514a16fc47e095b8c1014e12a2e92a) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `safe-publish-latest`, `tape` [`7fa437e`](https://github.com/es-shims/String.prototype.trim/commit/7fa437e4c3d25798d979294a121f93cb4346ba04) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `functions-have-names`, `tape` [`716a060`](https://github.com/es-shims/String.prototype.trim/commit/716a06080dbca68ec8e3b2e0e18c0a333ed28594) +- [actions] update codecov uploader [`9a39958`](https://github.com/es-shims/String.prototype.trim/commit/9a39958a13e20d6b9f01f9fce71dd37cc03da52e) +- [Fix] ensure main entry point properly checks the receiver in ES3 engines [`24220c4`](https://github.com/es-shims/String.prototype.trim/commit/24220c49dcb7055b5b94eb52c4d610428e19d3e4) +- [Deps] update `define-properties`, `es-abstract` [`c6008ea`](https://github.com/es-shims/String.prototype.trim/commit/c6008ea9007741755710b70ae05003cb71a7d1bd) + +## [v1.2.5](https://github.com/es-shims/String.prototype.trim/compare/v1.2.4...v1.2.5) - 2021-10-03 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`37d5a61`](https://github.com/es-shims/String.prototype.trim/commit/37d5a61c95a26c079b30e2d9d2ffdb70f36ca9cf) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `auto-changelog`, `tape` [`4c4a85e`](https://github.com/es-shims/String.prototype.trim/commit/4c4a85e5f521ae9811ac1205af933e3845b5a24e) +- [readme] add github actions/codecov badges [`9980eee`](https://github.com/es-shims/String.prototype.trim/commit/9980eee58866b08218ff3257a3af2aa9e29774fc) +- [Deps] update `es-abstract` [`6c1da80`](https://github.com/es-shims/String.prototype.trim/commit/6c1da806270fd909a76fc43e3dfe91be46058382) +- [readme] remove defunct testling badge [`8d282d1`](https://github.com/es-shims/String.prototype.trim/commit/8d282d1becd5f8d3ffe0e6e1dbfa2ddf29071670) +- [Dev Deps] update `eslint`, `tape` [`8856c26`](https://github.com/es-shims/String.prototype.trim/commit/8856c2663b5495cafb930e009f68e2d22958cac0) +- [actions] update workflows [`62cd341`](https://github.com/es-shims/String.prototype.trim/commit/62cd3412aaeee13c0d2cfe7f9bd33297e7279989) +- [meta] use `prepublishOnly` script for npm 7+ [`abd99c4`](https://github.com/es-shims/String.prototype.trim/commit/abd99c4a9838847efb3db7ddf579fb4bda8f6030) +- [Deps] update `es-abstract` [`802cb7b`](https://github.com/es-shims/String.prototype.trim/commit/802cb7b69b3a0c9a9b9642d641f0af490bd9dde7) + +## [v1.2.4](https://github.com/es-shims/String.prototype.trim/compare/v1.2.3...v1.2.4) - 2021-02-21 + +### Commits + +- [meta] do not publish github action workflow files [`936161b`](https://github.com/es-shims/String.prototype.trim/commit/936161bf43c83e09bc39c4d472d313c8f64e3fe3) +- [readme] remove travis badge [`9a28c39`](https://github.com/es-shims/String.prototype.trim/commit/9a28c3943b51a2cc87694c954205249122256d92) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `functions-have-names`, `has-strict-mode`, `tape` [`7b4be8d`](https://github.com/es-shims/String.prototype.trim/commit/7b4be8d12365feb5b42658902cf18316508a0c62) +- [Tests] increase coverage [`31b8735`](https://github.com/es-shims/String.prototype.trim/commit/31b87354f55f24501ca8b2f02477cb692a70457c) +- [actions] update workflows [`eda6ab7`](https://github.com/es-shims/String.prototype.trim/commit/eda6ab73fea52b49b74653e96ac81d5372599dc8) +- [Deps] update `call-bind`, `es-abstract` [`083f88f`](https://github.com/es-shims/String.prototype.trim/commit/083f88f5342144f337f1f82874cb8cd6f27f2262) + +## [v1.2.3](https://github.com/es-shims/String.prototype.trim/compare/v1.2.2...v1.2.3) - 2020-11-21 + +### Commits + +- [Tests] migrate tests to Github Actions [`6768c8d`](https://github.com/es-shims/String.prototype.trim/commit/6768c8d5569a6fcc841436b98a19ddf6b63c7de4) +- [Tests] run `nyc` on all tests [`2fd5baa`](https://github.com/es-shims/String.prototype.trim/commit/2fd5baa7239a4d449338e0333e2dc4573597962e) +- [Deps] update `es-abstract`; use `call-bind` where applicable [`e4e8c6e`](https://github.com/es-shims/String.prototype.trim/commit/e4e8c6ede423ee8c384564092f624f980097bb28) +- [Dev Deps] update `eslint`, `aud`, `auto-changelog` [`a21c1d5`](https://github.com/es-shims/String.prototype.trim/commit/a21c1d5c87ec9b1b5107b0a1faf138993951081c) + +## [v1.2.2](https://github.com/es-shims/String.prototype.trim/compare/v1.2.1...v1.2.2) - 2020-09-15 + +### Commits + +- [Tests] use `nyc` for coverage` [`0884270`](https://github.com/es-shims/String.prototype.trim/commit/0884270b26f7e6f7602d9f355dc3b4d5cd12d97e) +- [Tests] add implementation tests [`475c480`](https://github.com/es-shims/String.prototype.trim/commit/475c4804224a11bb6fba6d1407b59f7aab2c5d4e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`d70d913`](https://github.com/es-shims/String.prototype.trim/commit/d70d9136bc76499ecee1997068b7f3d1ba0f94e8) +- [actions] add "Allow Edits" workflow [`6e6be23`](https://github.com/es-shims/String.prototype.trim/commit/6e6be23aa679e02836e1f3e65bd09dd30c3fd2ae) +- [Refactor] use `RequireObjectCoercible` instead of `CheckObjectCoercible` [`5bfaf17`](https://github.com/es-shims/String.prototype.trim/commit/5bfaf1731edd5fcd01ec07f75717eebdf4992e4c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape`, `functions-have-names`; add `safe-publish-latest` [`65be600`](https://github.com/es-shims/String.prototype.trim/commit/65be600028222127c1faaeacea810bc042f35f70) +- [Deps] update `es-abstract`, remove `function-bind` [`5f4d1ec`](https://github.com/es-shims/String.prototype.trim/commit/5f4d1ec8f2c13a4b4fde171ca2029e1ec4057b2b) +- [Refactor] switch from 2019 to 2020 AOs [`4c2d5d2`](https://github.com/es-shims/String.prototype.trim/commit/4c2d5d23f63731958007d856767f5a2f9c779c15) +- [Dev Deps] update `auto-changelog`, `tape` [`c7fc9e2`](https://github.com/es-shims/String.prototype.trim/commit/c7fc9e22b09d24a9aa9e68358d4a5ba10e25ff04) +- [Dev Deps] update `auto-changelog`; add `aud` [`e1dec36`](https://github.com/es-shims/String.prototype.trim/commit/e1dec364391ea5d7dc8339d2da279fdc511cdbe9) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`35826c2`](https://github.com/es-shims/String.prototype.trim/commit/35826c21b140a3c1431bd20c3443da23888b92bc) +- [Deps] update `es-abstract` [`54095ef`](https://github.com/es-shims/String.prototype.trim/commit/54095ef76d193c8595516977e98343f8db754e2d) +- [Deps] update `es-abstract` [`486dd9c`](https://github.com/es-shims/String.prototype.trim/commit/486dd9c68c5843a9f50cde55749d34edb9702616) + +## [v1.2.1](https://github.com/es-shims/String.prototype.trim/compare/v1.2.0...v1.2.1) - 2019-12-16 + +### Commits + +- [Tests] use shared travis-ci configs [`52f7e64`](https://github.com/es-shims/String.prototype.trim/commit/52f7e643f128e04ed0139c1cb3da7b7907ea639f) +- [meta] add `auto-changelog` [`6284c06`](https://github.com/es-shims/String.prototype.trim/commit/6284c061c8f4de4314a43e8600ff879164ab162c) +- [meta] remove unused Makefile and associated utilities [`8c781cd`](https://github.com/es-shims/String.prototype.trim/commit/8c781cd4bad87f7bf31dae256ef0f1c19cec2113) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `functions-have-names` [`c54b481`](https://github.com/es-shims/String.prototype.trim/commit/c54b481743611e736315c10885cfc861d306e64a) +- [Refactor] use split-up `es-abstract` (57% bundle size decrease) [`b0378c9`](https://github.com/es-shims/String.prototype.trim/commit/b0378c99988846b0a8edf3fcfd08f30dd632f5a9) +- [actions] add automatic rebasing / merge commit blocking [`bffe893`](https://github.com/es-shims/String.prototype.trim/commit/bffe893990837250f8a3c4714bd52675251af5c7) +- [meta] add `funding` field [`0559449`](https://github.com/es-shims/String.prototype.trim/commit/05594490366fad2d8e4bd435937fbd81169d965a) +- [Deps] update `es-abstract` [`c44d307`](https://github.com/es-shims/String.prototype.trim/commit/c44d307a50bb1fc53811b49d9203cd794ed1bae4) + +## [v1.2.0](https://github.com/es-shims/String.prototype.trim/compare/v1.1.2...v1.2.0) - 2019-07-24 + +### Commits + +- [Tests] up to `node` `v12.6`, `v11.15`, `v10.16`, `v9.11`, `v8.16`, `v7.10`, `v6.17`, `4.9`; use `nvm install-latest-npm` [`b857148`](https://github.com/es-shims/String.prototype.trim/commit/b857148644d305f720b2dd9bf691b7dc2930f91d) +- [Tests] remove `jscs` [`ad1dea7`](https://github.com/es-shims/String.prototype.trim/commit/ad1dea7f6114de79d637e82cdfaf1aa5499bd358) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `covert`, `replace`, `semver`, `tape` [`fcbc11d`](https://github.com/es-shims/String.prototype.trim/commit/fcbc11d4af9be65f4f7eb4aec20498c7a33a004f) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `@ljharb/eslint-config` [`06a4ffa`](https://github.com/es-shims/String.prototype.trim/commit/06a4ffa3078d4ab65418e878d3ef7b03277e8a1f) +- [Dev Deps] update `jscs`, `nsp`, `eslint`, `@es-shims/api` [`3554fb1`](https://github.com/es-shims/String.prototype.trim/commit/3554fb1fe722004080000b0767f7f89676a3d73a) +- [Dev Deps] update `nsp`, `eslint`, `@ljharb/eslint-config` [`804b2f2`](https://github.com/es-shims/String.prototype.trim/commit/804b2f244c257b32cb2473eb1a829ce97dc6a0a5) +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `semver`, `@ljharb/eslint-config` [`6a69408`](https://github.com/es-shims/String.prototype.trim/commit/6a694081cdd9aa9296ea181e4d2b4c6fe656bb16) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`e89adee`](https://github.com/es-shims/String.prototype.trim/commit/e89adeefcbd6fb59563e62d230b8036d65a8bf69) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`1280e56`](https://github.com/es-shims/String.prototype.trim/commit/1280e5629deb4554c7077d0e452399c03c06f7b1) +- [New] add `auto` entry point [`bb00b15`](https://github.com/es-shims/String.prototype.trim/commit/bb00b1551d2774e216b5d316b552d08a7f0619d4) +- [Tests] fix tests for the mongolian vowel separator [`a35f627`](https://github.com/es-shims/String.prototype.trim/commit/a35f6275ec7b4d6b47136a007fd07566e037cac8) +- [Tests] up to `node` `v5.9`, `v4.4` [`b541b9b`](https://github.com/es-shims/String.prototype.trim/commit/b541b9b46873be859aea6c5b1e7f6f54323ea139) +- [Dev Deps] update `jscs`, `nsp`, `eslint` [`b52022d`](https://github.com/es-shims/String.prototype.trim/commit/b52022d809922914827c34bcf2c1f81b68bde092) +- [Tests] use pretest/posttest for linting/security [`39f5684`](https://github.com/es-shims/String.prototype.trim/commit/39f56844f30f630ab5497f38153b8f0646ed1d96) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`8c358c2`](https://github.com/es-shims/String.prototype.trim/commit/8c358c22ee57bd5e7b437fb707230399ea7c42aa) +- [Tests] up to `node` `v6.2` [`2ac7e1f`](https://github.com/es-shims/String.prototype.trim/commit/2ac7e1f90088bb0c96986006539ffebb6b2a6eda) +- Only apps should have lockfiles [`cb15ed5`](https://github.com/es-shims/String.prototype.trim/commit/cb15ed57fbf3ba3f2d7f24af957e8ff41421dd81) +- [Deps] update `define-properties`, `es-abstract`, `function-bind` [`5e0371a`](https://github.com/es-shims/String.prototype.trim/commit/5e0371af5c7b8fee49a0e7d1bcc26fcf41743779) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api` [`37bae7f`](https://github.com/es-shims/String.prototype.trim/commit/37bae7f8f4952b376036d924673b9e885da022f8) +- [Tests] on `node` `v5.6`, `v4.3` [`33017cf`](https://github.com/es-shims/String.prototype.trim/commit/33017cf0d3aade480c357ee8aedaca7bc5a75092) +- [Tests] allow coverage to fail [`0d7b1e3`](https://github.com/es-shims/String.prototype.trim/commit/0d7b1e365484f8c33247b60e2a07748dc2183d40) +- [Tests] use `functions-have-names` [`3e68777`](https://github.com/es-shims/String.prototype.trim/commit/3e687776f6a45e3a6d129705aad3bb4863758114) +- [Tests] on `node` `v5.12` [`32ea49d`](https://github.com/es-shims/String.prototype.trim/commit/32ea49d7572b3f981d036ea060e3ed3559ad78ef) +- [Deps] update `es-abstract` [`15f7f24`](https://github.com/es-shims/String.prototype.trim/commit/15f7f249619b7aab941c6c8156cb81ed57c39b7e) +- [Tests] on `node` `v5.10` [`080c50f`](https://github.com/es-shims/String.prototype.trim/commit/080c50fc617de7ac024d443d4a9b76ba295bd744) +- [Deps] update `function-bind` [`532480e`](https://github.com/es-shims/String.prototype.trim/commit/532480e07ad7bf22da64d401ede35928d21ff558) + +## [v1.1.2](https://github.com/es-shims/String.prototype.trim/compare/v1.1.1...v1.1.2) - 2016-02-06 + +### Commits + +- [Dev Deps] update `tape`, `jscs`, `nsp`, `eslint`, `semver`, `@ljharb/eslint-config` [`df94d07`](https://github.com/es-shims/String.prototype.trim/commit/df94d07e12ca1e52739353f534a3d89e0a860a70) +- [Dev Deps] update `tape`, `jscs`, `eslint`, `@ljharb/eslint-config` [`ef78d89`](https://github.com/es-shims/String.prototype.trim/commit/ef78d89148efe8d371fb828923dd149163e2c5c6) +- [Dev Deps] update `jscs`, `eslint`, `@ljharb/eslint-config` [`b746516`](https://github.com/es-shims/String.prototype.trim/commit/b7465166a48828367bedaa2d42a30a5e148dcaae) +- package.json: use object form of "authors", add "contributors" [`a799df1`](https://github.com/es-shims/String.prototype.trim/commit/a799df17322ae526d5c8732c75bd5bcc3d1f649f) +- [Tests] up to `node` `v5.5`, don’t allow `0.8` to fail [`7fea308`](https://github.com/es-shims/String.prototype.trim/commit/7fea3082424fbeb25f2cb88884a999326ca428f2) +- [Dev Deps] update `jscs`, `nsp`, `eslint`, `semver`, `@ljharb/eslint-config` [`d14c7c1`](https://github.com/es-shims/String.prototype.trim/commit/d14c7c1850fb8e3a9f1d153bd818ed3beacdbadc) +- [Tests] up to `io.js` `v3.3`, `node` `v4.1` [`2903359`](https://github.com/es-shims/String.prototype.trim/commit/29033591ca3e65977e2746537c94b7e2e8b65ecc) +- [Tests] fix npm upgrades for older nodes [`0a6cbfa`](https://github.com/es-shims/String.prototype.trim/commit/0a6cbfa0ac506703ed554f6dc8bbde7ac1977cd4) +- [Deps] update `define-properties`, `es-abstract` [`39ccb08`](https://github.com/es-shims/String.prototype.trim/commit/39ccb0881762d762934ef2cb3c0459c65b3abf72) +- [Deps] update `es-abstract` [`c40e4fb`](https://github.com/es-shims/String.prototype.trim/commit/c40e4fb229e1a6a3e3c6818fc680ca380f2d866c) +- Use the polyfill, not the implementation, as the default export. [`0fe847e`](https://github.com/es-shims/String.prototype.trim/commit/0fe847e901871f1a8f33a66be2cd518bf8dcd0e1) +- [Tests] on `node` `v4.2` [`589743c`](https://github.com/es-shims/String.prototype.trim/commit/589743c0f8b1432a79cfed4b29187e6a9760a87b) +- [Deps] update `es-abstract` [`85bad8e`](https://github.com/es-shims/String.prototype.trim/commit/85bad8e217969a6e1eb7679a1bb06d6f075bd557) +- added assert [`aa81ac5`](https://github.com/es-shims/String.prototype.trim/commit/aa81ac55540a9e53a58ce0d1f5266ff36d403b3a) + +## [v1.1.1](https://github.com/es-shims/String.prototype.trim/compare/v1.1.0...v1.1.1) - 2015-08-16 + +### Commits + +- [Docs] remove "if" around `.shim` call in example [`b9ce088`](https://github.com/es-shims/String.prototype.trim/commit/b9ce08875f7252a85928e426db9b533cc5ee007a) + +## [v1.1.0](https://github.com/es-shims/String.prototype.trim/compare/v1.0.0...v1.1.0) - 2015-08-16 + +### Commits + +- Implement the [es-shim API](es-shims/api). [`5812703`](https://github.com/es-shims/String.prototype.trim/commit/581270337926462f9babf83772bcab71bc48bf8f) +- Move implementation to `implementation.js` [`e455b2a`](https://github.com/es-shims/String.prototype.trim/commit/e455b2af0e360358f02e54b556e698a971fc31f4) +- Fix `make release` [`efd2071`](https://github.com/es-shims/String.prototype.trim/commit/efd20711e9a226ad25e2b1e5ad7bbe85ef832d69) +- [Dev Deps] update `jscs` [`6c2fa95`](https://github.com/es-shims/String.prototype.trim/commit/6c2fa957538f139767de540693910cf1f49c8d3a) +- [Deps] update `es-abstract` [`de4cd87`](https://github.com/es-shims/String.prototype.trim/commit/de4cd876239d550f3c35e1db55a973cbb03c9b77) +- [Dev Deps] update `tape` [`2d07fe1`](https://github.com/es-shims/String.prototype.trim/commit/2d07fe19ff136467e1edbca91cfea6caac1b06d8) +- [Dev Deps] update `tape` [`e697efe`](https://github.com/es-shims/String.prototype.trim/commit/e697efe943cab07639d62649424c72e4f44f2469) +- Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. [`6065103`](https://github.com/es-shims/String.prototype.trim/commit/6065103baa10f56b904f44693d5ba6b23ee6ba57) + +## v1.0.0 - 2015-08-08 + +### Commits + +- Dotfiles / Makefile [`b7f0e52`](https://github.com/es-shims/String.prototype.trim/commit/b7f0e526ea73136e00595d768faaba83a41da7ee) +- Tests [`4d61441`](https://github.com/es-shims/String.prototype.trim/commit/4d61441de9dcf2278dcd118077d4541843a47534) +- package.json [`2a2e0f2`](https://github.com/es-shims/String.prototype.trim/commit/2a2e0f2949dd30095eda20e1796483ea21dd7b38) +- Initial commit [`51aa18f`](https://github.com/es-shims/String.prototype.trim/commit/51aa18f299f8d340034670af0311c5981c89f713) +- Read me [`5681192`](https://github.com/es-shims/String.prototype.trim/commit/56811925aed1dd06a2cfa654b3f246b6a897a33c) +- Implementation [`87f08c5`](https://github.com/es-shims/String.prototype.trim/commit/87f08c565f7be56c2826386aa4a4e683a00d8871) diff --git a/node_modules/string.prototype.trim/LICENSE b/node_modules/string.prototype.trim/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..fcf5754efe64aba538886b63ea4640a2c80457af --- /dev/null +++ b/node_modules/string.prototype.trim/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jordan Harband + +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. diff --git a/node_modules/string.prototype.trim/README.md b/node_modules/string.prototype.trim/README.md new file mode 100644 index 0000000000000000000000000000000000000000..243be5fa183a7a4e351e2682a4ae9e417562484f --- /dev/null +++ b/node_modules/string.prototype.trim/README.md @@ -0,0 +1,46 @@ +# String.prototype.trim [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +An ES5 spec-compliant `String.prototype.trim` shim. Invoke its "shim" method to shim `String.prototype.trim` if it is unavailable. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the spec (both [ES5](https://262.ecma-international.org/5.1/#sec-15.5.4.20) and [current](https://tc39.es/ecma262/#sec-string.prototype.trim)). + +Most common usage: + +```js +var assert = require('assert'); +var trim = require('string.prototype.trim'); + +assert(trim(' \t\na \t\n') === 'a'); + +trim.shim(); // will be a no-op if not needed + +assert(trim(' \t\na \t\n') === ' \t\na \t\n'.trim()); +``` + +## Engine Bugs +Some implementations of `String#trim` incorrectly trim zero-width spaces. This shim detects and corrects this behavior. + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/string.prototype.trim +[npm-version-svg]: https://versionbadg.es/es-shims/String.prototype.trim.svg +[deps-svg]: https://david-dm.org/es-shims/String.prototype.trim.svg +[deps-url]: https://david-dm.org/es-shims/String.prototype.trim +[dev-deps-svg]: https://david-dm.org/es-shims/String.prototype.trim/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/String.prototype.trim#info=devDependencies +[license-image]: https://img.shields.io/npm/l/string.prototype.trim.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/string.prototype.trim.svg +[downloads-url]: https://npm-stat.com/charts.html?package=string.prototype.trim +[codecov-image]: https://codecov.io/gh/es-shims/String.prototype.trim/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/String.prototype.trim/ +[actions-image]: https://img.shields.io/github/check-runs/es-shims/String.prototype.trim/main +[actions-url]: https://github.com/es-shims/String.prototype.trim/actions diff --git a/node_modules/string.prototype.trim/auto.js b/node_modules/string.prototype.trim/auto.js new file mode 100644 index 0000000000000000000000000000000000000000..8ebf606cb02ff3a8c6ef786afa37d21a19254f46 --- /dev/null +++ b/node_modules/string.prototype.trim/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/string.prototype.trim/implementation.js b/node_modules/string.prototype.trim/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..dcc9f2613be09c540ba9bf3c4a23c5b4fbd6e125 --- /dev/null +++ b/node_modules/string.prototype.trim/implementation.js @@ -0,0 +1,30 @@ +'use strict'; + +var RequireObjectCoercible = require('es-object-atoms/RequireObjectCoercible'); +var ToString = require('es-abstract/2025/ToString'); +var callBound = require('call-bound'); +var safeRegexTester = require('safe-regex-test'); + +var $replace = callBound('String.prototype.replace'); +var $charAt = callBound('String.prototype.charAt'); +var $slice = callBound('String.prototype.slice'); + +var mvsIsWS = (/^\s$/).test('\u180E'); +/* eslint-disable no-control-regex */ +var leftWhitespace = mvsIsWS + ? /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/ + : /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/; +var isWhitespace = safeRegexTester(mvsIsWS + ? /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]$/ + : /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]$/); +/* eslint-enable no-control-regex */ + +module.exports = function trim() { + var S = $replace(ToString(RequireObjectCoercible(this)), leftWhitespace, ''); + // scan back for the trailing whitespace boundary; a `$`-anchored regexp is quadratic on large internal whitespace runs + var end = S.length; + while (end > 0 && isWhitespace($charAt(S, end - 1))) { + end -= 1; + } + return $slice(S, 0, end); +}; diff --git a/node_modules/string.prototype.trim/index.js b/node_modules/string.prototype.trim/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ce41c888ce172e8b900b10bb690ff25ded2754f9 --- /dev/null +++ b/node_modules/string.prototype.trim/index.js @@ -0,0 +1,23 @@ +'use strict'; + +var callBind = require('call-bind'); +var define = require('define-properties'); +var RequireObjectCoercible = require('es-object-atoms/RequireObjectCoercible'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var bound = callBind(getPolyfill()); +var boundMethod = function trim(receiver) { + RequireObjectCoercible(receiver); + return bound(receiver); +}; + +define(boundMethod, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = boundMethod; diff --git a/node_modules/string.prototype.trim/package.json b/node_modules/string.prototype.trim/package.json new file mode 100644 index 0000000000000000000000000000000000000000..28cedb0f6a49a9efac5043dcdd6f39f061146426 --- /dev/null +++ b/node_modules/string.prototype.trim/package.json @@ -0,0 +1,108 @@ +{ + "name": "string.prototype.trim", + "version": "1.2.11", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "ES5 spec-compliant shim for String.prototype.trim", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "tests-only": "nyc tape 'test/**/*.js'", + "lint": "eslint --ext=js,mjs .", + "postlint": "es-shim-api --bound", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/es-shims/String.prototype.trim.git" + }, + "keywords": [ + "String.prototype.trim", + "string", + "ES5", + "shim", + "trim", + "polyfill", + "es-shim API" + ], + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-data-property": "^1.1.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.2", + "es-object-atoms": "^1.1.2", + "has-property-descriptors": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "devDependencies": { + "@ericcornelissen/assert-time": "^1.0.3", + "@es-shims/api": "^2.5.1", + "@ljharb/eslint-config": "^22.2.3", + "auto-changelog": "^2.6.0", + "eslint": "^8.57.1", + "for-each": "^0.3.5", + "functions-have-names": "^1.2.3", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "string.prototype.repeat": "^1.0.0", + "tape": "^5.9.0" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/9.0..latest", + "firefox/4.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/11.6..latest", + "opera/next", + "safari/5.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + } +} diff --git a/node_modules/string.prototype.trim/polyfill.js b/node_modules/string.prototype.trim/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..534db4ca9f830a9180cc373a9685472d2227fd75 --- /dev/null +++ b/node_modules/string.prototype.trim/polyfill.js @@ -0,0 +1,19 @@ +'use strict'; + +var implementation = require('./implementation'); + +var zeroWidthSpace = '\u200b'; +var mongolianVowelSeparator = '\u180E'; + +module.exports = function getPolyfill() { + if ( + String.prototype.trim + && zeroWidthSpace.trim() === zeroWidthSpace + && mongolianVowelSeparator.trim() === mongolianVowelSeparator + && ('_' + mongolianVowelSeparator).trim() === ('_' + mongolianVowelSeparator) + && (mongolianVowelSeparator + '_').trim() === (mongolianVowelSeparator + '_') + ) { + return String.prototype.trim; + } + return implementation; +}; diff --git a/node_modules/string.prototype.trim/shim.js b/node_modules/string.prototype.trim/shim.js new file mode 100644 index 0000000000000000000000000000000000000000..58a073cdcb75f1bf5a50d08bee5b9bd4e372e2de --- /dev/null +++ b/node_modules/string.prototype.trim/shim.js @@ -0,0 +1,20 @@ +'use strict'; + +var supportsDescriptors = require('has-property-descriptors')(); +var defineDataProperty = require('define-data-property'); + +var getPolyfill = require('./polyfill'); + +module.exports = function shimStringTrim() { + var polyfill = getPolyfill(); + + if (String.prototype.trim !== polyfill) { + if (supportsDescriptors) { + defineDataProperty(String.prototype, 'trim', polyfill, true); + } else { + defineDataProperty(String.prototype, 'trim', polyfill); + } + } + + return polyfill; +}; diff --git a/node_modules/string.prototype.trim/test/implementation.js b/node_modules/string.prototype.trim/test/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..ba3ae596ea41e1a1691f35038de6f356a53c2df5 --- /dev/null +++ b/node_modules/string.prototype.trim/test/implementation.js @@ -0,0 +1,21 @@ +'use strict'; + +var trim = require('../implementation'); +var test = require('tape'); +var hasStrictMode = require('has-strict-mode')(); +var callBind = require('call-bind'); + +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', { skip: !hasStrictMode }, function (st) { + /* eslint no-useless-call: 0 */ + st['throws'](function () { trim.call(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { trim.call(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(trim), t); + + t.end(); +}); diff --git a/node_modules/string.prototype.trim/test/index.js b/node_modules/string.prototype.trim/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..cc90851756c4d013d86dd9394199a6d72077e46d --- /dev/null +++ b/node_modules/string.prototype.trim/test/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var trim = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { trim(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { trim(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(trim, t); + + t.end(); +}); diff --git a/node_modules/string.prototype.trim/test/shimmed.js b/node_modules/string.prototype.trim/test/shimmed.js new file mode 100644 index 0000000000000000000000000000000000000000..57cf69c7c3279e1dce9b2dd05d0f7a8313f2cb03 --- /dev/null +++ b/node_modules/string.prototype.trim/test/shimmed.js @@ -0,0 +1,36 @@ +'use strict'; + +require('../auto'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +var runTests = require('./tests'); + +test('shimmed', function (t) { + t.equal(String.prototype.trim.length, 0, 'String#trim has a length of 0'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal(String.prototype.trim.name, 'trim', 'String#trim has name "trim"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(String.prototype, 'trim'), 'String#trim is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad string/this value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return String.prototype.trim.call(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return String.prototype.trim.call(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(String.prototype.trim), t); + + t.end(); +}); diff --git a/node_modules/string.prototype.trim/test/tests.js b/node_modules/string.prototype.trim/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..95c83c88595bff6d4c9f4943cf8c3a1b933cfb1d --- /dev/null +++ b/node_modules/string.prototype.trim/test/tests.js @@ -0,0 +1,92 @@ +'use strict'; + +var forEach = require('for-each'); +var repeat = require('string.prototype.repeat'); +var assertTime = require('@ericcornelissen/assert-time'); + +module.exports = function (trim, t) { + t.test('normal cases', function (st) { + st.equal(trim(' \t\na \t\n'), 'a', 'strips whitespace off left and right sides'); + st.equal(trim('a'), 'a', 'noop when no whitespace'); + st.equal(trim(' a'), 'a', 'strips whitespace off left side only'); + st.equal(trim('a '), 'a', 'strips whitespace off right side only'); + + var allWhitespaceChars = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + st.equal(trim(allWhitespaceChars + 'a' + allWhitespaceChars), 'a', 'all expected whitespace chars are trimmed'); + + st.end(); + }); + + t.test('pathological case', function (st) { + var input = 'A' + repeat(' ', 100000) + 'A'; + + st.doesNotThrow(function () { + assertTime(function () { + trim(input); + }, 500); + }); + + st.end(); + }); + + t.test('pathological case with trailing whitespace', function (st) { + var input = 'A' + repeat(' ', 100000) + 'A' + repeat(' ', 100000); + + st.equal(trim(input), 'A' + repeat(' ', 100000) + 'A', 'trailing whitespace is trimmed, internal whitespace is preserved'); + + st.doesNotThrow(function () { + assertTime(function () { + trim(input); + }, 500); + }); + + st.end(); + }); + + // see https://codeblog.jonskeet.uk/2014/12/01/when-is-an-identifier-not-an-identifier-attack-of-the-mongolian-vowel-separator/ + var mongolianVowelSeparator = '\u180E'; + var mvsIsWS = (/^\s$/).test('\u180E'); + t.test('unicode >= 4 && < 6.3', function (st) { + st.equal( + trim(mongolianVowelSeparator + 'a' + mongolianVowelSeparator), + mvsIsWS ? 'a' : mongolianVowelSeparator + 'a' + mongolianVowelSeparator, + 'mongolian vowel separator is' + (mvsIsWS ? '' : ' not') + ' whitespace' + ); + + st.equal( + trim(mongolianVowelSeparator), + mvsIsWS ? '' : mongolianVowelSeparator + ); + st.equal( + trim('_' + mongolianVowelSeparator), + '_' + (mvsIsWS ? '' : mongolianVowelSeparator) + ); + st.equal( + trim(mongolianVowelSeparator + '_'), + (mvsIsWS ? '' : mongolianVowelSeparator) + '_' + ); + + st.end(); + }); + + t.test('zero-width spaces', function (st) { + var zeroWidth = '\u200b'; + st.equal(trim(zeroWidth), zeroWidth, 'zero width space does not trim'); + st.end(); + }); + + t.test('non-whitespace characters', function (st) { + // Zero-width space (zws), next line character (nel), and non-character (bom) are not whitespace. + var nonWhitespaces = { + '\\u0085': '\u0085', + '\\u200b': '\u200b', + '\\ufffe': '\ufffe' + }; + + forEach(nonWhitespaces, function (nonWhitespace, name) { + st.equal(trim(nonWhitespace), nonWhitespace, name + ' does not trim'); + }); + + st.end(); + }); +}; diff --git a/node_modules/string.prototype.trimend/.editorconfig b/node_modules/string.prototype.trimend/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..bc228f8269443bf772b437890dde7756a3e8a894 --- /dev/null +++ b/node_modules/string.prototype.trimend/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/string.prototype.trimend/.eslintrc b/node_modules/string.prototype.trimend/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..8056b20c9f21cb06262631bb70c27ab43fef655f --- /dev/null +++ b/node_modules/string.prototype.trimend/.eslintrc @@ -0,0 +1,24 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "RequireObjectCoercible", + ], + }], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "id-length": 0, + "no-invalid-this": 1, + }, + }, + ], +} diff --git a/node_modules/string.prototype.trimend/.nycrc b/node_modules/string.prototype.trimend/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/string.prototype.trimend/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/string.prototype.trimend/CHANGELOG.md b/node_modules/string.prototype.trimend/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..957f4350783992e25649bded27f23d1e03c01ba1 --- /dev/null +++ b/node_modules/string.prototype.trimend/CHANGELOG.md @@ -0,0 +1,139 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.10](https://github.com/es-shims/String.prototype.trimEnd/compare/v1.0.9...v1.0.10) - 2026-06-05 + +### Commits + +- [Fix] avoid quadratic runtime trimming strings with large internal whitespace runs [`14ee151`](https://github.com/es-shims/String.prototype.trimEnd/commit/14ee1516d13537c2c63afa56c85048ead5f2e7c8) +- [actions] update workflows [`867fda8`](https://github.com/es-shims/String.prototype.trimEnd/commit/867fda84fa544487659ed49407ab53986cf67897) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `eslint`, `has-strict-mode`, `npmignore` [`c1dad08`](https://github.com/es-shims/String.prototype.trimEnd/commit/c1dad08e7b3410f7cf37d0031452db166a671b3f) +- [Deps] update `call-bind`, `call-bound`, `es-object-atoms` [`9f23631`](https://github.com/es-shims/String.prototype.trimEnd/commit/9f23631ac981b82d3f769b20538c3b429dc86e93) +- [readme] remove dead badges [`5156bc8`](https://github.com/es-shims/String.prototype.trimEnd/commit/5156bc89dfaceb0bbfb48c553517db9242a5c09a) +- [readme] replace runkit CI badge with shields.io check-runs badge [`79f9686`](https://github.com/es-shims/String.prototype.trimEnd/commit/79f96868928b28ce477bcbd01d8d4b55e60753e6) + +## [v1.0.9](https://github.com/es-shims/String.prototype.trimEnd/compare/v1.0.8...v1.0.9) - 2024-12-11 + +### Commits + +- [actions] split out node 10-20, and 20+ [`7e5ffdc`](https://github.com/es-shims/String.prototype.trimEnd/commit/7e5ffdc2ab30b09e19773f35df5dceffddc660d4) +- [meta] sort package.json mildly [`2f99c8b`](https://github.com/es-shims/String.prototype.trimEnd/commit/2f99c8bc69d50dc0c56af3900cc31129ef42bc1b) +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `auto-changelog`, `tape` [`2774fe6`](https://github.com/es-shims/String.prototype.trimEnd/commit/2774fe6660c9de92eacf2a8173f494aa151b1fc1) +- [Refactor] use `call-bound` directly [`9e3bbec`](https://github.com/es-shims/String.prototype.trimEnd/commit/9e3bbec66695b715ec38f832aa472e1a82ffe095) +- [Tests] replace `aud` with `npm audit` [`cb9a462`](https://github.com/es-shims/String.prototype.trimEnd/commit/cb9a4623b86d2a91cb0a5b704739b6fe43078abd) +- [meta] add missing `engines.node` [`f46c829`](https://github.com/es-shims/String.prototype.trimEnd/commit/f46c829985a3c78e92482247fe30800781b4a9e3) +- [Deps] update `call-bind` [`e892c32`](https://github.com/es-shims/String.prototype.trimEnd/commit/e892c32d30aaaee372c8159b7ac94d564cf7f0e9) +- [Dev Deps] add missing peer dep [`e1a59da`](https://github.com/es-shims/String.prototype.trimEnd/commit/e1a59da39cc18bbe546371b12d39f86b4c947896) + +## [v1.0.8](https://github.com/es-shims/String.prototype.trimEnd/compare/v1.0.7...v1.0.8) - 2024-03-16 + +### Commits + +- [Refactor] replace `es-abstract` with `es-object-atoms` [`0df2b01`](https://github.com/es-shims/String.prototype.trimEnd/commit/0df2b018d3ba214e2435b9841a7a03fc06c24fd0) +- [Dev Deps] update `aud`, `npmignore`, `tape` [`190e9c5`](https://github.com/es-shims/String.prototype.trimEnd/commit/190e9c5d74f84d8f90f61c9e9ad4b05f657df830) + +## [v1.0.7](https://github.com/es-shims/String.prototype.trimEnd/compare/v1.0.6...v1.0.7) - 2023-09-07 + +### Commits + +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `tape` [`1a10293`](https://github.com/es-shims/String.prototype.trimEnd/commit/1a102935636b564cd346d83666f62a9398864081) +- [Deps] update `define-properties`, `es-abstract` [`6ba2e19`](https://github.com/es-shims/String.prototype.trimEnd/commit/6ba2e19a78f9c63bad2daf0627ce7f2e33f1aeb9) + +## [v1.0.6](https://github.com/es-shims/String.prototype.trimEnd/compare/v1.0.5...v1.0.6) - 2022-11-07 + +### Commits + +- [meta] use `npmignore` to autogenerate an npmignore file [`1d1e717`](https://github.com/es-shims/String.prototype.trimEnd/commit/1d1e71720ada81e484c9bffb386f65d7a6a1335e) +- [actions] update rebase action to use reusable workflow [`83f2683`](https://github.com/es-shims/String.prototype.trimEnd/commit/83f268325cc37ca72bea995281167a9d2821810b) +- [Dev Deps] update `aud`, `tape` [`a3a9129`](https://github.com/es-shims/String.prototype.trimEnd/commit/a3a9129dd995a949bdb93d278f403aa400e088ed) +- [Deps] update `es-abstract` [`a6e476d`](https://github.com/es-shims/String.prototype.trimEnd/commit/a6e476dc0120a41a22e66b5079bf3b407da387fa) + +## [v1.0.5](https://github.com/es-shims/String.prototype.trimEnd/compare/v1.0.4...v1.0.5) - 2022-05-02 + +### Commits + +- [actions] reuse common workflows [`69a56ce`](https://github.com/es-shims/String.prototype.trimEnd/commit/69a56ce95343848d5e498f8e939a0697db8ac9f2) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`5d7db31`](https://github.com/es-shims/String.prototype.trimEnd/commit/5d7db314948faac975705db56305b6cc3dae7ba9) +- [Fix] ensure main entry point properly checks the receiver in ES3 engines [`bb1983d`](https://github.com/es-shims/String.prototype.trimEnd/commit/bb1983dc27504733ab883a42f55b134f679a642d) +- [Fix] as of unicode v6, the mongolian vowel separator is no longer whitespace [`10a1091`](https://github.com/es-shims/String.prototype.trimEnd/commit/10a10916e1ffc8cdab78515b2cc521cc74c08277) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `safe-publish-latest`, `tape` [`a08e14b`](https://github.com/es-shims/String.prototype.trimEnd/commit/a08e14bfea5e27d419ef742e83f467a169a69971) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `functions-have-names`, `tape` [`1c4c8da`](https://github.com/es-shims/String.prototype.trimEnd/commit/1c4c8dab4aefc1c5823a61b5a0286bb6fe1e036c) +- [actions] update codecov uploader [`70c4a7c`](https://github.com/es-shims/String.prototype.trimEnd/commit/70c4a7c566fd5bf72475df9318ec2cd218ceca26) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `auto-changelog`, `tape` [`4b08ed7`](https://github.com/es-shims/String.prototype.trimEnd/commit/4b08ed78a579585b593b3ca4ac7919d13906e840) +- [readme] add github actions/codecov badges [`9805501`](https://github.com/es-shims/String.prototype.trimEnd/commit/980550105b304385bcccb8ec05a247e02c24d04a) +- [Dev Deps] update `eslint`, `tape` [`50ec335`](https://github.com/es-shims/String.prototype.trimEnd/commit/50ec335ed42b59d1ab626dbe412f4ae23ab99b4b) +- [actions] update workflows [`bf9c32e`](https://github.com/es-shims/String.prototype.trimEnd/commit/bf9c32efe08e98b53302df67581dc971b7a758cd) +- [meta] use `prepublishOnly` script for npm 7+ [`9d921bd`](https://github.com/es-shims/String.prototype.trimEnd/commit/9d921bdbcaf8cebebbc302e6df518cbc3e4907bd) +- [Deps] update `define-properties` [`15617ce`](https://github.com/es-shims/String.prototype.trimEnd/commit/15617ced8ac2ea3ab8324a04d16fd294b12059b5) + +## [v1.0.4](https://github.com/es-shims/String.prototype.trimEnd/compare/v1.0.3...v1.0.4) - 2021-02-23 + +### Commits + +- [meta] do not publish github action workflow files [`08e735c`](https://github.com/es-shims/String.prototype.trimEnd/commit/08e735cd55b00ae78a9dc16c6b4e786f7931085b) +- [readme] remove travis badge [`10e0e47`](https://github.com/es-shims/String.prototype.trimEnd/commit/10e0e47cb2ecfd171e68b40f8486c5d007dcf3ef) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `functions-have-names`, `has-strict-mode`, `tape` [`0871432`](https://github.com/es-shims/String.prototype.trimEnd/commit/0871432c70c2f6a3929acd740a5d1f57c939f345) +- [Tests] increase coverage [`711e6a6`](https://github.com/es-shims/String.prototype.trimEnd/commit/711e6a66660f30f7a30fef536be435af1a13d05c) +- [actions] update workflows [`deb0d06`](https://github.com/es-shims/String.prototype.trimEnd/commit/deb0d06f41ac1c3e1e640ecd1cf0e69303ab5799) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`e250b4a`](https://github.com/es-shims/String.prototype.trimEnd/commit/e250b4a38401e7c02a067dab26cc68316da47ef7) +- [meta] gitignore coverage output [`55231df`](https://github.com/es-shims/String.prototype.trimEnd/commit/55231dfd9829277ba5c3f07be5434dc385703ca9) +- [Deps] update `call-bind` [`0580f5f`](https://github.com/es-shims/String.prototype.trimEnd/commit/0580f5f915ecb87677764d03fe3cf023e3bee7d8) + +## [v1.0.3](https://github.com/es-shims/String.prototype.trimEnd/compare/v1.0.2...v1.0.3) - 2020-11-21 + +### Commits + +- [Tests] migrate tests to Github Actions [`23e7a09`](https://github.com/es-shims/String.prototype.trimEnd/commit/23e7a09a4ad37c21c3db3d7761212c7d84a371a2) +- [Tests] add `implementation` test; run `es-shim-api` in postlint; use `tape` runner [`26e8623`](https://github.com/es-shims/String.prototype.trimEnd/commit/26e8623cf35c1859d0b482d4bb5b3450d101a810) +- [Tests] run `nyc` on all tests [`a72a546`](https://github.com/es-shims/String.prototype.trimEnd/commit/a72a546f671c5d3ac65dff68b4db1a1cc7089bfd) +- [Deps] replace `es-abstract` with `call-bind` [`f07b87d`](https://github.com/es-shims/String.prototype.trimEnd/commit/f07b87dd452090a2601d666edceb1daa90d45f24) +- [Dev Deps] update `eslint`, `aud`; add `safe-publish-latest` [`122ecb7`](https://github.com/es-shims/String.prototype.trimEnd/commit/122ecb726b1dc043b9ef27fa5a7b4172a4d5df37) + +## [v1.0.2](https://github.com/es-shims/String.prototype.trimEnd/compare/v1.0.1...v1.0.2) - 2020-10-20 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`a003e71`](https://github.com/es-shims/String.prototype.trimEnd/commit/a003e7166d8de16c551a14b0ec855187357cce43) +- [actions] add "Allow Edits" workflow [`0b4b43c`](https://github.com/es-shims/String.prototype.trimEnd/commit/0b4b43cb605f7b3532e61c43dfc7f1795296c5a4) +- [Deps] update `es-abstract` [`75ca6b0`](https://github.com/es-shims/String.prototype.trimEnd/commit/75ca6b0e9757d64013ae863cfaac49ebcb36f1cf) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`552016c`](https://github.com/es-shims/String.prototype.trimEnd/commit/552016cb631ac13c12bbbc0d6dd65012e5e79583) + +## [v1.0.1](https://github.com/es-shims/String.prototype.trimEnd/compare/v1.0.0...v1.0.1) - 2020-04-09 + +### Commits + +- [meta] add some missing repo metadata [`6abe248`](https://github.com/es-shims/String.prototype.trimEnd/commit/6abe248ba0b57a8b0e16bbe01de07a4d37c421bc) +- [Dev Deps] update `auto-changelog` [`e2eaab2`](https://github.com/es-shims/String.prototype.trimEnd/commit/e2eaab2fd1bc27a3d224b3d76db16190c1dd6d08) + +## [v1.0.0](https://github.com/es-shims/String.prototype.trimEnd/compare/v0.1.0...v1.0.0) - 2020-03-30 + +### Commits + +- [Breaking] convert to es-shim API [`2c6ef13`](https://github.com/es-shims/String.prototype.trimEnd/commit/2c6ef13d3f0b07a9bc55e367b311dbb731780405) +- [meta] add `auto-changelog` [`6f1fcc1`](https://github.com/es-shims/String.prototype.trimEnd/commit/6f1fcc1739de1e9541bd603b659807646a13dd7f) +- [meta] update readme [`ed4ce0d`](https://github.com/es-shims/String.prototype.trimEnd/commit/ed4ce0d84d53e626b48375c5959be20332464eaf) +- [Tests] add `npm run lint` [`eadaf2c`](https://github.com/es-shims/String.prototype.trimEnd/commit/eadaf2c83f2d791b54d80d7b30a9961ebc0f246f) +- Only apps should have lockfiles [`44d355f`](https://github.com/es-shims/String.prototype.trimEnd/commit/44d355f7dafcb0b51c5001824b07f7a2b9f1d06e) +- [actions] add automatic rebasing / merge commit blocking [`e78bf8e`](https://github.com/es-shims/String.prototype.trimEnd/commit/e78bf8e5fc04fcb3379dd1c98360d7df4f9ea7d6) +- [Tests] use shared travis-ci configs [`983c563`](https://github.com/es-shims/String.prototype.trimEnd/commit/983c5639efca2c9bb8b93ebbb917fbcb2561b94c) +- [meta] add `funding` field [`35139d6`](https://github.com/es-shims/String.prototype.trimEnd/commit/35139d6236ceacfc1501d08fb196d18a936ee583) +- [meta] fix non-updated version number [`a2d308b`](https://github.com/es-shims/String.prototype.trimEnd/commit/a2d308b99967ca427936c54747175794ca7336e1) + +## [v0.1.0](https://github.com/es-shims/String.prototype.trimEnd/compare/v0.0.1...v0.1.0) - 2017-12-19 + +### Commits + +- updated README [`f1c71a0`](https://github.com/es-shims/String.prototype.trimEnd/commit/f1c71a0a882e89e1c207ed2b316d91670be2b075) + +## v0.0.1 - 2017-12-19 + +### Commits + +- finished polyfill [`e58d550`](https://github.com/es-shims/String.prototype.trimEnd/commit/e58d550ab8695924ff4221ebe91f00f29801aa4b) +- created README file [`f78628a`](https://github.com/es-shims/String.prototype.trimEnd/commit/f78628ab123171f8b7759bba331d6a589702584f) +- Initial commit [`9199478`](https://github.com/es-shims/String.prototype.trimEnd/commit/9199478256da953e2f5bddfc4d82a161f4537e85) +- typo [`d1f4558`](https://github.com/es-shims/String.prototype.trimEnd/commit/d1f4558a51157833f14d8a424426d038d06576ce) diff --git a/node_modules/string.prototype.trimend/LICENSE b/node_modules/string.prototype.trimend/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e48a1b576c0f62b1e51dceec614a7f4a374d2d3d --- /dev/null +++ b/node_modules/string.prototype.trimend/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Khaled Al-Ansari + +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. diff --git a/node_modules/string.prototype.trimend/README.md b/node_modules/string.prototype.trimend/README.md new file mode 100644 index 0000000000000000000000000000000000000000..747c19607bcbf74754c4ed6c68633fd11da9b8f9 --- /dev/null +++ b/node_modules/string.prototype.trimend/README.md @@ -0,0 +1,44 @@ +# String.prototype.trimEnd [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +An ES2019-spec-compliant `String.prototype.trimEnd` shim. Invoke its "shim" method to shim `String.prototype.trimEnd` if it is unavailable. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](https://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. + +Most common usage: +```js +var trimEnd = require('string.prototype.trimend'); + +assert(trimEnd(' \t\na \t\n') === 'a \t\n'); + +if (!String.prototype.trimEnd) { + trimEnd.shim(); +} + +assert(trimEnd(' \t\na \t\n ') === ' \t\na \t\n '.trimEnd()); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/string.prototype.trimend +[npm-version-svg]: https://vb.teelaun.ch/es-shims/String.prototype.trimEnd.svg +[deps-svg]: https://david-dm.org/es-shims/String.prototype.trimEnd.svg +[deps-url]: https://david-dm.org/es-shims/String.prototype.trimEnd +[dev-deps-svg]: https://david-dm.org/es-shims/String.prototype.trimEnd/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/String.prototype.trimEnd#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/string.prototype.trimend.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/string.prototype.trimend.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/string.prototype.trimend.svg +[downloads-url]: https://npm-stat.com/charts.html?package=string.prototype.trimend +[codecov-image]: https://codecov.io/gh/es-shims/String.prototype.trimEnd/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/String.prototype.trimEnd/ +[actions-image]: https://img.shields.io/github/check-runs/es-shims/String.prototype.trimEnd/main +[actions-url]: https://github.com/es-shims/String.prototype.trimEnd/actions diff --git a/node_modules/string.prototype.trimend/auto.js b/node_modules/string.prototype.trimend/auto.js new file mode 100644 index 0000000000000000000000000000000000000000..8ebf606cb02ff3a8c6ef786afa37d21a19254f46 --- /dev/null +++ b/node_modules/string.prototype.trimend/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/string.prototype.trimend/implementation.js b/node_modules/string.prototype.trimend/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..2b6096b68c23d90a52cb2fc7024a615d5cf9d378 --- /dev/null +++ b/node_modules/string.prototype.trimend/implementation.js @@ -0,0 +1,22 @@ +'use strict'; + +var callBound = require('call-bound'); +var $slice = callBound('String.prototype.slice'); +var $charAt = callBound('String.prototype.charAt'); +var $test = callBound('RegExp.prototype.test'); + +var mvsIsWS = (/^\s$/).test('\u180E'); +/* eslint-disable no-control-regex */ +var isWhitespace = mvsIsWS + ? /* istanbul ignore next */ /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]$/ + : /[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]$/; +/* eslint-enable no-control-regex */ + +module.exports = function trimEnd() { + var S = $slice(this, 0); + var end = S.length; + while (end > 0 && $test(isWhitespace, $charAt(S, end - 1))) { + end -= 1; + } + return $slice(S, 0, end); +}; diff --git a/node_modules/string.prototype.trimend/index.js b/node_modules/string.prototype.trimend/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ce41c888ce172e8b900b10bb690ff25ded2754f9 --- /dev/null +++ b/node_modules/string.prototype.trimend/index.js @@ -0,0 +1,23 @@ +'use strict'; + +var callBind = require('call-bind'); +var define = require('define-properties'); +var RequireObjectCoercible = require('es-object-atoms/RequireObjectCoercible'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var bound = callBind(getPolyfill()); +var boundMethod = function trim(receiver) { + RequireObjectCoercible(receiver); + return bound(receiver); +}; + +define(boundMethod, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = boundMethod; diff --git a/node_modules/string.prototype.trimend/package.json b/node_modules/string.prototype.trimend/package.json new file mode 100644 index 0000000000000000000000000000000000000000..0e144978c2d9780033d2d36a8722c2d922c45187 --- /dev/null +++ b/node_modules/string.prototype.trimend/package.json @@ -0,0 +1,82 @@ +{ + "name": "string.prototype.trimend", + "version": "1.0.10", + "author": "Jordan Harband ", + "contributors": [ + "Jordan Harband ", + "Khaled Al-Ansari " + ], + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "ES2019 spec-compliant String.prototype.trimEnd shim.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "lint": "eslint --ext=js,mjs .", + "postlint": "es-shim-api --bound", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "npx npm@'>= 10.2' audit --production", + "tests-only": "nyc tape 'test/**/*.js'", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/es-shims/String.prototype.trimEnd.git" + }, + "keywords": [ + "es6", + "es7", + "es8", + "javascript", + "prototype", + "polyfill", + "utility", + "trim", + "trimLeft", + "trimRight", + "trimStart", + "trimEnd", + "tc39" + ], + "dependencies": { + "call-bind": "^1.0.9", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.2" + }, + "devDependencies": { + "@es-shims/api": "^2.5.1", + "@ljharb/eslint-config": "^22.2.3", + "auto-changelog": "^2.6.0", + "eslint": "^8.57.1", + "functions-have-names": "^1.2.3", + "has-strict-mode": "^1.1.0", + "in-publish": "^2.0.1", + "npmignore": "^0.3.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/string.prototype.trimend/polyfill.js b/node_modules/string.prototype.trimend/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..0fa4f708357ea760011888d146920678639f46c5 --- /dev/null +++ b/node_modules/string.prototype.trimend/polyfill.js @@ -0,0 +1,15 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = function getPolyfill() { + if (!String.prototype.trimEnd && !String.prototype.trimRight) { + return implementation; + } + var zeroWidthSpace = '\u200b'; + var trimmed = zeroWidthSpace.trimEnd ? zeroWidthSpace.trimEnd() : zeroWidthSpace.trimRight(); + if (trimmed !== zeroWidthSpace) { + return implementation; + } + return String.prototype.trimEnd || String.prototype.trimRight; +}; diff --git a/node_modules/string.prototype.trimend/shim.js b/node_modules/string.prototype.trimend/shim.js new file mode 100644 index 0000000000000000000000000000000000000000..5a8f4773b0a2d12fae6c2823a8688ac73cec4b6b --- /dev/null +++ b/node_modules/string.prototype.trimend/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +module.exports = function shimTrimEnd() { + var polyfill = getPolyfill(); + define( + String.prototype, + { trimEnd: polyfill }, + { trimEnd: function () { return String.prototype.trimEnd !== polyfill; } } + ); + return polyfill; +}; diff --git a/node_modules/string.prototype.trimend/test/implementation.js b/node_modules/string.prototype.trimend/test/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..7fdf95b7da1a541ef76ccf4f576a323b2c97097b --- /dev/null +++ b/node_modules/string.prototype.trimend/test/implementation.js @@ -0,0 +1,20 @@ +'use strict'; + +var implementation = require('../implementation'); +var callBind = require('call-bind'); +var test = require('tape'); +var hasStrictMode = require('has-strict-mode')(); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', { skip: !hasStrictMode }, function (st) { + /* eslint no-useless-call: 0 */ + st['throws'](function () { implementation.call(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { implementation.call(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(implementation), t); + + t.end(); +}); diff --git a/node_modules/string.prototype.trimend/test/index.js b/node_modules/string.prototype.trimend/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2ee8f6703ccd64a800e358bad5a1b60a4fe026f5 --- /dev/null +++ b/node_modules/string.prototype.trimend/test/index.js @@ -0,0 +1,17 @@ +'use strict'; + +var trimEnd = require('../'); +var test = require('tape'); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { trimEnd(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { trimEnd(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(trimEnd, t); + + t.end(); +}); diff --git a/node_modules/string.prototype.trimend/test/shimmed.js b/node_modules/string.prototype.trimend/test/shimmed.js new file mode 100644 index 0000000000000000000000000000000000000000..1a01ceb1bcf4cc6176712142da200d0852819c79 --- /dev/null +++ b/node_modules/string.prototype.trimend/test/shimmed.js @@ -0,0 +1,36 @@ +'use strict'; + +require('../auto'); + +var runTests = require('./tests'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +test('shimmed', function (t) { + t.equal(String.prototype.trimEnd.length, 0, 'String#trimEnd has a length of 0'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal((/^(?:trimRight|trimEnd)$/).test(String.prototype.trimEnd.name), true, 'String#trimEnd has name "trimRight" or "trimEnd"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(String.prototype, 'trimEnd'), 'String#trimEnd is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad string/this value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return String.prototype.trimEnd.call(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return String.prototype.trimEnd.call(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(String.prototype.trimEnd), t); + + t.end(); +}); diff --git a/node_modules/string.prototype.trimend/test/tests.js b/node_modules/string.prototype.trimend/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..1179938bede301dd11e91b19b96baf7f2e1f593c --- /dev/null +++ b/node_modules/string.prototype.trimend/test/tests.js @@ -0,0 +1,45 @@ +'use strict'; + +module.exports = function (trimEnd, t) { + t.test('normal cases', function (st) { + st.equal(trimEnd(' \t\na \t\n'), ' \t\na', 'strips whitespace off the left side'); + st.equal(trimEnd('a'), 'a', 'noop when no whitespace'); + + var allWhitespaceChars = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + st.equal(trimEnd(allWhitespaceChars + 'a' + allWhitespaceChars), allWhitespaceChars + 'a', 'all expected whitespace chars are trimmed'); + + st.end(); + }); + + t.test('pathological case', function (st) { + var manySpaces = new Array(100001).join(' '); + var input = 'A' + manySpaces + 'A' + manySpaces; + + var start = Date.now(); + var result = trimEnd(input); + var elapsed = Date.now() - start; + + st.equal(result, 'A' + manySpaces + 'A', 'trailing whitespace is trimmed; internal whitespace is preserved'); + st.ok(elapsed < 250, 'completes in linear time (took ' + elapsed + 'ms)'); + + st.end(); + }); + + // see https://codeblog.jonskeet.uk/2014/12/01/when-is-an-identifier-not-an-identifier-attack-of-the-mongolian-vowel-separator/ + var mongolianVowelSeparator = '\u180E'; + var mvsIsWS = (/^\s$/).test(mongolianVowelSeparator); + t.test('mongolian vowel separator: unicode >= 4 && < 6.3', function (st) { + st.equal( + trimEnd(mongolianVowelSeparator + 'a' + mongolianVowelSeparator), + mongolianVowelSeparator + 'a' + (mvsIsWS ? '' : mongolianVowelSeparator), + 'mongolian vowel separator is ' + (mvsIsWS ? '' : 'not ') + 'whitespace' + ); + st.end(); + }); + + t.test('zero-width spaces', function (st) { + var zeroWidth = '\u200b'; + st.equal(trimEnd(zeroWidth), zeroWidth, 'zero width space does not trim'); + st.end(); + }); +}; diff --git a/node_modules/string.prototype.trimstart/.editorconfig b/node_modules/string.prototype.trimstart/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..bc228f8269443bf772b437890dde7756a3e8a894 --- /dev/null +++ b/node_modules/string.prototype.trimstart/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/string.prototype.trimstart/.eslintrc b/node_modules/string.prototype.trimstart/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..8056b20c9f21cb06262631bb70c27ab43fef655f --- /dev/null +++ b/node_modules/string.prototype.trimstart/.eslintrc @@ -0,0 +1,24 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "id-length": "off", + "new-cap": ["error", { + "capIsNewExceptions": [ + "RequireObjectCoercible", + ], + }], + }, + + "overrides": [ + { + "files": "test/**", + "rules": { + "id-length": 0, + "no-invalid-this": 1, + }, + }, + ], +} diff --git a/node_modules/string.prototype.trimstart/.nycrc b/node_modules/string.prototype.trimstart/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/string.prototype.trimstart/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/string.prototype.trimstart/CHANGELOG.md b/node_modules/string.prototype.trimstart/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..e7701e1be7a2ee5d30d0aa549e9fe4d9f61589eb --- /dev/null +++ b/node_modules/string.prototype.trimstart/CHANGELOG.md @@ -0,0 +1,118 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.8](https://github.com/es-shims/String.prototype.trimStart/compare/v1.0.7...v1.0.8) - 2024-03-21 + +### Commits + +- [actions] use reusable workflows [`d139c11`](https://github.com/es-shims/String.prototype.trimStart/commit/d139c119ba5003936649741fae52b28080794dd3) +- [Dev Deps] update `aud`, `npmignore`, `tape` [`16ff815`](https://github.com/es-shims/String.prototype.trimStart/commit/16ff81546c62ac3159fdf223cd1b035729fd55f0) +- [Deps] update `call-bind`, `define-properties` [`8dd308d`](https://github.com/es-shims/String.prototype.trimStart/commit/8dd308dd225ea3cb6a4d2c9662e435101367a5ef) +- [Refactor] use `es-object-atoms` instead of `es-abstract` [`4868f56`](https://github.com/es-shims/String.prototype.trimStart/commit/4868f566f8052ab7e28ce733ecc62b56f743f7fc) +- [meta] add missing `engines.node` [`8c1cce6`](https://github.com/es-shims/String.prototype.trimStart/commit/8c1cce612e4e1fdd1e5172c9e508a88abd3e6a5c) + +## [v1.0.7](https://github.com/es-shims/String.prototype.trimStart/compare/v1.0.6...v1.0.7) - 2023-09-04 + +### Commits + +- [Dev Deps] update `@es-shims/api`, `@ljharb/eslint-config`, `aud`, `tape` [`58e7aa6`](https://github.com/es-shims/String.prototype.trimStart/commit/58e7aa63b702f4494b89b8723b585bab5899a304) +- [Deps] update `define-properties`, `es-abstract` [`8d9a7bf`](https://github.com/es-shims/String.prototype.trimStart/commit/8d9a7bf123f320799211dd57aa0c832aaafb8a19) + +## [v1.0.6](https://github.com/es-shims/String.prototype.trimStart/compare/v1.0.5...v1.0.6) - 2022-11-07 + +### Commits + +- [meta] use `npmignore` to autogenerate an npmignore file [`0838ae4`](https://github.com/es-shims/String.prototype.trimStart/commit/0838ae4ed948df470185afbeea4296f5c5ecd759) +- [actions] update rebase action to use reusable workflow [`d6bb784`](https://github.com/es-shims/String.prototype.trimStart/commit/d6bb78400a00459e9ab0b28f433c45804a65184d) +- [Dev Deps] update `aud`, `tape` [`8734d9a`](https://github.com/es-shims/String.prototype.trimStart/commit/8734d9a616c6aca9ec7f0c8819e66c2496deb32e) +- [Deps] update `es-abstract` [`30f593f`](https://github.com/es-shims/String.prototype.trimStart/commit/30f593f3febf6d8d9b3d5605174b437fed9cbb3a) + +## [v1.0.5](https://github.com/es-shims/String.prototype.trimStart/compare/v1.0.4...v1.0.5) - 2022-05-02 + +### Commits + +- [actions] reuse common workflows [`61d4009`](https://github.com/es-shims/String.prototype.trimStart/commit/61d40098a96b3dcc6cf963c9d03dd1b23b6eb13d) +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`bfe39c4`](https://github.com/es-shims/String.prototype.trimStart/commit/bfe39c498e26a4ad75c64cce27ff3df9bfef2cc1) +- [Fix] ensure main entry point properly checks the receiver in ES3 engines [`36e3730`](https://github.com/es-shims/String.prototype.trimStart/commit/36e37307bb06fb5dc34d861a4bf6f7db931340d9) +- [Fix] as of unicode v6, the mongolian vowel separator is no longer whitespace [`4f77eed`](https://github.com/es-shims/String.prototype.trimStart/commit/4f77eed5aa64e6f781310847d7831563fce90f5c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `safe-publish-latest`, `tape` [`59fcb99`](https://github.com/es-shims/String.prototype.trimStart/commit/59fcb995ef8d4723a83e28d46dbe41a14253b681) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `functions-have-names`, `tape` [`486ffcf`](https://github.com/es-shims/String.prototype.trimStart/commit/486ffcfa93c75516601169a3973b81fdfeb7de8b) +- [actions] update codecov uploader [`b33ac48`](https://github.com/es-shims/String.prototype.trimStart/commit/b33ac48ccc86f6b894d8fde5162bd1c806904972) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `@es-shims/api`, `aud`, `auto-changelog`, `tape` [`3c89fa5`](https://github.com/es-shims/String.prototype.trimStart/commit/3c89fa571d1c4b8894230d93caaf3b3d9885534d) +- [readme] add github actions/codecov badges [`00be6b3`](https://github.com/es-shims/String.prototype.trimStart/commit/00be6b34fdd989950b934b4471087362b78d4b0c) +- [Dev Deps] update `eslint`, `tape` [`13a08f5`](https://github.com/es-shims/String.prototype.trimStart/commit/13a08f578c53cf5f129fb6ebe486e8bbcc40c14e) +- [actions] update workflows [`6ac576d`](https://github.com/es-shims/String.prototype.trimStart/commit/6ac576dde99f73d19492777efed29ec069e89bf1) +- [meta] use `prepublishOnly` script for npm 7+ [`fa382ca`](https://github.com/es-shims/String.prototype.trimStart/commit/fa382caa5c8e9a868572605ce215a3db1dc9ef21) +- [Deps] update `define-properties` [`d57bffe`](https://github.com/es-shims/String.prototype.trimStart/commit/d57bffef7d89384c8888627c5ee33b80e24d54e0) + +## [v1.0.4](https://github.com/es-shims/String.prototype.trimStart/compare/v1.0.3...v1.0.4) - 2021-02-23 + +### Commits + +- [meta] do not publish github action workflow files [`9c434ec`](https://github.com/es-shims/String.prototype.trimStart/commit/9c434eceb50141cf36e8e65f514226b0b547b568) +- [readme] remove travis badge [`7843160`](https://github.com/es-shims/String.prototype.trimStart/commit/7843160a3e8feaa2213feb0da9c5ad7d9bf21b59) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `functions-have-names`, `has-strict-mode`, `tape` [`8b52646`](https://github.com/es-shims/String.prototype.trimStart/commit/8b52646510aea20473da5491fe0876117a2251b1) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`badeda2`](https://github.com/es-shims/String.prototype.trimStart/commit/badeda2b01d2e266e4d1c2e7dc0e4fca0f066f3e) +- [Tests] increase coverage [`bf8777d`](https://github.com/es-shims/String.prototype.trimStart/commit/bf8777d54c4b05c093559021cfaf0670306120f8) +- [actions] update workflows [`61be1c6`](https://github.com/es-shims/String.prototype.trimStart/commit/61be1c649ae859faa40286e57fa22cef65ae1229) +- [meta] gitignore coverage output [`c9c98d7`](https://github.com/es-shims/String.prototype.trimStart/commit/c9c98d75d7708e8906a39b55a0ad7a0ed6a9e4b0) +- [Deps] update `call-bind` [`c8645e8`](https://github.com/es-shims/String.prototype.trimStart/commit/c8645e89f9ace7681660ba66c724cf00c798f3d4) + +## [v1.0.3](https://github.com/es-shims/String.prototype.trimStart/compare/v1.0.2...v1.0.3) - 2020-11-21 + +### Commits + +- [Tests] migrate tests to Github Actions [`fbc7519`](https://github.com/es-shims/String.prototype.trimStart/commit/fbc7519cce2b5bfff9fe28dea96fb5f6f82e19fd) +- [Tests] add `implementation` test; run `es-shim-api` in postlint; use `tape` runner [`3c9330b`](https://github.com/es-shims/String.prototype.trimStart/commit/3c9330be9ad02497f78ff0fd94b7c918c3a4bc21) +- [Tests] run `nyc` on all tests [`52229ca`](https://github.com/es-shims/String.prototype.trimStart/commit/52229ca28426be516c3826743e417be85144673e) +- [Deps] replace `es-abstract` with `call-bind` [`5e5068d`](https://github.com/es-shims/String.prototype.trimStart/commit/5e5068d2cc85d0a6f2a441ea984521ee70470537) +- [Dev Deps] update `eslint`, `aud`; add `safe-publish-latest` [`42a853e`](https://github.com/es-shims/String.prototype.trimStart/commit/42a853e2cb419378085098cb66e421ee94eed3ab) + +## [v1.0.2](https://github.com/es-shims/String.prototype.trimStart/compare/v1.0.1...v1.0.2) - 2020-10-20 + +### Commits + +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`d032b38`](https://github.com/es-shims/String.prototype.trimStart/commit/d032b38aac7e9ebae7bf5c4195492c508af2815a) +- [actions] add "Allow Edits" workflow [`83e30ba`](https://github.com/es-shims/String.prototype.trimStart/commit/83e30bac01572b6dba6358fec6e339c55dc431c9) +- [Deps] update `es-abstract` [`707d85d`](https://github.com/es-shims/String.prototype.trimStart/commit/707d85d827d9c537a144f199fdecc47edaade1cd) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`096c6d9`](https://github.com/es-shims/String.prototype.trimStart/commit/096c6d9dc142286c750da7024e7a88ed698a4953) + +## [v1.0.1](https://github.com/es-shims/String.prototype.trimStart/compare/v1.0.0...v1.0.1) - 2020-04-09 + +### Commits + +- [meta] add some missing repo metadata [`3385da3`](https://github.com/es-shims/String.prototype.trimStart/commit/3385da3bbb87819de11a869981ca954887a6a092) +- [Dev Deps] update `auto-changelog` [`879377d`](https://github.com/es-shims/String.prototype.trimStart/commit/879377df9c1ff97d8f0b3eac800683f1d68a304c) + +## [v1.0.0](https://github.com/es-shims/String.prototype.trimStart/compare/v0.1.0...v1.0.0) - 2020-03-30 + +### Commits + +- [Breaking] convert to es-shim API [`970922c`](https://github.com/es-shims/String.prototype.trimStart/commit/970922c494c78b033c351c77f61a8aefd49c30d9) +- [meta] add `auto-changelog` [`ff30c09`](https://github.com/es-shims/String.prototype.trimStart/commit/ff30c0996289113d2c3dbbfca7e280ff151bf36d) +- [meta] update readme [`816291d`](https://github.com/es-shims/String.prototype.trimStart/commit/816291d01e0eaf85da9b732c179cfb2454bd282e) +- [Tests] add `npm run lint` [`3341104`](https://github.com/es-shims/String.prototype.trimStart/commit/3341104450bc6ac84f3b70a6d6c0fbeb4df5131e) +- Only apps should have lockfiles [`f008df7`](https://github.com/es-shims/String.prototype.trimStart/commit/f008df73fbf3dcf8dfad6d5cad86de7050d0ae09) +- [actions] add automatic rebasing / merge commit blocking [`e5ba35c`](https://github.com/es-shims/String.prototype.trimStart/commit/e5ba35c1a14fcf652336cc9c4be49d232981161e) +- [Tests] use shared travis-ci configs [`46516b1`](https://github.com/es-shims/String.prototype.trimStart/commit/46516b137a8c07ed5807d751bd61199688ef9baa) +- [meta] add `funding` field [`34ae856`](https://github.com/es-shims/String.prototype.trimStart/commit/34ae8563f115bd4a5e5f5d2d786c0fa0a420fa2a) +- [meta] fix non-updated version number [`3b0e262`](https://github.com/es-shims/String.prototype.trimStart/commit/3b0e262e2f4eeee2e1b99fe890f8ca17bed8f2fd) + +## [v0.1.0](https://github.com/es-shims/String.prototype.trimStart/compare/v0.0.1...v0.1.0) - 2017-12-19 + +### Commits + +- updated README [`ab2f6ac`](https://github.com/es-shims/String.prototype.trimStart/commit/ab2f6ac8813ed336a0f2dc3aa8cdb52f4d52814b) + +## v0.0.1 - 2017-12-19 + +### Commits + +- finished polyfill [`1c7ca20`](https://github.com/es-shims/String.prototype.trimStart/commit/1c7ca2043e3383b6e743870bc622ad4a38477147) +- created README file: [`192ecad`](https://github.com/es-shims/String.prototype.trimStart/commit/192ecaded4e0d5baaa65cd41e590b8d837520d44) +- Initial commit [`14044f8`](https://github.com/es-shims/String.prototype.trimStart/commit/14044f8a0fe1d155fe7403a8327bdbaf135da2d6) +- updated README [`d4fb6be`](https://github.com/es-shims/String.prototype.trimStart/commit/d4fb6be15455dd68fc4b306bee1d30dd4afc96e7) diff --git a/node_modules/string.prototype.trimstart/LICENSE b/node_modules/string.prototype.trimstart/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e48a1b576c0f62b1e51dceec614a7f4a374d2d3d --- /dev/null +++ b/node_modules/string.prototype.trimstart/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Khaled Al-Ansari + +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. diff --git a/node_modules/string.prototype.trimstart/README.md b/node_modules/string.prototype.trimstart/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5ec76138e80f7d588eeb03f51ff1e48676ea2bb4 --- /dev/null +++ b/node_modules/string.prototype.trimstart/README.md @@ -0,0 +1,46 @@ +# String.prototype.trimStart [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +An ES2019-spec-compliant `String.prototype.trimStart` shim. Invoke its "shim" method to shim `String.prototype.trimStart` if it is unavailable. + +This package implements the [es-shim API](https://github.com/es-shims/api) interface. It works in an ES3-supported environment and complies with the [spec](https://www.ecma-international.org/ecma-262/6.0/#sec-object.assign). In an ES6 environment, it will also work properly with `Symbol`s. + +Most common usage: +```js +var trimStart = require('string.prototype.trimstart'); + +assert(trimStart(' \t\na \t\n') === 'a \t\n'); + +if (!String.prototype.trimStart) { + trimStart.shim(); +} + +assert(trimStart(' \t\na \t\n') === ' \t\na \t\n'.trimStart()); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.com/package/string.prototype.trimstart +[npm-version-svg]: https://vb.teelaun.ch/es-shims/String.prototype.trimStart.svg +[deps-svg]: https://david-dm.org/es-shims/String.prototype.trimStart.svg +[deps-url]: https://david-dm.org/es-shims/String.prototype.trimStart +[dev-deps-svg]: https://david-dm.org/es-shims/String.prototype.trimStart/dev-status.svg +[dev-deps-url]: https://david-dm.org/es-shims/String.prototype.trimStart#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/string.prototype.trimstart.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/string.prototype.trimstart.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/string.prototype.trimstart.svg +[downloads-url]: https://npm-stat.com/charts.html?package=string.prototype.trimstart +[codecov-image]: https://codecov.io/gh/es-shims/String.prototype.trimStart/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/es-shims/String.prototype.trimStart/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/es-shims/String.prototype.trimStart +[actions-url]: https://github.com/es-shims/String.prototype.trimStart/actions diff --git a/node_modules/string.prototype.trimstart/auto.js b/node_modules/string.prototype.trimstart/auto.js new file mode 100644 index 0000000000000000000000000000000000000000..8ebf606cb02ff3a8c6ef786afa37d21a19254f46 --- /dev/null +++ b/node_modules/string.prototype.trimstart/auto.js @@ -0,0 +1,3 @@ +'use strict'; + +require('./shim')(); diff --git a/node_modules/string.prototype.trimstart/implementation.js b/node_modules/string.prototype.trimstart/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..882e7111e1e10637b214dc5036c8e7972874ae86 --- /dev/null +++ b/node_modules/string.prototype.trimstart/implementation.js @@ -0,0 +1,15 @@ +'use strict'; + +var callBound = require('call-bind/callBound'); +var $replace = callBound('String.prototype.replace'); + +var mvsIsWS = (/^\s$/).test('\u180E'); +/* eslint-disable no-control-regex */ +var startWhitespace = mvsIsWS + ? /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/ + : /^[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF]+/; +/* eslint-enable no-control-regex */ + +module.exports = function trimStart() { + return $replace(this, startWhitespace, ''); +}; diff --git a/node_modules/string.prototype.trimstart/index.js b/node_modules/string.prototype.trimstart/index.js new file mode 100644 index 0000000000000000000000000000000000000000..ce41c888ce172e8b900b10bb690ff25ded2754f9 --- /dev/null +++ b/node_modules/string.prototype.trimstart/index.js @@ -0,0 +1,23 @@ +'use strict'; + +var callBind = require('call-bind'); +var define = require('define-properties'); +var RequireObjectCoercible = require('es-object-atoms/RequireObjectCoercible'); + +var implementation = require('./implementation'); +var getPolyfill = require('./polyfill'); +var shim = require('./shim'); + +var bound = callBind(getPolyfill()); +var boundMethod = function trim(receiver) { + RequireObjectCoercible(receiver); + return bound(receiver); +}; + +define(boundMethod, { + getPolyfill: getPolyfill, + implementation: implementation, + shim: shim +}); + +module.exports = boundMethod; diff --git a/node_modules/string.prototype.trimstart/package.json b/node_modules/string.prototype.trimstart/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ceefb8b3f26d3cb836e6d34a4c20186906577539 --- /dev/null +++ b/node_modules/string.prototype.trimstart/package.json @@ -0,0 +1,82 @@ +{ + "name": "string.prototype.trimstart", + "version": "1.0.8", + "author": "Jordan Harband ", + "contributors": [ + "Jordan Harband ", + "Khaled Al-Ansari " + ], + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "description": "ES2019 spec-compliant String.prototype.trimStart shim.", + "license": "MIT", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "lint": "eslint --ext=js,mjs .", + "postlint": "es-shim-api --bound", + "pretest": "npm run lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "nyc tape 'test/**/*.js'", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/es-shims/String.prototype.trimStart.git" + }, + "keywords": [ + "es6", + "es7", + "es8", + "javascript", + "prototype", + "polyfill", + "utility", + "trim", + "trimLeft", + "trimRight", + "trimStart", + "trimEnd", + "tc39" + ], + "devDependencies": { + "@es-shims/api": "^2.4.2", + "@ljharb/eslint-config": "^21.1.0", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "eslint": "=8.8.0", + "functions-have-names": "^1.2.3", + "has-strict-mode": "^1.0.1", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.5" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/string.prototype.trimstart/polyfill.js b/node_modules/string.prototype.trimstart/polyfill.js new file mode 100644 index 0000000000000000000000000000000000000000..9adaccd528b9fc2503cb5af8cce95dea8fa38132 --- /dev/null +++ b/node_modules/string.prototype.trimstart/polyfill.js @@ -0,0 +1,15 @@ +'use strict'; + +var implementation = require('./implementation'); + +module.exports = function getPolyfill() { + if (!String.prototype.trimStart && !String.prototype.trimLeft) { + return implementation; + } + var zeroWidthSpace = '\u200b'; + var trimmed = zeroWidthSpace.trimStart ? zeroWidthSpace.trimStart() : zeroWidthSpace.trimLeft(); + if (trimmed !== zeroWidthSpace) { + return implementation; + } + return String.prototype.trimStart || String.prototype.trimLeft; +}; diff --git a/node_modules/string.prototype.trimstart/shim.js b/node_modules/string.prototype.trimstart/shim.js new file mode 100644 index 0000000000000000000000000000000000000000..5ea6dfdcf9ddeaf199207d42d7802bbe4bfa65d9 --- /dev/null +++ b/node_modules/string.prototype.trimstart/shim.js @@ -0,0 +1,14 @@ +'use strict'; + +var define = require('define-properties'); +var getPolyfill = require('./polyfill'); + +module.exports = function shimTrimStart() { + var polyfill = getPolyfill(); + define( + String.prototype, + { trimStart: polyfill }, + { trimStart: function () { return String.prototype.trimStart !== polyfill; } } + ); + return polyfill; +}; diff --git a/node_modules/string.prototype.trimstart/test/implementation.js b/node_modules/string.prototype.trimstart/test/implementation.js new file mode 100644 index 0000000000000000000000000000000000000000..7fdf95b7da1a541ef76ccf4f576a323b2c97097b --- /dev/null +++ b/node_modules/string.prototype.trimstart/test/implementation.js @@ -0,0 +1,20 @@ +'use strict'; + +var implementation = require('../implementation'); +var callBind = require('call-bind'); +var test = require('tape'); +var hasStrictMode = require('has-strict-mode')(); +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', { skip: !hasStrictMode }, function (st) { + /* eslint no-useless-call: 0 */ + st['throws'](function () { implementation.call(undefined); }, TypeError, 'undefined is not an object'); + st['throws'](function () { implementation.call(null); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(implementation), t); + + t.end(); +}); diff --git a/node_modules/string.prototype.trimstart/test/index.js b/node_modules/string.prototype.trimstart/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..baff6b59b825c9cb2403f1368bdf11c8008e63ba --- /dev/null +++ b/node_modules/string.prototype.trimstart/test/index.js @@ -0,0 +1,18 @@ +'use strict'; + +var trimStart = require('../'); +var test = require('tape'); + +var runTests = require('./tests'); + +test('as a function', function (t) { + t.test('bad array/this value', function (st) { + st['throws'](function () { trimStart(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { trimStart(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(trimStart, t); + + t.end(); +}); diff --git a/node_modules/string.prototype.trimstart/test/shimmed.js b/node_modules/string.prototype.trimstart/test/shimmed.js new file mode 100644 index 0000000000000000000000000000000000000000..bfdbe486c29623f7dd51e3dbc757a844b6b23294 --- /dev/null +++ b/node_modules/string.prototype.trimstart/test/shimmed.js @@ -0,0 +1,36 @@ +'use strict'; + +require('../auto'); + +var runTests = require('./tests'); + +var test = require('tape'); +var defineProperties = require('define-properties'); +var callBind = require('call-bind'); +var isEnumerable = Object.prototype.propertyIsEnumerable; +var functionsHaveNames = require('functions-have-names')(); + +test('shimmed', function (t) { + t.equal(String.prototype.trimStart.length, 0, 'String#trimStart has a length of 0'); + t.test('Function name', { skip: !functionsHaveNames }, function (st) { + st.equal((/^(?:trimLeft|trimStart)$/).test(String.prototype.trimStart.name), true, 'String#trimStart has name "trimLeft" or "trimStart"'); + st.end(); + }); + + t.test('enumerability', { skip: !defineProperties.supportsDescriptors }, function (et) { + et.equal(false, isEnumerable.call(String.prototype, 'trimStart'), 'String#trimStart is not enumerable'); + et.end(); + }); + + var supportsStrictMode = (function () { return typeof this === 'undefined'; }()); + + t.test('bad string/this value', { skip: !supportsStrictMode }, function (st) { + st['throws'](function () { return String.prototype.trimStart.call(undefined, 'a'); }, TypeError, 'undefined is not an object'); + st['throws'](function () { return String.prototype.trimStart.call(null, 'a'); }, TypeError, 'null is not an object'); + st.end(); + }); + + runTests(callBind(String.prototype.trimStart), t); + + t.end(); +}); diff --git a/node_modules/string.prototype.trimstart/test/tests.js b/node_modules/string.prototype.trimstart/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..526aac144d6cfddbb657570efd5e5ca20f81c5c8 --- /dev/null +++ b/node_modules/string.prototype.trimstart/test/tests.js @@ -0,0 +1,31 @@ +'use strict'; + +module.exports = function (trimStart, t) { + t.test('normal cases', function (st) { + st.equal(trimStart(' \t\na \t\n'), 'a \t\n', 'strips whitespace off the left side'); + st.equal(trimStart('a'), 'a', 'noop when no whitespace'); + + var allWhitespaceChars = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; + st.equal(trimStart(allWhitespaceChars + 'a' + allWhitespaceChars), 'a' + allWhitespaceChars, 'all expected whitespace chars are trimmed'); + + st.end(); + }); + + // see https://codeblog.jonskeet.uk/2014/12/01/when-is-an-identifier-not-an-identifier-attack-of-the-mongolian-vowel-separator/ + var mongolianVowelSeparator = '\u180E'; + var mvsIsWS = (/^\s$/).test(mongolianVowelSeparator); + t.test('mongolian vowel separator: unicode >= 4 && < 6.3', function (st) { + st.equal( + trimStart(mongolianVowelSeparator + 'a' + mongolianVowelSeparator), + (mvsIsWS ? '' : mongolianVowelSeparator) + 'a' + mongolianVowelSeparator, + 'mongolian vowel separator is ' + (mvsIsWS ? '' : 'not ') + 'whitespace' + ); + st.end(); + }); + + t.test('zero-width spaces', function (st) { + var zeroWidth = '\u200b'; + st.equal(trimStart(zeroWidth), zeroWidth, 'zero width space does not trim'); + st.end(); + }); +}; diff --git a/node_modules/string_decoder/LICENSE b/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..778edb20730ef48c01002248f4d51e7752c13487 --- /dev/null +++ b/node_modules/string_decoder/LICENSE @@ -0,0 +1,48 @@ +Node.js is licensed for use as follows: + +""" +Copyright Node.js contributors. All rights reserved. + +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. +""" + +This license applies to parts of Node.js originating from the +https://github.com/joyent/node repository: + +""" +Copyright Joyent, Inc. and other Node contributors. All rights reserved. +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. +""" + diff --git a/node_modules/string_decoder/README.md b/node_modules/string_decoder/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5fd58315ed588027742dde690a31cd0a2610649d --- /dev/null +++ b/node_modules/string_decoder/README.md @@ -0,0 +1,47 @@ +# string_decoder + +***Node-core v8.9.4 string_decoder for userland*** + + +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/) + + +```bash +npm install --save string_decoder +``` + +***Node-core string_decoder for userland*** + +This package is a mirror of the string_decoder implementation in Node-core. + +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/). + +As of version 1.0.0 **string_decoder** uses semantic versioning. + +## Previous versions + +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. + +## Update + +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version. + +## Streams Working Group + +`string_decoder` is maintained by the Streams Working Group, which +oversees the development and maintenance of the Streams API within +Node.js. The responsibilities of the Streams Working Group include: + +* Addressing stream issues on the Node.js issue tracker. +* Authoring and editing stream documentation within the Node.js project. +* Reviewing changes to stream subclasses within the Node.js project. +* Redirecting changes to streams from the Node.js project to this + project. +* Assisting in the implementation of stream providers within Node.js. +* Recommending versions of `readable-stream` to be included in Node.js. +* Messaging about the future of streams to give the community advance + notice of changes. + +See [readable-stream](https://github.com/nodejs/readable-stream) for +more details. diff --git a/node_modules/string_decoder/lib/string_decoder.js b/node_modules/string_decoder/lib/string_decoder.js new file mode 100644 index 0000000000000000000000000000000000000000..2e89e63f7933e42b8ba543ede35d2a8fa3e4f100 --- /dev/null +++ b/node_modules/string_decoder/lib/string_decoder.js @@ -0,0 +1,296 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// 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. + +'use strict'; + +/**/ + +var Buffer = require('safe-buffer').Buffer; +/**/ + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} \ No newline at end of file diff --git a/node_modules/string_decoder/package.json b/node_modules/string_decoder/package.json new file mode 100644 index 0000000000000000000000000000000000000000..b2bb141160cad31581cf39ee21813196ad13a5cd --- /dev/null +++ b/node_modules/string_decoder/package.json @@ -0,0 +1,34 @@ +{ + "name": "string_decoder", + "version": "1.3.0", + "description": "The string_decoder module from Node core", + "main": "lib/string_decoder.js", + "files": [ + "lib" + ], + "dependencies": { + "safe-buffer": "~5.2.0" + }, + "devDependencies": { + "babel-polyfill": "^6.23.0", + "core-util-is": "^1.0.2", + "inherits": "^2.0.3", + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/parallel/*.js && node test/verify-dependencies", + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodejs/string_decoder.git" + }, + "homepage": "https://github.com/nodejs/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT" +} diff --git a/node_modules/stringify-entities/index.d.ts b/node_modules/stringify-entities/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..512bf89bcffbcdb12206047028b4660157acf3a2 --- /dev/null +++ b/node_modules/stringify-entities/index.d.ts @@ -0,0 +1,3 @@ +export * from "./lib/index.js"; +export type LightOptions = import('./lib/index.js').LightOptions; +export type Options = import('./lib/index.js').Options; diff --git a/node_modules/stringify-entities/index.js b/node_modules/stringify-entities/index.js new file mode 100644 index 0000000000000000000000000000000000000000..2834f13d27c9b830adf90e7850d9242cc66fa9c8 --- /dev/null +++ b/node_modules/stringify-entities/index.js @@ -0,0 +1,6 @@ +/** + * @typedef {import('./lib/index.js').LightOptions} LightOptions + * @typedef {import('./lib/index.js').Options} Options + */ + +export * from './lib/index.js' diff --git a/node_modules/stringify-entities/lib/constant/dangerous.d.ts b/node_modules/stringify-entities/lib/constant/dangerous.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c21102b60c049b2fe890d4af35fafcfb30984abc --- /dev/null +++ b/node_modules/stringify-entities/lib/constant/dangerous.d.ts @@ -0,0 +1,7 @@ +/** + * List of legacy (that don’t need a trailing `;`) named references which could, + * depending on what follows them, turn into a different meaning + * + * @type {Array} + */ +export const dangerous: Array; diff --git a/node_modules/stringify-entities/lib/constant/dangerous.js b/node_modules/stringify-entities/lib/constant/dangerous.js new file mode 100644 index 0000000000000000000000000000000000000000..2bbf46476100d47f3250f0874be8d4258a90bb27 --- /dev/null +++ b/node_modules/stringify-entities/lib/constant/dangerous.js @@ -0,0 +1,16 @@ +/** + * List of legacy (that don’t need a trailing `;`) named references which could, + * depending on what follows them, turn into a different meaning + * + * @type {Array} + */ +export const dangerous = [ + 'cent', + 'copy', + 'divide', + 'gt', + 'lt', + 'not', + 'para', + 'times' +] diff --git a/node_modules/stringify-entities/lib/core.d.ts b/node_modules/stringify-entities/lib/core.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b425411211339e236e9a852392481543867d9b98 --- /dev/null +++ b/node_modules/stringify-entities/lib/core.d.ts @@ -0,0 +1,26 @@ +/** + * Encode certain characters in `value`. + * + * @param {string} value + * @param {CoreWithFormatOptions} options + * @returns {string} + */ +export function core(value: string, options: CoreWithFormatOptions): string; +export type CoreOptions = { + /** + * Whether to only escape the given subset of characters. + */ + subset?: ReadonlyArray; + /** + * Whether to only escape possibly dangerous characters. + * Those characters are `"`, `&`, `'`, `<`, `>`, and `` ` ``. + */ + escapeOnly?: boolean; +}; +export type FormatOptions = { + /** + * Format strategy. + */ + format: (code: number, next: number, options: CoreWithFormatOptions) => string; +}; +export type CoreWithFormatOptions = CoreOptions & FormatOptions & import('./util/format-smart.js').FormatSmartOptions; diff --git a/node_modules/stringify-entities/lib/core.js b/node_modules/stringify-entities/lib/core.js new file mode 100644 index 0000000000000000000000000000000000000000..69e9843cc85ad21c801640cacbe66bebf55c4fd9 --- /dev/null +++ b/node_modules/stringify-entities/lib/core.js @@ -0,0 +1,117 @@ +/** + * @typedef CoreOptions + * @property {ReadonlyArray} [subset=[]] + * Whether to only escape the given subset of characters. + * @property {boolean} [escapeOnly=false] + * Whether to only escape possibly dangerous characters. + * Those characters are `"`, `&`, `'`, `<`, `>`, and `` ` ``. + * + * @typedef FormatOptions + * @property {(code: number, next: number, options: CoreWithFormatOptions) => string} format + * Format strategy. + * + * @typedef {CoreOptions & FormatOptions & import('./util/format-smart.js').FormatSmartOptions} CoreWithFormatOptions + */ + +const defaultSubsetRegex = /["&'<>`]/g +const surrogatePairsRegex = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g +const controlCharactersRegex = + // eslint-disable-next-line no-control-regex, unicorn/no-hex-escape + /[\x01-\t\v\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g +const regexEscapeRegex = /[|\\{}()[\]^$+*?.]/g + +/** @type {WeakMap, RegExp>} */ +const subsetToRegexCache = new WeakMap() + +/** + * Encode certain characters in `value`. + * + * @param {string} value + * @param {CoreWithFormatOptions} options + * @returns {string} + */ +export function core(value, options) { + value = value.replace( + options.subset + ? charactersToExpressionCached(options.subset) + : defaultSubsetRegex, + basic + ) + + if (options.subset || options.escapeOnly) { + return value + } + + return ( + value + // Surrogate pairs. + .replace(surrogatePairsRegex, surrogate) + // BMP control characters (C0 except for LF, CR, SP; DEL; and some more + // non-ASCII ones). + .replace(controlCharactersRegex, basic) + ) + + /** + * @param {string} pair + * @param {number} index + * @param {string} all + */ + function surrogate(pair, index, all) { + return options.format( + (pair.charCodeAt(0) - 0xd800) * 0x400 + + pair.charCodeAt(1) - + 0xdc00 + + 0x10000, + all.charCodeAt(index + 2), + options + ) + } + + /** + * @param {string} character + * @param {number} index + * @param {string} all + */ + function basic(character, index, all) { + return options.format( + character.charCodeAt(0), + all.charCodeAt(index + 1), + options + ) + } +} + +/** + * A wrapper function that caches the result of `charactersToExpression` with a WeakMap. + * This can improve performance when tooling calls `charactersToExpression` repeatedly + * with the same subset. + * + * @param {ReadonlyArray} subset + * @returns {RegExp} + */ +function charactersToExpressionCached(subset) { + let cached = subsetToRegexCache.get(subset) + + if (!cached) { + cached = charactersToExpression(subset) + subsetToRegexCache.set(subset, cached) + } + + return cached +} + +/** + * @param {ReadonlyArray} subset + * @returns {RegExp} + */ +function charactersToExpression(subset) { + /** @type {Array} */ + const groups = [] + let index = -1 + + while (++index < subset.length) { + groups.push(subset[index].replace(regexEscapeRegex, '\\$&')) + } + + return new RegExp('(?:' + groups.join('|') + ')', 'g') +} diff --git a/node_modules/stringify-entities/lib/index.d.ts b/node_modules/stringify-entities/lib/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..10b50974762b15d0cdf6dd018240d24ea27bceab --- /dev/null +++ b/node_modules/stringify-entities/lib/index.d.ts @@ -0,0 +1,24 @@ +/** + * Encode special characters in `value`. + * + * @param {string} value + * Value to encode. + * @param {Options} [options] + * Configuration. + * @returns {string} + * Encoded value. + */ +export function stringifyEntities(value: string, options?: Options | undefined): string; +/** + * Encode special characters in `value` as hexadecimals. + * + * @param {string} value + * Value to encode. + * @param {LightOptions} [options] + * Configuration. + * @returns {string} + * Encoded value. + */ +export function stringifyEntitiesLight(value: string, options?: import("./core.js").CoreOptions | undefined): string; +export type Options = import('./core.js').CoreOptions & import('./util/format-smart.js').FormatSmartOptions; +export type LightOptions = import('./core.js').CoreOptions; diff --git a/node_modules/stringify-entities/lib/index.js b/node_modules/stringify-entities/lib/index.js new file mode 100644 index 0000000000000000000000000000000000000000..aa8ebf4e93031297f08debcfd30db557ad576052 --- /dev/null +++ b/node_modules/stringify-entities/lib/index.js @@ -0,0 +1,36 @@ +/** + * @typedef {import('./core.js').CoreOptions & import('./util/format-smart.js').FormatSmartOptions} Options + * @typedef {import('./core.js').CoreOptions} LightOptions + */ + +import {core} from './core.js' +import {formatSmart} from './util/format-smart.js' +import {formatBasic} from './util/format-basic.js' + +/** + * Encode special characters in `value`. + * + * @param {string} value + * Value to encode. + * @param {Options} [options] + * Configuration. + * @returns {string} + * Encoded value. + */ +export function stringifyEntities(value, options) { + return core(value, Object.assign({format: formatSmart}, options)) +} + +/** + * Encode special characters in `value` as hexadecimals. + * + * @param {string} value + * Value to encode. + * @param {LightOptions} [options] + * Configuration. + * @returns {string} + * Encoded value. + */ +export function stringifyEntitiesLight(value, options) { + return core(value, Object.assign({format: formatBasic}, options)) +} diff --git a/node_modules/stringify-entities/lib/util/format-basic.d.ts b/node_modules/stringify-entities/lib/util/format-basic.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0fd0272e9260aea3240b72df45dcbd1c1d9a9b7 --- /dev/null +++ b/node_modules/stringify-entities/lib/util/format-basic.d.ts @@ -0,0 +1,7 @@ +/** + * The smallest way to encode a character. + * + * @param {number} code + * @returns {string} + */ +export function formatBasic(code: number): string; diff --git a/node_modules/stringify-entities/lib/util/format-basic.js b/node_modules/stringify-entities/lib/util/format-basic.js new file mode 100644 index 0000000000000000000000000000000000000000..da9794eb820127f9baa6caabe744fd2c06241911 --- /dev/null +++ b/node_modules/stringify-entities/lib/util/format-basic.js @@ -0,0 +1,9 @@ +/** + * The smallest way to encode a character. + * + * @param {number} code + * @returns {string} + */ +export function formatBasic(code) { + return '&#x' + code.toString(16).toUpperCase() + ';' +} diff --git a/node_modules/stringify-entities/lib/util/format-smart.d.ts b/node_modules/stringify-entities/lib/util/format-smart.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..cac1fa187d15076cf492402ef657432366490d61 --- /dev/null +++ b/node_modules/stringify-entities/lib/util/format-smart.d.ts @@ -0,0 +1,32 @@ +/** + * Configurable ways to encode a character yielding pretty or small results. + * + * @param {number} code + * @param {number} next + * @param {FormatSmartOptions} options + * @returns {string} + */ +export function formatSmart(code: number, next: number, options: FormatSmartOptions): string; +export type FormatSmartOptions = { + /** + * Prefer named character references (`&`) where possible. + */ + useNamedReferences?: boolean; + /** + * Prefer the shortest possible reference, if that results in less bytes. + * **Note**: `useNamedReferences` can be omitted when using `useShortestReferences`. + */ + useShortestReferences?: boolean; + /** + * Whether to omit semicolons when possible. + * **Note**: This creates what HTML calls “parse errors” but is otherwise still valid HTML — don’t use this except when building a minifier. + * Omitting semicolons is possible for certain named and numeric references in some cases. + */ + omitOptionalSemicolons?: boolean; + /** + * Create character references which don’t fail in attributes. + * **Note**: `attribute` only applies when operating dangerously with + * `omitOptionalSemicolons: true`. + */ + attribute?: boolean; +}; diff --git a/node_modules/stringify-entities/lib/util/format-smart.js b/node_modules/stringify-entities/lib/util/format-smart.js new file mode 100644 index 0000000000000000000000000000000000000000..e640c62193d67c6b03f5f6917e8f7e02af1febc6 --- /dev/null +++ b/node_modules/stringify-entities/lib/util/format-smart.js @@ -0,0 +1,69 @@ +/** + * @typedef FormatSmartOptions + * @property {boolean} [useNamedReferences=false] + * Prefer named character references (`&`) where possible. + * @property {boolean} [useShortestReferences=false] + * Prefer the shortest possible reference, if that results in less bytes. + * **Note**: `useNamedReferences` can be omitted when using `useShortestReferences`. + * @property {boolean} [omitOptionalSemicolons=false] + * Whether to omit semicolons when possible. + * **Note**: This creates what HTML calls “parse errors” but is otherwise still valid HTML — don’t use this except when building a minifier. + * Omitting semicolons is possible for certain named and numeric references in some cases. + * @property {boolean} [attribute=false] + * Create character references which don’t fail in attributes. + * **Note**: `attribute` only applies when operating dangerously with + * `omitOptionalSemicolons: true`. + */ + +import {toHexadecimal} from './to-hexadecimal.js' +import {toDecimal} from './to-decimal.js' +import {toNamed} from './to-named.js' + +/** + * Configurable ways to encode a character yielding pretty or small results. + * + * @param {number} code + * @param {number} next + * @param {FormatSmartOptions} options + * @returns {string} + */ +export function formatSmart(code, next, options) { + let numeric = toHexadecimal(code, next, options.omitOptionalSemicolons) + /** @type {string|undefined} */ + let named + + if (options.useNamedReferences || options.useShortestReferences) { + named = toNamed( + code, + next, + options.omitOptionalSemicolons, + options.attribute + ) + } + + // Use the shortest numeric reference when requested. + // A simple algorithm would use decimal for all code points under 100, as + // those are shorter than hexadecimal: + // + // * `c` vs `c` (decimal shorter) + // * `d` vs `d` (equal) + // + // However, because we take `next` into consideration when `omit` is used, + // And it would be possible that decimals are shorter on bigger values as + // well if `next` is hexadecimal but not decimal, we instead compare both. + if ( + (options.useShortestReferences || !named) && + options.useShortestReferences + ) { + const decimal = toDecimal(code, next, options.omitOptionalSemicolons) + + if (decimal.length < numeric.length) { + numeric = decimal + } + } + + return named && + (!options.useShortestReferences || named.length < numeric.length) + ? named + : numeric +} diff --git a/node_modules/stringify-entities/lib/util/to-decimal.d.ts b/node_modules/stringify-entities/lib/util/to-decimal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0c9b22994ea1db37c6ae1096ca2ac51d978430f2 --- /dev/null +++ b/node_modules/stringify-entities/lib/util/to-decimal.d.ts @@ -0,0 +1,9 @@ +/** + * Configurable ways to encode characters as decimal references. + * + * @param {number} code + * @param {number} next + * @param {boolean|undefined} omit + * @returns {string} + */ +export function toDecimal(code: number, next: number, omit: boolean | undefined): string; diff --git a/node_modules/stringify-entities/lib/util/to-decimal.js b/node_modules/stringify-entities/lib/util/to-decimal.js new file mode 100644 index 0000000000000000000000000000000000000000..f0f706c75edef7b8e6236e08fd9cca2cb2f3ebc0 --- /dev/null +++ b/node_modules/stringify-entities/lib/util/to-decimal.js @@ -0,0 +1,16 @@ +const decimalRegex = /\d/ + +/** + * Configurable ways to encode characters as decimal references. + * + * @param {number} code + * @param {number} next + * @param {boolean|undefined} omit + * @returns {string} + */ +export function toDecimal(code, next, omit) { + const value = '&#' + String(code) + return omit && next && !decimalRegex.test(String.fromCharCode(next)) + ? value + : value + ';' +} diff --git a/node_modules/stringify-entities/lib/util/to-hexadecimal.d.ts b/node_modules/stringify-entities/lib/util/to-hexadecimal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..628cc81baedf7169b33fbd05c70ae1d24b37e10e --- /dev/null +++ b/node_modules/stringify-entities/lib/util/to-hexadecimal.d.ts @@ -0,0 +1,9 @@ +/** + * Configurable ways to encode characters as hexadecimal references. + * + * @param {number} code + * @param {number} next + * @param {boolean|undefined} omit + * @returns {string} + */ +export function toHexadecimal(code: number, next: number, omit: boolean | undefined): string; diff --git a/node_modules/stringify-entities/lib/util/to-hexadecimal.js b/node_modules/stringify-entities/lib/util/to-hexadecimal.js new file mode 100644 index 0000000000000000000000000000000000000000..0df6c68f5310feb139551fc63447eb033c63c2f1 --- /dev/null +++ b/node_modules/stringify-entities/lib/util/to-hexadecimal.js @@ -0,0 +1,16 @@ +const hexadecimalRegex = /[\dA-Fa-f]/ + +/** + * Configurable ways to encode characters as hexadecimal references. + * + * @param {number} code + * @param {number} next + * @param {boolean|undefined} omit + * @returns {string} + */ +export function toHexadecimal(code, next, omit) { + const value = '&#x' + code.toString(16).toUpperCase() + return omit && next && !hexadecimalRegex.test(String.fromCharCode(next)) + ? value + : value + ';' +} diff --git a/node_modules/stringify-entities/lib/util/to-named.d.ts b/node_modules/stringify-entities/lib/util/to-named.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..674ac2fb12386efc29a81b8e624da2eacad01050 --- /dev/null +++ b/node_modules/stringify-entities/lib/util/to-named.d.ts @@ -0,0 +1,10 @@ +/** + * Configurable ways to encode characters as named references. + * + * @param {number} code + * @param {number} next + * @param {boolean|undefined} omit + * @param {boolean|undefined} attribute + * @returns {string} + */ +export function toNamed(code: number, next: number, omit: boolean | undefined, attribute: boolean | undefined): string; diff --git a/node_modules/stringify-entities/lib/util/to-named.js b/node_modules/stringify-entities/lib/util/to-named.js new file mode 100644 index 0000000000000000000000000000000000000000..01915e239cf5830bef4e361c543110893b222894 --- /dev/null +++ b/node_modules/stringify-entities/lib/util/to-named.js @@ -0,0 +1,57 @@ +import {characterEntitiesLegacy} from 'character-entities-legacy' +import {characterEntitiesHtml4} from 'character-entities-html4' +import {dangerous} from '../constant/dangerous.js' + +const own = {}.hasOwnProperty + +/** + * `characterEntitiesHtml4` but inverted. + * + * @type {Record} + */ +const characters = {} + +/** @type {string} */ +let key + +for (key in characterEntitiesHtml4) { + if (own.call(characterEntitiesHtml4, key)) { + characters[characterEntitiesHtml4[key]] = key + } +} + +const notAlphanumericRegex = /[^\dA-Za-z]/ + +/** + * Configurable ways to encode characters as named references. + * + * @param {number} code + * @param {number} next + * @param {boolean|undefined} omit + * @param {boolean|undefined} attribute + * @returns {string} + */ +export function toNamed(code, next, omit, attribute) { + const character = String.fromCharCode(code) + + if (own.call(characters, character)) { + const name = characters[character] + const value = '&' + name + + if ( + omit && + characterEntitiesLegacy.includes(name) && + !dangerous.includes(name) && + (!attribute || + (next && + next !== 61 /* `=` */ && + notAlphanumericRegex.test(String.fromCharCode(next)))) + ) { + return value + } + + return value + ';' + } + + return '' +} diff --git a/node_modules/stringify-entities/license b/node_modules/stringify-entities/license new file mode 100644 index 0000000000000000000000000000000000000000..611b67581bb8e218704aff1dfb073edac83a86dc --- /dev/null +++ b/node_modules/stringify-entities/license @@ -0,0 +1,22 @@ +(The MIT License) + +Copyright (c) 2015 Titus Wormer + +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. diff --git a/node_modules/stringify-entities/package.json b/node_modules/stringify-entities/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ba14d0c351862c343673fb27c8a8f956de45c99e --- /dev/null +++ b/node_modules/stringify-entities/package.json @@ -0,0 +1,86 @@ +{ + "name": "stringify-entities", + "version": "4.0.4", + "description": "Serialize (encode) HTML character references", + "license": "MIT", + "keywords": [ + "stringify", + "encode", + "escape", + "html", + "character", + "reference", + "entity", + "entities" + ], + "repository": "wooorm/stringify-entities", + "bugs": "https://github.com/wooorm/stringify-entities/issues", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + }, + "author": "Titus Wormer (https://wooorm.com)", + "contributors": [ + "Titus Wormer (https://wooorm.com)" + ], + "sideEffects": false, + "type": "module", + "main": "index.js", + "types": "index.d.ts", + "files": [ + "lib/", + "index.d.ts", + "index.js" + ], + "dependencies": { + "character-entities-html4": "^2.0.0", + "character-entities-legacy": "^3.0.0" + }, + "devDependencies": { + "@types/node": "^20.0.0", + "c8": "^9.0.0", + "character-entities": "^2.0.0", + "prettier": "^3.0.0", + "remark-cli": "^11.0.0", + "remark-preset-wooorm": "^9.0.0", + "type-coverage": "^2.0.0", + "typescript": "^5.0.0", + "xo": "^0.58.0" + }, + "scripts": { + "prepack": "npm run build && npm run format", + "generate": "node --conditions development build.js", + "build": "tsc --build --clean && tsc --build && type-coverage", + "format": "remark . -qfo && prettier . -w --log-level warn && xo --fix", + "test-api": "node --conditions development test.js", + "test-coverage": "c8 --check-coverage --100 --reporter lcov npm run test-api", + "test": "npm run generate && npm run build && npm run format && npm run test-coverage" + }, + "prettier": { + "tabWidth": 2, + "useTabs": false, + "singleQuote": true, + "bracketSpacing": false, + "semi": false, + "trailingComma": "none" + }, + "xo": { + "prettier": true, + "rules": { + "unicorn/prefer-code-point": "off", + "unicorn/prefer-string-replace-all": "off", + "unicorn/numeric-separators-style": "off" + } + }, + "remarkConfig": { + "plugins": [ + "preset-wooorm" + ] + }, + "typeCoverage": { + "atLeast": 100, + "detail": true, + "strict": true, + "ignoreCatch": true + } +} diff --git a/node_modules/stringify-entities/readme.md b/node_modules/stringify-entities/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..3c319091bc90ca94cd9cc2eecad2a47e0273278d --- /dev/null +++ b/node_modules/stringify-entities/readme.md @@ -0,0 +1,233 @@ +# stringify-entities + +[![Build Status][build-badge]][build] +[![Coverage Status][coverage-badge]][coverage] +[![Downloads][downloads-badge]][downloads] +[![Size][size-badge]][size] + +Serialize (encode) HTML character references. + +## Contents + +* [What is this?](#what-is-this) +* [When should I use this?](#when-should-i-use-this) +* [Install](#install) +* [Use](#use) +* [API](#api) + * [`stringifyEntities(value[, options])`](#stringifyentitiesvalue-options) +* [Algorithm](#algorithm) +* [Types](#types) +* [Compatibility](#compatibility) +* [Security](#security) +* [Related](#related) +* [Contribute](#contribute) +* [License](#license) + +## What is this? + +This is a small and powerful encoder of HTML character references (often called +entities). +This one has either all the options you need for a minifier/formatter, or a +tiny size when using `stringifyEntitiesLight`. + +## When should I use this? + +You can use this for spec-compliant encoding of character references. +It’s small and fast enough to do that well. +You can also use this when making an HTML formatter or minifier, because there +are different ways to produce pretty or tiny output. +This package is reliable: ``'`'`` characters are encoded to ensure no scripts +run in Internet Explorer 6 to 8. +Additionally, only named references recognized by HTML 4 are encoded, meaning +the infamous `'` (which people think is a [virus][]) won’t show up. + +## Install + +This package is [ESM only][esm]. +In Node.js (version 14.14+, 16.0+), install with [npm][]: + +```sh +npm install stringify-entities +``` + +In Deno with [`esm.sh`][esmsh]: + +```js +import {stringifyEntities} from 'https://esm.sh/stringify-entities@4' +``` + +In browsers with [`esm.sh`][esmsh]: + +```html + +``` + +## Use + +```js +import {stringifyEntities} from 'stringify-entities' + +stringifyEntities('alpha © bravo ≠ charlie 𝌆 delta') +// => 'alpha © bravo ≠ charlie 𝌆 delta' + +stringifyEntities('alpha © bravo ≠ charlie 𝌆 delta', {useNamedReferences: true}) +// => 'alpha © bravo ≠ charlie 𝌆 delta' +``` + +## API + +This package exports the identifiers `stringifyEntities` and +`stringifyEntitiesLight`. +There is no default export. + +### `stringifyEntities(value[, options])` + +Encode special characters in `value`. + +##### Core options + +###### `options.escapeOnly` + +Whether to only escape possibly dangerous characters (`boolean`, default: +`false`). +Those characters are `"`, `&`, `'`, `<`, `>`, and `` ` ``. + +###### `options.subset` + +Whether to only escape the given subset of characters (`Array`). +Note that only BMP characters are supported here (so no emoji). + +##### Formatting options + +If you do not care about the following options, use `stringifyEntitiesLight`, +which always outputs hexadecimal character references. + +###### `options.useNamedReferences` + +Prefer named character references (`&`) where possible (`boolean?`, default: +`false`). + +###### `options.useShortestReferences` + +Prefer the shortest possible reference, if that results in less bytes +(`boolean?`, default: `false`). + +> ⚠️ **Note**: `useNamedReferences` can be omitted when using +> `useShortestReferences`. + +###### `options.omitOptionalSemicolons` + +Whether to omit semicolons when possible (`boolean?`, default: `false`). + +> ⚠️ **Note**: This creates what HTML calls “parse errors” but is otherwise +> still valid HTML — don’t use this except when building a minifier. +> Omitting semicolons is possible for certain named and numeric references in +> some cases. + +###### `options.attribute` + +Create character references which don’t fail in attributes (`boolean?`, default: +`false`). + +> ⚠️ **Note**: `attribute` only applies when operating dangerously with +> `omitOptionalSemicolons: true`. + +#### Returns + +Encoded value (`string`). + +## Algorithm + +By default, all dangerous, non-ASCII, and non-printable ASCII characters are +encoded. +A [subset][] of characters can be given to encode just those characters. +Alternatively, pass [`escapeOnly`][escapeonly] to escape just the dangerous +characters (`"`, `'`, `<`, `>`, `&`, `` ` ``). +By default, hexadecimal character references are used. +Pass [`useNamedReferences`][named] to use named character references when +possible, or [`useShortestReferences`][short] to use whichever is shortest: +decimal, hexadecimal, or named. +There is also a `stringifyEntitiesLight` export, which works just like +`stringifyEntities` but without the formatting options: it’s much smaller but +always outputs hexadecimal character references. + +## Types + +This package is fully typed with [TypeScript][]. +It exports the additional types `Options` and `LightOptions` types. + +## Compatibility + +This package is at least compatible with all maintained versions of Node.js. +As of now, that is Node.js 14.14+ and 16.0+. +It also works in Deno and modern browsers. + +## Security + +This package is safe. + +## Related + +* [`parse-entities`](https://github.com/wooorm/parse-entities) + — parse (decode) HTML character references +* [`wooorm/character-entities`](https://github.com/wooorm/character-entities) + — info on character references +* [`wooorm/character-entities-html4`](https://github.com/wooorm/character-entities-html4) + — info on HTML 4 character references +* [`wooorm/character-entities-legacy`](https://github.com/wooorm/character-entities-legacy) + — info on legacy character references +* [`wooorm/character-reference-invalid`](https://github.com/wooorm/character-reference-invalid) + — info on invalid numeric character references + +## Contribute + +Yes please! +See [How to Contribute to Open Source][contribute]. + +## License + +[MIT][license] © [Titus Wormer][author] + + + +[build-badge]: https://github.com/wooorm/stringify-entities/workflows/main/badge.svg + +[build]: https://github.com/wooorm/stringify-entities/actions + +[coverage-badge]: https://img.shields.io/codecov/c/github/wooorm/stringify-entities.svg + +[coverage]: https://codecov.io/github/wooorm/stringify-entities + +[downloads-badge]: https://img.shields.io/npm/dm/stringify-entities.svg + +[downloads]: https://www.npmjs.com/package/stringify-entities + +[size-badge]: https://img.shields.io/bundlephobia/minzip/stringify-entities.svg + +[size]: https://bundlephobia.com/result?p=stringify-entities + +[npm]: https://docs.npmjs.com/cli/install + +[esmsh]: https://esm.sh + +[license]: license + +[author]: https://wooorm.com + +[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c + +[typescript]: https://www.typescriptlang.org + +[contribute]: https://opensource.guide/how-to-contribute/ + +[virus]: https://www.telegraph.co.uk/technology/advice/10516839/Why-do-some-apostrophes-get-replaced-with-andapos.html + +[subset]: #optionssubset + +[escapeonly]: #optionsescapeonly + +[named]: #optionsusenamedreferences + +[short]: #optionsuseshortestreferences diff --git a/node_modules/stringify-object/LICENSE b/node_modules/stringify-object/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ff642e65a3a914a1a144ce801ca6f22256ffb791 --- /dev/null +++ b/node_modules/stringify-object/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2015, Yeoman team +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/stringify-object/index.js b/node_modules/stringify-object/index.js new file mode 100644 index 0000000000000000000000000000000000000000..beed5e3ae38c94415ca5dd9b11398b31d6f471db --- /dev/null +++ b/node_modules/stringify-object/index.js @@ -0,0 +1,131 @@ +'use strict'; +const isRegexp = require('is-regexp'); +const isObj = require('is-obj'); +const getOwnEnumPropSymbols = require('get-own-enumerable-property-symbols').default; + +module.exports = (val, opts, pad) => { + const seen = []; + + return (function stringify(val, opts, pad) { + opts = opts || {}; + opts.indent = opts.indent || '\t'; + pad = pad || ''; + + let tokens; + + if (opts.inlineCharacterLimit === undefined) { + tokens = { + newLine: '\n', + newLineOrSpace: '\n', + pad, + indent: pad + opts.indent + }; + } else { + tokens = { + newLine: '@@__STRINGIFY_OBJECT_NEW_LINE__@@', + newLineOrSpace: '@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@', + pad: '@@__STRINGIFY_OBJECT_PAD__@@', + indent: '@@__STRINGIFY_OBJECT_INDENT__@@' + }; + } + + const expandWhiteSpace = string => { + if (opts.inlineCharacterLimit === undefined) { + return string; + } + + const oneLined = string + .replace(new RegExp(tokens.newLine, 'g'), '') + .replace(new RegExp(tokens.newLineOrSpace, 'g'), ' ') + .replace(new RegExp(tokens.pad + '|' + tokens.indent, 'g'), ''); + + if (oneLined.length <= opts.inlineCharacterLimit) { + return oneLined; + } + + return string + .replace(new RegExp(tokens.newLine + '|' + tokens.newLineOrSpace, 'g'), '\n') + .replace(new RegExp(tokens.pad, 'g'), pad) + .replace(new RegExp(tokens.indent, 'g'), pad + opts.indent); + }; + + if (seen.indexOf(val) !== -1) { + return '"[Circular]"'; + } + + if (val === null || + val === undefined || + typeof val === 'number' || + typeof val === 'boolean' || + typeof val === 'function' || + typeof val === 'symbol' || + isRegexp(val)) { + return String(val); + } + + if (val instanceof Date) { + return `new Date('${val.toISOString()}')`; + } + + if (Array.isArray(val)) { + if (val.length === 0) { + return '[]'; + } + + seen.push(val); + + const ret = '[' + tokens.newLine + val.map((el, i) => { + const eol = val.length - 1 === i ? tokens.newLine : ',' + tokens.newLineOrSpace; + let value = stringify(el, opts, pad + opts.indent); + if (opts.transform) { + value = opts.transform(val, i, value); + } + return tokens.indent + value + eol; + }).join('') + tokens.pad + ']'; + + seen.pop(); + + return expandWhiteSpace(ret); + } + + if (isObj(val)) { + let objKeys = Object.keys(val).concat(getOwnEnumPropSymbols(val)); + + if (opts.filter) { + objKeys = objKeys.filter(el => opts.filter(val, el)); + } + + if (objKeys.length === 0) { + return '{}'; + } + + seen.push(val); + + const ret = '{' + tokens.newLine + objKeys.map((el, i) => { + const eol = objKeys.length - 1 === i ? tokens.newLine : ',' + tokens.newLineOrSpace; + const isSymbol = typeof el === 'symbol'; + const isClassic = !isSymbol && /^[a-z$_][a-z$_0-9]*$/i.test(el); + const key = isSymbol || isClassic ? el : stringify(el, opts); + let value = stringify(val[el], opts, pad + opts.indent); + if (opts.transform) { + value = opts.transform(val, el, value); + } + return tokens.indent + String(key) + ': ' + value + eol; + }).join('') + tokens.pad + '}'; + + seen.pop(); + + return expandWhiteSpace(ret); + } + + val = String(val).replace(/[\r\n]/g, x => x === '\n' ? '\\n' : '\\r'); + + if (opts.singleQuotes === false) { + val = val.replace(/"/g, '\\"'); + return `"${val}"`; + } + + val = val.replace(/\\?'/g, '\\\''); + return `'${val}'`; + })(val, opts, pad); +}; diff --git a/node_modules/stringify-object/package.json b/node_modules/stringify-object/package.json new file mode 100644 index 0000000000000000000000000000000000000000..74d638c008915b542beb02281d5b45d81bb35893 --- /dev/null +++ b/node_modules/stringify-object/package.json @@ -0,0 +1,40 @@ +{ + "name": "stringify-object", + "version": "3.3.0", + "description": "Stringify an object/array like JSON.stringify just without all the double-quotes", + "license": "BSD-2-Clause", + "repository": "yeoman/stringify-object", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "object", + "stringify", + "pretty", + "print", + "dump", + "format", + "type", + "json" + ], + "dependencies": { + "get-own-enumerable-property-symbols": "^3.0.0", + "is-obj": "^1.0.1", + "is-regexp": "^1.0.0" + }, + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/stringify-object/readme.md b/node_modules/stringify-object/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..d4d6c3d79942c17485de6dc777f2ad34b799312d --- /dev/null +++ b/node_modules/stringify-object/readme.md @@ -0,0 +1,155 @@ +# stringify-object [![Build Status](https://secure.travis-ci.org/yeoman/stringify-object.svg?branch=master)](http://travis-ci.org/yeoman/stringify-object) + +> Stringify an object/array like JSON.stringify just without all the double-quotes + +Useful for when you want to get the string representation of an object in a formatted way. + +It also handles circular references and lets you specify quote type. + + +## Install + +``` +$ npm install stringify-object +``` + + +## Usage + +```js +const stringifyObject = require('stringify-object'); + +const obj = { + foo: 'bar', + 'arr': [1, 2, 3], + nested: { hello: "world" } +}; + +const pretty = stringifyObject(obj, { + indent: ' ', + singleQuotes: false +}); + +console.log(pretty); +/* +{ + foo: "bar", + arr: [ + 1, + 2, + 3 + ], + nested: { + hello: "world" + } +} +*/ +``` + + +## API + +### stringifyObject(input, [options]) + +Circular references will be replaced with `"[Circular]"`. + +#### input + +Type: `Object` `Array` + +#### options + +##### indent + +Type: `string`
+Default: `\t` + +Preferred indentation. + +##### singleQuotes + +Type: `boolean`
+Default: `true` + +Set to false to get double-quoted strings. + +##### filter(obj, prop) + +Type: `Function` + +Expected to return a `boolean` of whether to include the property `prop` of the object `obj` in the output. + +##### transform(obj, prop, originalResult) + +Type: `Function`
+Default: `undefined` + +Expected to return a `string` that transforms the string that resulted from stringifying `obj[prop]`. This can be used to detect special types of objects that need to be stringified in a particular way. The `transform` function might return an alternate string in this case, otherwise returning the `originalResult`. + +Here's an example that uses the `transform` option to mask fields named "password": + +```js +const obj = { + user: 'becky', + password: 'secret' +} + +const pretty = stringifyObject(obj, { + transform: (obj, prop, originalResult) => { + if (prop === 'password') { + return originalResult.replace(/\w/g, '*'); + } else { + return originalResult; + } + } +}); + +console.log(pretty); +/* +{ + user: 'becky', + password: '******' +} +*/ +``` + + +##### inlineCharacterLimit + +Type: `number` + +When set, will inline values up to `inlineCharacterLimit` length for the sake of more terse output. + +For example, given the example at the top of the README: + +```js +const obj = { + foo: 'bar', + 'arr': [1, 2, 3], + nested: { hello: "world" } +}; + +const pretty = stringifyObject(obj, { + indent: ' ', + singleQuotes: false, + inlineCharacterLimit: 12 +}); + +console.log(pretty); +/* +{ + foo: "bar", + arr: [1, 2, 3], + nested: { + hello: "world" + } +} +*/ +``` + +As you can see, `arr` was printed as a one-liner because its string was shorter than 12 characters. + + +## License + +BSD-2-Clause © Yeoman team diff --git a/node_modules/strip-ansi/index.d.ts b/node_modules/strip-ansi/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..44e954d0c724d82e07bbb484f05fcbf817347b03 --- /dev/null +++ b/node_modules/strip-ansi/index.d.ts @@ -0,0 +1,15 @@ +/** +Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. + +@example +``` +import stripAnsi from 'strip-ansi'; + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` +*/ +export default function stripAnsi(string: string): string; diff --git a/node_modules/strip-ansi/index.js b/node_modules/strip-ansi/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0309635491a2e92378a7a3b381d1302c3710b197 --- /dev/null +++ b/node_modules/strip-ansi/index.js @@ -0,0 +1,19 @@ +import ansiRegex from 'ansi-regex'; + +const regex = ansiRegex(); + +export default function stripAnsi(string) { + if (typeof string !== 'string') { + throw new TypeError(`Expected a \`string\`, got \`${typeof string}\``); + } + + // Fast path: ANSI codes require ESC (7-bit) or CSI (8-bit) introducer + if (!string.includes('\u001B') && !string.includes('\u009B')) { + return string; + } + + // Even though the regex is global, we don't need to reset the `.lastIndex` + // because unlike `.exec()` and `.test()`, `.replace()` does it automatically + // and doing it manually has a performance penalty. + return string.replace(regex, ''); +} diff --git a/node_modules/strip-ansi/license b/node_modules/strip-ansi/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/strip-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +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. diff --git a/node_modules/strip-ansi/package.json b/node_modules/strip-ansi/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a1786b3c5bc9ade04d546961a7055bc04d98c96c --- /dev/null +++ b/node_modules/strip-ansi/package.json @@ -0,0 +1,59 @@ +{ + "name": "strip-ansi", + "version": "7.2.0", + "description": "Strip ANSI escape codes from a string", + "license": "MIT", + "repository": "chalk/strip-ansi", + "funding": "https://github.com/chalk/strip-ansi?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "type": "module", + "exports": "./index.js", + "types": "./index.d.ts", + "sideEffects": false, + "engines": { + "node": ">=12" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "devDependencies": { + "ava": "^6.4.1", + "tsd": "^0.33.0", + "xo": "^1.2.3" + } +} diff --git a/node_modules/strip-ansi/readme.md b/node_modules/strip-ansi/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..109b692b413c4aaa57168f9a981f5fb1f48525c7 --- /dev/null +++ b/node_modules/strip-ansi/readme.md @@ -0,0 +1,37 @@ +# strip-ansi + +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string + +> [!NOTE] +> Node.js has this built-in now with [`stripVTControlCharacters`](https://nodejs.org/api/util.html#utilstripvtcontrolcharactersstr). The benefit of this package is consistent behavior across Node.js versions and faster improvements. The Node.js version is actually based on this package. + +## Install + +```sh +npm install strip-ansi +``` + +## Usage + +```js +import stripAnsi from 'strip-ansi'; + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` + +## Related + +- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) diff --git a/node_modules/strip-bom/index.js b/node_modules/strip-bom/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b00feb9a440961c004d6eeaf297bd4cbd04d64a9 --- /dev/null +++ b/node_modules/strip-bom/index.js @@ -0,0 +1,14 @@ +'use strict'; +module.exports = x => { + if (typeof x !== 'string') { + throw new TypeError('Expected a string, got ' + typeof x); + } + + // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string + // conversion translates it to FEFF (UTF-16 BOM) + if (x.charCodeAt(0) === 0xFEFF) { + return x.slice(1); + } + + return x; +}; diff --git a/node_modules/strip-bom/license b/node_modules/strip-bom/license new file mode 100644 index 0000000000000000000000000000000000000000..654d0bfe943437d43242325b1fbcff5f400d84ee --- /dev/null +++ b/node_modules/strip-bom/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/strip-bom/package.json b/node_modules/strip-bom/package.json new file mode 100644 index 0000000000000000000000000000000000000000..10f8fdd7e5dba757e3c9557171d01ed5695d80e5 --- /dev/null +++ b/node_modules/strip-bom/package.json @@ -0,0 +1,40 @@ +{ + "name": "strip-bom", + "version": "3.0.0", + "description": "Strip UTF-8 byte order mark (BOM) from a string", + "license": "MIT", + "repository": "sindresorhus/strip-bom", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "strip", + "bom", + "byte", + "order", + "mark", + "unicode", + "utf8", + "utf-8", + "remove", + "delete", + "trim", + "text", + "string" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/strip-bom/readme.md b/node_modules/strip-bom/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..812a98071fb97f94deab51bc003d09f6f0be2cf8 --- /dev/null +++ b/node_modules/strip-bom/readme.md @@ -0,0 +1,36 @@ +# strip-bom [![Build Status](https://travis-ci.org/sindresorhus/strip-bom.svg?branch=master)](https://travis-ci.org/sindresorhus/strip-bom) + +> Strip UTF-8 [byte order mark](http://en.wikipedia.org/wiki/Byte_order_mark#UTF-8) (BOM) from a string + +From Wikipedia: + +> The Unicode Standard permits the BOM in UTF-8, but does not require nor recommend its use. Byte order has no meaning in UTF-8. + + +## Install + +``` +$ npm install --save strip-bom +``` + + +## Usage + +```js +const stripBom = require('strip-bom'); + +stripBom('\uFEFFunicorn'); +//=> 'unicorn' +``` + + +## Related + +- [strip-bom-cli](https://github.com/sindresorhus/strip-bom-cli) - CLI for this module +- [strip-bom-buf](https://github.com/sindresorhus/strip-bom-buf) - Buffer version of this module +- [strip-bom-stream](https://github.com/sindresorhus/strip-bom-stream) - Stream version of this module + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com)