This commit is contained in:
3056762376@qq.com 2022-11-20 17:18:54 +08:00
parent 3e21965910
commit 5a5ce06738
391 changed files with 43072 additions and 16280 deletions

View File

@ -0,0 +1,207 @@
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__js_mathTools_js__ = __webpack_require__(1);
console.log(__WEBPACK_IMPORTED_MODULE_0__js_mathTools_js__["a" /* add */](33,44));
console.log(__WEBPACK_IMPORTED_MODULE_0__js_mathTools_js__["b" /* remove */](323,111));
__webpack_require__(2)
/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return add; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return remove; });
function add(num1,num2){
return num1 + num2;
}
function remove(num1,num2){
return num1-num2
}
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
// Imports
var ___CSS_LOADER_API_IMPORT___ = __webpack_require__(3);
exports = ___CSS_LOADER_API_IMPORT___(false);
// Module
exports.push([module.i, "body{\r\n background-color: antiquewhite;\r\n}\r\n", ""]);
// Exports
module.exports = exports;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
// css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function (useSourceMap) {
var list = []; // return the list of modules as css string
list.toString = function toString() {
return this.map(function (item) {
var content = cssWithMappingToString(item, useSourceMap);
if (item[2]) {
return "@media ".concat(item[2], " {").concat(content, "}");
}
return content;
}).join('');
}; // import a list of modules into the list
// eslint-disable-next-line func-names
list.i = function (modules, mediaQuery, dedupe) {
if (typeof modules === 'string') {
// eslint-disable-next-line no-param-reassign
modules = [[null, modules, '']];
}
var alreadyImportedModules = {};
if (dedupe) {
for (var i = 0; i < this.length; i++) {
// eslint-disable-next-line prefer-destructuring
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
}
for (var _i = 0; _i < modules.length; _i++) {
var item = [].concat(modules[_i]);
if (dedupe && alreadyImportedModules[item[0]]) {
// eslint-disable-next-line no-continue
continue;
}
if (mediaQuery) {
if (!item[2]) {
item[2] = mediaQuery;
} else {
item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
}
}
list.push(item);
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === 'function') {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function (source) {
return "/*# sourceURL=".concat(cssMapping.sourceRoot || '').concat(source, " */");
});
return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
}
return [content].join('\n');
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
return "/*# ".concat(data, " */");
}
/***/ })
/******/ ]);

View File

@ -1,12 +0,0 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../nanoid/bin/nanoid.cjs" "$@"
else
exec node "$basedir/../nanoid/bin/nanoid.cjs" "$@"
fi

View File

@ -1,17 +0,0 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nanoid\bin\nanoid.cjs" %*

View File

@ -1,28 +0,0 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
} else {
& "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
} else {
& "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args
}
$ret=$LASTEXITCODE
}
exit $ret

View File

@ -4,6 +4,12 @@
"lockfileVersion": 2,
"requires": true,
"packages": {
"node_modules/@types/json-schema": {
"version": "7.0.11",
"resolved": "https://registry.npmmirror.com/@types/json-schema/-/json-schema-7.0.11.tgz",
"integrity": "sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==",
"dev": true
},
"node_modules/acorn": {
"version": "5.7.4",
"resolved": "https://registry.npmmirror.com/acorn/-/acorn-5.7.4.tgz",
@ -657,60 +663,55 @@
}
},
"node_modules/css-loader": {
"version": "6.7.2",
"resolved": "https://registry.npmmirror.com/css-loader/-/css-loader-6.7.2.tgz",
"integrity": "sha512-oqGbbVcBJkm8QwmnNzrFrWTnudnRZC+1eXikLJl0n4ljcfotgRifpg2a1lKy8jTrc4/d9A/ap1GFq1jDKG7J+Q==",
"version": "3.6.0",
"resolved": "https://registry.npmmirror.com/css-loader/-/css-loader-3.6.0.tgz",
"integrity": "sha512-M5lSukoWi1If8dhQAUCvj4H8vUt3vOnwbQBH9DdTm/s4Ym2B/3dPMtYZeJmq7Q3S3Pa+I94DcZ7pc9bP14cWIQ==",
"dev": true,
"dependencies": {
"icss-utils": "^5.1.0",
"postcss": "^8.4.18",
"postcss-modules-extract-imports": "^3.0.0",
"postcss-modules-local-by-default": "^4.0.0",
"postcss-modules-scope": "^3.0.0",
"postcss-modules-values": "^4.0.0",
"postcss-value-parser": "^4.2.0",
"semver": "^7.3.8"
"camelcase": "^5.3.1",
"cssesc": "^3.0.0",
"icss-utils": "^4.1.1",
"loader-utils": "^1.2.3",
"normalize-path": "^3.0.0",
"postcss": "^7.0.32",
"postcss-modules-extract-imports": "^2.0.0",
"postcss-modules-local-by-default": "^3.0.2",
"postcss-modules-scope": "^2.2.0",
"postcss-modules-values": "^3.0.0",
"postcss-value-parser": "^4.1.0",
"schema-utils": "^2.7.0",
"semver": "^6.3.0"
},
"engines": {
"node": ">= 12.13.0"
"node": ">= 8.9.0"
},
"peerDependencies": {
"webpack": "^5.0.0"
"webpack": "^4.0.0 || ^5.0.0"
}
},
"node_modules/css-loader/node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmmirror.com/lru-cache/-/lru-cache-6.0.0.tgz",
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
"dependencies": {
"yallist": "^4.0.0"
},
"node_modules/css-loader/node_modules/camelcase": {
"version": "5.3.1",
"resolved": "https://registry.npmmirror.com/camelcase/-/camelcase-5.3.1.tgz",
"integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==",
"dev": true,
"engines": {
"node": ">=10"
"node": ">=6"
}
},
"node_modules/css-loader/node_modules/semver": {
"version": "7.3.8",
"resolved": "https://registry.npmmirror.com/semver/-/semver-7.3.8.tgz",
"integrity": "sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==",
"dependencies": {
"lru-cache": "^6.0.0"
},
"version": "6.3.0",
"resolved": "https://registry.npmmirror.com/semver/-/semver-6.3.0.tgz",
"integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==",
"dev": true,
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/css-loader/node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmmirror.com/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="
},
"node_modules/cssesc": {
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/cssesc/-/cssesc-3.0.0.tgz",
"integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==",
"dev": true,
"bin": {
"cssesc": "bin/cssesc"
},
@ -1407,14 +1408,15 @@
"integrity": "sha512-J+FkSdyD+0mA0N+81tMotaRMfSL9SGi+xpD3T6YApKsc3bGSXJlfXri3VyFOeYkfLRQisDk1W+jIFFKBeUBbBg=="
},
"node_modules/icss-utils": {
"version": "5.1.0",
"resolved": "https://registry.npmmirror.com/icss-utils/-/icss-utils-5.1.0.tgz",
"integrity": "sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==",
"engines": {
"node": "^10 || ^12 || >= 14"
"version": "4.1.1",
"resolved": "https://registry.npmmirror.com/icss-utils/-/icss-utils-4.1.1.tgz",
"integrity": "sha512-4aFq7wvWyMHKgxsH8QQtGpvbASCf+eM3wPRLI6R+MgAnTCZ6STYsRvttLvRWK0Nfif5piF394St3HeJDaljGPA==",
"dev": true,
"dependencies": {
"postcss": "^7.0.14"
},
"peerDependencies": {
"postcss": "^8.1.0"
"engines": {
"node": ">= 6"
}
},
"node_modules/ieee754": {
@ -1996,17 +1998,6 @@
"resolved": "https://registry.npmmirror.com/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
},
"node_modules/nanoid": {
"version": "3.3.4",
"resolved": "https://registry.npmmirror.com/nanoid/-/nanoid-3.3.4.tgz",
"integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/nanomatch": {
"version": "1.2.13",
"resolved": "https://registry.npmmirror.com/nanomatch/-/nanomatch-1.2.13.tgz",
@ -2369,9 +2360,10 @@
}
},
"node_modules/picocolors": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-1.0.0.tgz",
"integrity": "sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ=="
"version": "0.2.1",
"resolved": "https://registry.npmmirror.com/picocolors/-/picocolors-0.2.1.tgz",
"integrity": "sha512-cMlDqaLEqfSaW8Z7N5Jw+lyIW869EzT73/F5lhtY9cLGoVxSXznfgfXMO0Z5K0o0Q2TkTXq+0KFsdnSe3jDViA==",
"dev": true
},
"node_modules/picomatch": {
"version": "2.3.1",
@ -2398,77 +2390,73 @@
}
},
"node_modules/postcss": {
"version": "8.4.19",
"resolved": "https://registry.npmmirror.com/postcss/-/postcss-8.4.19.tgz",
"integrity": "sha512-h+pbPsyhlYj6N2ozBmHhHrs9DzGmbaarbLvWipMRO7RLS+v4onj26MPFXA5OBYFxyqYhUJK456SwDcY9H2/zsA==",
"version": "7.0.39",
"resolved": "https://registry.npmmirror.com/postcss/-/postcss-7.0.39.tgz",
"integrity": "sha512-yioayjNbHn6z1/Bywyb2Y4s3yvDAeXGOyxqD+LnVOinq6Mdmd++SW2wUNVzavyyHxd6+DxzWGIuosg6P1Rj8uA==",
"dev": true,
"dependencies": {
"nanoid": "^3.3.4",
"picocolors": "^1.0.0",
"source-map-js": "^1.0.2"
"picocolors": "^0.2.1",
"source-map": "^0.6.1"
},
"engines": {
"node": "^10 || ^12 || >=14"
"node": ">=6.0.0"
}
},
"node_modules/postcss-modules-extract-imports": {
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/postcss-modules-extract-imports/-/postcss-modules-extract-imports-3.0.0.tgz",
"integrity": "sha512-bdHleFnP3kZ4NYDhuGlVK+CMrQ/pqUm8bx/oGL93K6gVwiclvX5x0n76fYMKuIGKzlABOy13zsvqjb0f92TEXw==",
"engines": {
"node": "^10 || ^12 || >= 14"
"version": "2.0.0",
"resolved": "https://registry.npmmirror.com/postcss-modules-extract-imports/-/postcss-modules-extract-imports-2.0.0.tgz",
"integrity": "sha512-LaYLDNS4SG8Q5WAWqIJgdHPJrDDr/Lv775rMBFUbgjTz6j34lUznACHcdRWroPvXANP2Vj7yNK57vp9eFqzLWQ==",
"dev": true,
"dependencies": {
"postcss": "^7.0.5"
},
"peerDependencies": {
"postcss": "^8.1.0"
"engines": {
"node": ">= 6"
}
},
"node_modules/postcss-modules-local-by-default": {
"version": "4.0.0",
"resolved": "https://registry.npmmirror.com/postcss-modules-local-by-default/-/postcss-modules-local-by-default-4.0.0.tgz",
"integrity": "sha512-sT7ihtmGSF9yhm6ggikHdV0hlziDTX7oFoXtuVWeDd3hHObNkcHRo9V3yg7vCAY7cONyxJC/XXCmmiHHcvX7bQ==",
"version": "3.0.3",
"resolved": "https://registry.npmmirror.com/postcss-modules-local-by-default/-/postcss-modules-local-by-default-3.0.3.tgz",
"integrity": "sha512-e3xDq+LotiGesympRlKNgaJ0PCzoUIdpH0dj47iWAui/kyTgh3CiAr1qP54uodmJhl6p9rN6BoNcdEDVJx9RDw==",
"dev": true,
"dependencies": {
"icss-utils": "^5.0.0",
"icss-utils": "^4.1.1",
"postcss": "^7.0.32",
"postcss-selector-parser": "^6.0.2",
"postcss-value-parser": "^4.1.0"
},
"engines": {
"node": "^10 || ^12 || >= 14"
},
"peerDependencies": {
"postcss": "^8.1.0"
"node": ">= 6"
}
},
"node_modules/postcss-modules-scope": {
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/postcss-modules-scope/-/postcss-modules-scope-3.0.0.tgz",
"integrity": "sha512-hncihwFA2yPath8oZ15PZqvWGkWf+XUfQgUGamS4LqoP1anQLOsOJw0vr7J7IwLpoY9fatA2qiGUGmuZL0Iqlg==",
"version": "2.2.0",
"resolved": "https://registry.npmmirror.com/postcss-modules-scope/-/postcss-modules-scope-2.2.0.tgz",
"integrity": "sha512-YyEgsTMRpNd+HmyC7H/mh3y+MeFWevy7V1evVhJWewmMbjDHIbZbOXICC2y+m1xI1UVfIT1HMW/O04Hxyu9oXQ==",
"dev": true,
"dependencies": {
"postcss-selector-parser": "^6.0.4"
"postcss": "^7.0.6",
"postcss-selector-parser": "^6.0.0"
},
"engines": {
"node": "^10 || ^12 || >= 14"
},
"peerDependencies": {
"postcss": "^8.1.0"
"node": ">= 6"
}
},
"node_modules/postcss-modules-values": {
"version": "4.0.0",
"resolved": "https://registry.npmmirror.com/postcss-modules-values/-/postcss-modules-values-4.0.0.tgz",
"integrity": "sha512-RDxHkAiEGI78gS2ofyvCsu7iycRv7oqw5xMWn9iMoR0N/7mf9D50ecQqUo5BZ9Zh2vH4bCUR/ktCqbB9m8vJjQ==",
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/postcss-modules-values/-/postcss-modules-values-3.0.0.tgz",
"integrity": "sha512-1//E5jCBrZ9DmRX+zCtmQtRSV6PV42Ix7Bzj9GbwJceduuf7IqP8MgeTXuRDHOWj2m0VzZD5+roFWDuU8RQjcg==",
"dev": true,
"dependencies": {
"icss-utils": "^5.0.0"
},
"engines": {
"node": "^10 || ^12 || >= 14"
},
"peerDependencies": {
"postcss": "^8.1.0"
"icss-utils": "^4.0.0",
"postcss": "^7.0.6"
}
},
"node_modules/postcss-selector-parser": {
"version": "6.0.10",
"resolved": "https://registry.npmmirror.com/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz",
"integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==",
"dev": true,
"dependencies": {
"cssesc": "^3.0.0",
"util-deprecate": "^1.0.2"
@ -2480,7 +2468,17 @@
"node_modules/postcss-value-parser": {
"version": "4.2.0",
"resolved": "https://registry.npmmirror.com/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz",
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ=="
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
"dev": true
},
"node_modules/postcss/node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmmirror.com/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"dev": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/process": {
"version": "0.11.10",
@ -2736,6 +2734,53 @@
"resolved": "https://registry.npmmirror.com/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"node_modules/schema-utils": {
"version": "2.7.1",
"resolved": "https://registry.npmmirror.com/schema-utils/-/schema-utils-2.7.1.tgz",
"integrity": "sha512-SHiNtMOUGWBQJwzISiVYKu82GiV4QYGePp3odlY1tuKO7gPtphAT5R/py0fA6xtbgLL/RvtJZnU9b8s0F1q0Xg==",
"dev": true,
"dependencies": {
"@types/json-schema": "^7.0.5",
"ajv": "^6.12.4",
"ajv-keywords": "^3.5.2"
},
"engines": {
"node": ">= 8.9.0"
}
},
"node_modules/schema-utils/node_modules/ajv": {
"version": "6.12.6",
"resolved": "https://registry.npmmirror.com/ajv/-/ajv-6.12.6.tgz",
"integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==",
"dev": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0",
"json-schema-traverse": "^0.4.1",
"uri-js": "^4.2.2"
}
},
"node_modules/schema-utils/node_modules/ajv-keywords": {
"version": "3.5.2",
"resolved": "https://registry.npmmirror.com/ajv-keywords/-/ajv-keywords-3.5.2.tgz",
"integrity": "sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==",
"dev": true,
"peerDependencies": {
"ajv": "^6.9.1"
}
},
"node_modules/schema-utils/node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmmirror.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true
},
"node_modules/schema-utils/node_modules/json-schema-traverse": {
"version": "0.4.1",
"resolved": "https://registry.npmmirror.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
"integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
"dev": true
},
"node_modules/semver": {
"version": "5.7.1",
"resolved": "https://registry.npmmirror.com/semver/-/semver-5.7.1.tgz",
@ -2962,14 +3007,6 @@
"node": ">=0.10.0"
}
},
"node_modules/source-map-js": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/source-map-js/-/source-map-js-1.0.2.tgz",
"integrity": "sha512-R0XvVJ9WusLiqTCEiGCmICCMplcCkIwwR11mOSD9CR5u+IXYdiseeEuXCVAjS54zqwkLcPNnmU4OeJ6tUrWhDw==",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/source-map-resolve": {
"version": "0.5.3",
"resolved": "https://registry.npmmirror.com/source-map-resolve/-/source-map-resolve-0.5.3.tgz",

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

View File

@ -0,0 +1,16 @@
# Installation
> `npm install --save @types/json-schema`
# Summary
This package contains type definitions for json-schema 4.0, 6.0 and (https://github.com/kriszyp/json-schema).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/json-schema.
### Additional Details
* Last updated: Fri, 25 Mar 2022 14:01:45 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [Boris Cherny](https://github.com/bcherny), [Lucian Buzzo](https://github.com/lucianbuzzo), [Roland Groza](https://github.com/rolandjitsu), and [Jason Kwok](https://github.com/JasonHK).

View File

@ -0,0 +1,758 @@
// Type definitions for json-schema 4.0, 6.0 and 7.0
// Project: https://github.com/kriszyp/json-schema
// Definitions by: Boris Cherny <https://github.com/bcherny>
// Lucian Buzzo <https://github.com/lucianbuzzo>
// Roland Groza <https://github.com/rolandjitsu>
// Jason Kwok <https://github.com/JasonHK>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
//==================================================================================================
// JSON Schema Draft 04
//==================================================================================================
/**
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1
*/
export type JSONSchema4TypeName =
| 'string' //
| 'number'
| 'integer'
| 'boolean'
| 'object'
| 'array'
| 'null'
| 'any';
/**
* @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-3.5
*/
export type JSONSchema4Type =
| string //
| number
| boolean
| JSONSchema4Object
| JSONSchema4Array
| null;
// Workaround for infinite type recursion
export interface JSONSchema4Object {
[key: string]: JSONSchema4Type;
}
// Workaround for infinite type recursion
// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540
export interface JSONSchema4Array extends Array<JSONSchema4Type> {}
/**
* Meta schema
*
* Recommended values:
* - 'http://json-schema.org/schema#'
* - 'http://json-schema.org/hyper-schema#'
* - 'http://json-schema.org/draft-04/schema#'
* - 'http://json-schema.org/draft-04/hyper-schema#'
* - 'http://json-schema.org/draft-03/schema#'
* - 'http://json-schema.org/draft-03/hyper-schema#'
*
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5
*/
export type JSONSchema4Version = string;
/**
* JSON Schema V4
* @see https://tools.ietf.org/html/draft-zyp-json-schema-04
*/
export interface JSONSchema4 {
id?: string | undefined;
$ref?: string | undefined;
$schema?: JSONSchema4Version | undefined;
/**
* This attribute is a string that provides a short description of the
* instance property.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.21
*/
title?: string | undefined;
/**
* This attribute is a string that provides a full description of the of
* purpose the instance property.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.22
*/
description?: string | undefined;
default?: JSONSchema4Type | undefined;
multipleOf?: number | undefined;
maximum?: number | undefined;
exclusiveMaximum?: boolean | undefined;
minimum?: number | undefined;
exclusiveMinimum?: boolean | undefined;
maxLength?: number | undefined;
minLength?: number | undefined;
pattern?: string | undefined;
/**
* May only be defined when "items" is defined, and is a tuple of JSONSchemas.
*
* This provides a definition for additional items in an array instance
* when tuple definitions of the items is provided. This can be false
* to indicate additional items in the array are not allowed, or it can
* be a schema that defines the schema of the additional items.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.6
*/
additionalItems?: boolean | JSONSchema4 | undefined;
/**
* This attribute defines the allowed items in an instance array, and
* MUST be a schema or an array of schemas. The default value is an
* empty schema which allows any value for items in the instance array.
*
* When this attribute value is a schema and the instance value is an
* array, then all the items in the array MUST be valid according to the
* schema.
*
* When this attribute value is an array of schemas and the instance
* value is an array, each position in the instance array MUST conform
* to the schema in the corresponding position for this array. This
* called tuple typing. When tuple typing is used, additional items are
* allowed, disallowed, or constrained by the "additionalItems"
* (Section 5.6) attribute using the same rules as
* "additionalProperties" (Section 5.4) for objects.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.5
*/
items?: JSONSchema4 | JSONSchema4[] | undefined;
maxItems?: number | undefined;
minItems?: number | undefined;
uniqueItems?: boolean | undefined;
maxProperties?: number | undefined;
minProperties?: number | undefined;
/**
* This attribute indicates if the instance must have a value, and not
* be undefined. This is false by default, making the instance
* optional.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.7
*/
required?: boolean | string[] | undefined;
/**
* This attribute defines a schema for all properties that are not
* explicitly defined in an object type definition. If specified, the
* value MUST be a schema or a boolean. If false is provided, no
* additional properties are allowed beyond the properties defined in
* the schema. The default value is an empty schema which allows any
* value for additional properties.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.4
*/
additionalProperties?: boolean | JSONSchema4 | undefined;
definitions?: {
[k: string]: JSONSchema4;
} | undefined;
/**
* This attribute is an object with property definitions that define the
* valid values of instance object property values. When the instance
* value is an object, the property values of the instance object MUST
* conform to the property definitions in this object. In this object,
* each property definition's value MUST be a schema, and the property's
* name MUST be the name of the instance property that it defines. The
* instance property value MUST be valid according to the schema from
* the property definition. Properties are considered unordered, the
* order of the instance properties MAY be in any order.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.2
*/
properties?: {
[k: string]: JSONSchema4;
} | undefined;
/**
* This attribute is an object that defines the schema for a set of
* property names of an object instance. The name of each property of
* this attribute's object is a regular expression pattern in the ECMA
* 262/Perl 5 format, while the value is a schema. If the pattern
* matches the name of a property on the instance object, the value of
* the instance's property MUST be valid against the pattern name's
* schema value.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.3
*/
patternProperties?: {
[k: string]: JSONSchema4;
} | undefined;
dependencies?: {
[k: string]: JSONSchema4 | string[];
} | undefined;
/**
* This provides an enumeration of all possible values that are valid
* for the instance property. This MUST be an array, and each item in
* the array represents a possible value for the instance value. If
* this attribute is defined, the instance value MUST be one of the
* values in the array in order for the schema to be valid.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19
*/
enum?: JSONSchema4Type[] | undefined;
/**
* A single type, or a union of simple types
*/
type?: JSONSchema4TypeName | JSONSchema4TypeName[] | undefined;
allOf?: JSONSchema4[] | undefined;
anyOf?: JSONSchema4[] | undefined;
oneOf?: JSONSchema4[] | undefined;
not?: JSONSchema4 | undefined;
/**
* The value of this property MUST be another schema which will provide
* a base schema which the current schema will inherit from. The
* inheritance rules are such that any instance that is valid according
* to the current schema MUST be valid according to the referenced
* schema. This MAY also be an array, in which case, the instance MUST
* be valid for all the schemas in the array. A schema that extends
* another schema MAY define additional attributes, constrain existing
* attributes, or add other constraints.
*
* Conceptually, the behavior of extends can be seen as validating an
* instance against all constraints in the extending schema as well as
* the extended schema(s).
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.26
*/
extends?: string | string[] | undefined;
/**
* @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-5.6
*/
[k: string]: any;
format?: string | undefined;
}
//==================================================================================================
// JSON Schema Draft 06
//==================================================================================================
export type JSONSchema6TypeName =
| 'string' //
| 'number'
| 'integer'
| 'boolean'
| 'object'
| 'array'
| 'null'
| 'any';
export type JSONSchema6Type =
| string //
| number
| boolean
| JSONSchema6Object
| JSONSchema6Array
| null;
// Workaround for infinite type recursion
export interface JSONSchema6Object {
[key: string]: JSONSchema6Type;
}
// Workaround for infinite type recursion
// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540
export interface JSONSchema6Array extends Array<JSONSchema6Type> {}
/**
* Meta schema
*
* Recommended values:
* - 'http://json-schema.org/schema#'
* - 'http://json-schema.org/hyper-schema#'
* - 'http://json-schema.org/draft-06/schema#'
* - 'http://json-schema.org/draft-06/hyper-schema#'
*
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5
*/
export type JSONSchema6Version = string;
/**
* JSON Schema V6
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01
*/
export type JSONSchema6Definition = JSONSchema6 | boolean;
export interface JSONSchema6 {
$id?: string | undefined;
$ref?: string | undefined;
$schema?: JSONSchema6Version | undefined;
/**
* Must be strictly greater than 0.
* A numeric instance is valid only if division by this keyword's value results in an integer.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.1
*/
multipleOf?: number | undefined;
/**
* Representing an inclusive upper limit for a numeric instance.
* This keyword validates only if the instance is less than or exactly equal to "maximum".
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.2
*/
maximum?: number | undefined;
/**
* Representing an exclusive upper limit for a numeric instance.
* This keyword validates only if the instance is strictly less than (not equal to) to "exclusiveMaximum".
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.3
*/
exclusiveMaximum?: number | undefined;
/**
* Representing an inclusive lower limit for a numeric instance.
* This keyword validates only if the instance is greater than or exactly equal to "minimum".
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.4
*/
minimum?: number | undefined;
/**
* Representing an exclusive lower limit for a numeric instance.
* This keyword validates only if the instance is strictly greater than (not equal to) to "exclusiveMinimum".
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.5
*/
exclusiveMinimum?: number | undefined;
/**
* Must be a non-negative integer.
* A string instance is valid against this keyword if its length is less than, or equal to, the value of this keyword.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.6
*/
maxLength?: number | undefined;
/**
* Must be a non-negative integer.
* A string instance is valid against this keyword if its length is greater than, or equal to, the value of this keyword.
* Omitting this keyword has the same behavior as a value of 0.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.7
*/
minLength?: number | undefined;
/**
* Should be a valid regular expression, according to the ECMA 262 regular expression dialect.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.8
*/
pattern?: string | undefined;
/**
* This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself.
* Omitting this keyword has the same behavior as an empty schema.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.9
*/
items?: JSONSchema6Definition | JSONSchema6Definition[] | undefined;
/**
* This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself.
* If "items" is an array of schemas, validation succeeds if every instance element
* at a position greater than the size of "items" validates against "additionalItems".
* Otherwise, "additionalItems" MUST be ignored, as the "items" schema
* (possibly the default value of an empty schema) is applied to all elements.
* Omitting this keyword has the same behavior as an empty schema.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.10
*/
additionalItems?: JSONSchema6Definition | undefined;
/**
* Must be a non-negative integer.
* An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.11
*/
maxItems?: number | undefined;
/**
* Must be a non-negative integer.
* An array instance is valid against "maxItems" if its size is greater than, or equal to, the value of this keyword.
* Omitting this keyword has the same behavior as a value of 0.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.12
*/
minItems?: number | undefined;
/**
* If this keyword has boolean value false, the instance validates successfully.
* If it has boolean value true, the instance validates successfully if all of its elements are unique.
* Omitting this keyword has the same behavior as a value of false.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.13
*/
uniqueItems?: boolean | undefined;
/**
* An array instance is valid against "contains" if at least one of its elements is valid against the given schema.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.14
*/
contains?: JSONSchema6Definition | undefined;
/**
* Must be a non-negative integer.
* An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.15
*/
maxProperties?: number | undefined;
/**
* Must be a non-negative integer.
* An object instance is valid against "maxProperties" if its number of properties is greater than,
* or equal to, the value of this keyword.
* Omitting this keyword has the same behavior as a value of 0.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.16
*/
minProperties?: number | undefined;
/**
* Elements of this array must be unique.
* An object instance is valid against this keyword if every item in the array is the name of a property in the instance.
* Omitting this keyword has the same behavior as an empty array.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.17
*/
required?: string[] | undefined;
/**
* This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself.
* Validation succeeds if, for each name that appears in both the instance and as a name within this keyword's value,
* the child instance for that name successfully validates against the corresponding schema.
* Omitting this keyword has the same behavior as an empty object.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.18
*/
properties?: {
[k: string]: JSONSchema6Definition;
} | undefined;
/**
* This attribute is an object that defines the schema for a set of property names of an object instance.
* The name of each property of this attribute's object is a regular expression pattern in the ECMA 262, while the value is a schema.
* If the pattern matches the name of a property on the instance object, the value of the instance's property
* MUST be valid against the pattern name's schema value.
* Omitting this keyword has the same behavior as an empty object.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.19
*/
patternProperties?: {
[k: string]: JSONSchema6Definition;
} | undefined;
/**
* This attribute defines a schema for all properties that are not explicitly defined in an object type definition.
* If specified, the value MUST be a schema or a boolean.
* If false is provided, no additional properties are allowed beyond the properties defined in the schema.
* The default value is an empty schema which allows any value for additional properties.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.20
*/
additionalProperties?: JSONSchema6Definition | undefined;
/**
* This keyword specifies rules that are evaluated if the instance is an object and contains a certain property.
* Each property specifies a dependency.
* If the dependency value is an array, each element in the array must be unique.
* Omitting this keyword has the same behavior as an empty object.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.21
*/
dependencies?: {
[k: string]: JSONSchema6Definition | string[];
} | undefined;
/**
* Takes a schema which validates the names of all properties rather than their values.
* Note the property name that the schema is testing will always be a string.
* Omitting this keyword has the same behavior as an empty schema.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.22
*/
propertyNames?: JSONSchema6Definition | undefined;
/**
* This provides an enumeration of all possible values that are valid
* for the instance property. This MUST be an array, and each item in
* the array represents a possible value for the instance value. If
* this attribute is defined, the instance value MUST be one of the
* values in the array in order for the schema to be valid.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.23
*/
enum?: JSONSchema6Type[] | undefined;
/**
* More readable form of a one-element "enum"
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.24
*/
const?: JSONSchema6Type | undefined;
/**
* A single type, or a union of simple types
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.25
*/
type?: JSONSchema6TypeName | JSONSchema6TypeName[] | undefined;
/**
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.26
*/
allOf?: JSONSchema6Definition[] | undefined;
/**
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.27
*/
anyOf?: JSONSchema6Definition[] | undefined;
/**
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.28
*/
oneOf?: JSONSchema6Definition[] | undefined;
/**
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-6.29
*/
not?: JSONSchema6Definition | undefined;
/**
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.1
*/
definitions?: {
[k: string]: JSONSchema6Definition;
} | undefined;
/**
* This attribute is a string that provides a short description of the instance property.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2
*/
title?: string | undefined;
/**
* This attribute is a string that provides a full description of the of purpose the instance property.
*
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.2
*/
description?: string | undefined;
/**
* This keyword can be used to supply a default JSON value associated with a particular schema.
* It is RECOMMENDED that a default value be valid against the associated schema.
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.3
*/
default?: JSONSchema6Type | undefined;
/**
* Array of examples with no validation effect the value of "default" is usable as an example without repeating it under this keyword
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-7.4
*/
examples?: JSONSchema6Type[] | undefined;
/**
* @see https://tools.ietf.org/html/draft-wright-json-schema-validation-01#section-8
*/
format?: string | undefined;
}
//==================================================================================================
// JSON Schema Draft 07
//==================================================================================================
// https://tools.ietf.org/html/draft-handrews-json-schema-validation-01
//--------------------------------------------------------------------------------------------------
/**
* Primitive type
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1
*/
export type JSONSchema7TypeName =
| 'string' //
| 'number'
| 'integer'
| 'boolean'
| 'object'
| 'array'
| 'null';
/**
* Primitive type
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1
*/
export type JSONSchema7Type =
| string //
| number
| boolean
| JSONSchema7Object
| JSONSchema7Array
| null;
// Workaround for infinite type recursion
export interface JSONSchema7Object {
[key: string]: JSONSchema7Type;
}
// Workaround for infinite type recursion
// https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540
export interface JSONSchema7Array extends Array<JSONSchema7Type> {}
/**
* Meta schema
*
* Recommended values:
* - 'http://json-schema.org/schema#'
* - 'http://json-schema.org/hyper-schema#'
* - 'http://json-schema.org/draft-07/schema#'
* - 'http://json-schema.org/draft-07/hyper-schema#'
*
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5
*/
export type JSONSchema7Version = string;
/**
* JSON Schema v7
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01
*/
export type JSONSchema7Definition = JSONSchema7 | boolean;
export interface JSONSchema7 {
$id?: string | undefined;
$ref?: string | undefined;
$schema?: JSONSchema7Version | undefined;
$comment?: string | undefined;
/**
* @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-00#section-8.2.4
* @see https://datatracker.ietf.org/doc/html/draft-bhutton-json-schema-validation-00#appendix-A
*/
$defs?: {
[key: string]: JSONSchema7Definition;
} | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1
*/
type?: JSONSchema7TypeName | JSONSchema7TypeName[] | undefined;
enum?: JSONSchema7Type[] | undefined;
const?: JSONSchema7Type | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2
*/
multipleOf?: number | undefined;
maximum?: number | undefined;
exclusiveMaximum?: number | undefined;
minimum?: number | undefined;
exclusiveMinimum?: number | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3
*/
maxLength?: number | undefined;
minLength?: number | undefined;
pattern?: string | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4
*/
items?: JSONSchema7Definition | JSONSchema7Definition[] | undefined;
additionalItems?: JSONSchema7Definition | undefined;
maxItems?: number | undefined;
minItems?: number | undefined;
uniqueItems?: boolean | undefined;
contains?: JSONSchema7 | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5
*/
maxProperties?: number | undefined;
minProperties?: number | undefined;
required?: string[] | undefined;
properties?: {
[key: string]: JSONSchema7Definition;
} | undefined;
patternProperties?: {
[key: string]: JSONSchema7Definition;
} | undefined;
additionalProperties?: JSONSchema7Definition | undefined;
dependencies?: {
[key: string]: JSONSchema7Definition | string[];
} | undefined;
propertyNames?: JSONSchema7Definition | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6
*/
if?: JSONSchema7Definition | undefined;
then?: JSONSchema7Definition | undefined;
else?: JSONSchema7Definition | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7
*/
allOf?: JSONSchema7Definition[] | undefined;
anyOf?: JSONSchema7Definition[] | undefined;
oneOf?: JSONSchema7Definition[] | undefined;
not?: JSONSchema7Definition | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7
*/
format?: string | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-8
*/
contentMediaType?: string | undefined;
contentEncoding?: string | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-9
*/
definitions?: {
[key: string]: JSONSchema7Definition;
} | undefined;
/**
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10
*/
title?: string | undefined;
description?: string | undefined;
default?: JSONSchema7Type | undefined;
readOnly?: boolean | undefined;
writeOnly?: boolean | undefined;
examples?: JSONSchema7Type | undefined;
}
export interface ValidationResult {
valid: boolean;
errors: ValidationError[];
}
export interface ValidationError {
property: string;
message: string;
}
/**
* To use the validator call JSONSchema.validate with an instance object and an optional schema object.
* If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
* that schema will be used to validate and the schema parameter is not necessary (if both exist,
* both validations will occur).
*/
export function validate(instance: {}, schema: JSONSchema4 | JSONSchema6 | JSONSchema7): ValidationResult;
/**
* The checkPropertyChange method will check to see if an value can legally be in property with the given schema
* This is slightly different than the validate method in that it will fail if the schema is readonly and it will
* not check for self-validation, it is assumed that the passed in value is already internally valid.
*/
export function checkPropertyChange(
value: any,
schema: JSONSchema4 | JSONSchema6 | JSONSchema7,
property: string,
): ValidationResult;
/**
* This checks to ensure that the result is valid and will throw an appropriate error message if it is not.
*/
export function mustBeValid(result: ValidationResult): void;

View File

@ -0,0 +1,40 @@
{
"name": "@types/json-schema",
"version": "7.0.11",
"description": "TypeScript definitions for json-schema 4.0, 6.0 and",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/json-schema",
"license": "MIT",
"contributors": [
{
"name": "Boris Cherny",
"url": "https://github.com/bcherny",
"githubUsername": "bcherny"
},
{
"name": "Lucian Buzzo",
"url": "https://github.com/lucianbuzzo",
"githubUsername": "lucianbuzzo"
},
{
"name": "Roland Groza",
"url": "https://github.com/rolandjitsu",
"githubUsername": "rolandjitsu"
},
{
"name": "Jason Kwok",
"url": "https://github.com/JasonHK",
"githubUsername": "JasonHK"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/json-schema"
},
"scripts": {},
"dependencies": {},
"typesPublisherContentHash": "84a402b9e31ddb097f08b5c07c08590bf087035c483db7a4071a04903775dc44",
"typeScriptVersion": "3.9"
}

View File

@ -0,0 +1,437 @@
# Changelog
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.
## [3.6.0](https://github.com/webpack-contrib/css-loader/compare/v3.5.3...v3.6.0) (2020-06-13)
### Features
* allow `modules.auto` to be a filter function ([#1086](https://github.com/webpack-contrib/css-loader/issues/1086)) ([0902353](https://github.com/webpack-contrib/css-loader/commit/0902353c328d4d18e8ed2755fe9c83c03c53df81))
### [3.5.3](https://github.com/webpack-contrib/css-loader/compare/v3.5.2...v3.5.3) (2020-04-24)
### Bug Fixes
* add file from an error to file dependencies ([841423f](https://github.com/webpack-contrib/css-loader/commit/841423fca2932c18f8ac0cf0a1f0012fc0a62fb6))
* avoid query string in source maps ([#1082](https://github.com/webpack-contrib/css-loader/issues/1082)) ([f64de13](https://github.com/webpack-contrib/css-loader/commit/f64de13f7377eff9501348cf26213212ca696913))
### [3.5.2](https://github.com/webpack-contrib/css-loader/compare/v3.5.1...v3.5.2) (2020-04-10)
### Bug Fixes
* schema for the `modules.auto` option ([#1075](https://github.com/webpack-contrib/css-loader/issues/1075)) ([8c9ffe7](https://github.com/webpack-contrib/css-loader/commit/8c9ffe7c6df11232b63173c757baa71ed36f6145))
### [3.5.1](https://github.com/webpack-contrib/css-loader/compare/v3.5.0...v3.5.1) (2020-04-07)
### Bug Fixes
* don't generate an invalid code for `locals` ([#1072](https://github.com/webpack-contrib/css-loader/issues/1072)) ([866b84a](https://github.com/webpack-contrib/css-loader/commit/866b84acd7fd47651f741ca1e6cf7081c2bbe357))
## [3.5.0](https://github.com/webpack-contrib/css-loader/compare/v3.4.2...v3.5.0) (2020-04-06)
### Features
* accept semver compatible postcss AST ([#1049](https://github.com/webpack-contrib/css-loader/issues/1049)) ([14c4faa](https://github.com/webpack-contrib/css-loader/commit/14c4faae87305c9b965de4f468bb1e118f6b84cc))
* allow to determinate css modules using the `modules.auto` option, please look at an [example](https://github.com/webpack-contrib/css-loader#pure-css-css-modules-and-postcss) of how you can simplify the configuration. ([#1067](https://github.com/webpack-contrib/css-loader/issues/1067)) ([c673cf4](https://github.com/webpack-contrib/css-loader/commit/c673cf418e901c5050bc697eb45401dc9a42c477))
* the `modules.exportGlobals` option for export global classes and ids ([#1069](https://github.com/webpack-contrib/css-loader/issues/1069)) ([519e5f4](https://github.com/webpack-contrib/css-loader/commit/519e5f41539f4c87ec96db0a908aaadecc284a6c))
* the `modules.mode` option may be a function ([#1065](https://github.com/webpack-contrib/css-loader/issues/1065)) ([0d8ac3b](https://github.com/webpack-contrib/css-loader/commit/0d8ac3bcb831bc747657c914aba106b93840737e))
### [3.4.2](https://github.com/webpack-contrib/css-loader/compare/v3.4.1...v3.4.2) (2020-01-10)
### Bug Fixes
* do not duplicate css on `composes` ([#1040](https://github.com/webpack-contrib/css-loader/issues/1040)) ([df79602](https://github.com/webpack-contrib/css-loader/commit/df7960277be20ec80e9be1a41ac53baf69847fa0))
### [3.4.1](https://github.com/webpack-contrib/css-loader/compare/v3.4.0...v3.4.1) (2020-01-03)
### Bug Fixes
* do not output `undefined` when sourceRoot is unavailable ([#1036](https://github.com/webpack-contrib/css-loader/issues/1036)) ([ded2a79](https://github.com/webpack-contrib/css-loader/commit/ded2a797271f2adf864bf92300621c024974bc79))
* don't output invalid es5 code when locals do not exists ([#1035](https://github.com/webpack-contrib/css-loader/issues/1035)) ([b60e62a](https://github.com/webpack-contrib/css-loader/commit/b60e62a655719cc1779fae7d577af6ad6cf42135))
## [3.4.0](https://github.com/webpack-contrib/css-loader/compare/v3.3.1...v3.4.0) (2019-12-17)
### Features
* `esModule` option ([#1026](https://github.com/webpack-contrib/css-loader/issues/1026)) ([d358cdb](https://github.com/webpack-contrib/css-loader/commit/d358cdbe2c026afafa0279003cb6c8a3eff4c419))
### Bug Fixes
* logic for order and media queries for imports ([#1018](https://github.com/webpack-contrib/css-loader/issues/1018)) ([65450d9](https://github.com/webpack-contrib/css-loader/commit/65450d9c04790ccc9fb06eac81ea6d8f3cdbfaac))
### [3.3.2](https://github.com/webpack-contrib/css-loader/compare/v3.3.1...v3.3.2) (2019-12-12)
### Bug Fixes
* logic for order and media queries for imports ([1fb5134](https://github.com/webpack-contrib/css-loader/commit/1fb51340a7719b6f5b517cb71ea85ec5d45c1199))
### [3.3.1](https://github.com/webpack-contrib/css-loader/compare/v3.3.0...v3.3.1) (2019-12-12)
### Bug Fixes
* better handling url functions and an url in `@import` at-rules
* reduce count of `require` ([#1014](https://github.com/webpack-contrib/css-loader/issues/1014)) ([e091d27](https://github.com/webpack-contrib/css-loader/commit/e091d2709c29ac57ed0106af8ec3b581cbda7a9c))
## [3.3.0](https://github.com/webpack-contrib/css-loader/compare/v3.2.1...v3.3.0) (2019-12-09)
### Features
* support `pure` css modules ([#1008](https://github.com/webpack-contrib/css-loader/issues/1008)) ([6177af5](https://github.com/webpack-contrib/css-loader/commit/6177af5596566fead13a8f66d5abcb4dc2b744db))
### Bug Fixes
* do not crash when an assert return `null` or `undefined` ([#1006](https://github.com/webpack-contrib/css-loader/issues/1006)) ([6769783](https://github.com/webpack-contrib/css-loader/commit/67697833725e1cff12a14663390bbe4c65ea36d2))
* reduce count of `require` ([#1004](https://github.com/webpack-contrib/css-loader/issues/1004)) ([80e9662](https://github.com/webpack-contrib/css-loader/commit/80e966280f2477c5c0e4553d3be3a04511fea381))
### [3.2.1](https://github.com/webpack-contrib/css-loader/compare/v3.2.0...v3.2.1) (2019-12-02)
### Bug Fixes
* add an additional space after the escape sequence ([#998](https://github.com/webpack-contrib/css-loader/issues/998)) ([0961304](https://github.com/webpack-contrib/css-loader/commit/0961304020832fc9ca70cc708f4366e1f868e765))
* compatibility with ES modules syntax and hash in `url` function ([#1001](https://github.com/webpack-contrib/css-loader/issues/1001)) ([8f4d6f5](https://github.com/webpack-contrib/css-loader/commit/8f4d6f508187513347106a436eda993f874065f1))
## [3.2.0](https://github.com/webpack-contrib/css-loader/compare/v3.1.0...v3.2.0) (2019-08-06)
### Bug Fixes
* replace `.` characters in localIndent to `-` character (regression) ([#982](https://github.com/webpack-contrib/css-loader/issues/982)) ([967fb66](https://github.com/webpack-contrib/css-loader/commit/967fb66))
### Features
* support es modules for assets loader ([#984](https://github.com/webpack-contrib/css-loader/issues/984)) ([9c5126c](https://github.com/webpack-contrib/css-loader/commit/9c5126c))
## [3.1.0](https://github.com/webpack-contrib/css-loader/compare/v3.0.0...v3.1.0) (2019-07-18)
### Bug Fixes
* converting all (including reserved and control) filesystem characters to `-` (it was regression in `3.0.0` version) ([#972](https://github.com/webpack-contrib/css-loader/issues/972)) ([f51859b](https://github.com/webpack-contrib/css-loader/commit/f51859b))
* default context should be undefined instead of null ([#965](https://github.com/webpack-contrib/css-loader/issues/965)) ([9c32885](https://github.com/webpack-contrib/css-loader/commit/9c32885))
### Features
* allow `modules.getLocalIdent` to return a falsy value ([#963](https://github.com/webpack-contrib/css-loader/issues/963)) ([9c3571c](https://github.com/webpack-contrib/css-loader/commit/9c3571c))
* improved validation error messages ([65e4fc0](https://github.com/webpack-contrib/css-loader/commit/65e4fc0))
## [3.0.0](https://github.com/webpack-contrib/css-loader/compare/v2.1.1...v3.0.0) (2019-06-11)
### Bug Fixes
* avoid the "from" argument must be of type string error ([#908](https://github.com/webpack-contrib/css-loader/issues/908)) ([e5dfd23](https://github.com/webpack-contrib/css-loader/commit/e5dfd23))
* invert `Function` behavior for `url` and `import` options ([#939](https://github.com/webpack-contrib/css-loader/issues/939)) ([e9eb5ad](https://github.com/webpack-contrib/css-loader/commit/e9eb5ad))
* properly export locals with escaped characters ([#917](https://github.com/webpack-contrib/css-loader/issues/917)) ([a0efcda](https://github.com/webpack-contrib/css-loader/commit/a0efcda))
* property handle non css characters in localIdentName ([#920](https://github.com/webpack-contrib/css-loader/issues/920)) ([d3a0a3c](https://github.com/webpack-contrib/css-loader/commit/d3a0a3c))
### Features
* modules options now accepts object config ([#937](https://github.com/webpack-contrib/css-loader/issues/937)) ([1d7a464](https://github.com/webpack-contrib/css-loader/commit/1d7a464))
* support `@value` at-rule in selectors ([#941](https://github.com/webpack-contrib/css-loader/issues/941)) ([05a42e2](https://github.com/webpack-contrib/css-loader/commit/05a42e2))
### BREAKING CHANGES
* minimum required nodejs version is 8.9.0
* `@value` at rules now support in `selector`, recommends checking all `@values` at-rule usage (hint: you can add prefix to all `@value` at-rules, for example `@value v-foo: black;` or `@value m-foo: screen and (max-width: 12450px)`, and then do upgrade)
* invert `{Function}` behavior for `url` and `import` options (need return `true` when you want handle `url`/`@import` and return `false` if not)
* `camelCase` option was remove in favor `localsConvention` option, also it is accept only `{String}` value (use `camelCase` value if you previously value was `true` and `asIs` if you previously value was `false`)
* `exportOnlyLocals` option was remove in favor `onlyLocals` option
* `modules` option now can be `{Object}` and allow to setup `CSS Modules` options:
* `localIdentName` option was removed in favor `modules.localIdentName` option
* `context` option was remove in favor `modules.context` option
* `hashPrefix` option was removed in favor `modules.hashPrefix` option
* `getLocalIdent` option was removed in favor `modules.getLocalIdent` option
* `localIdentRegExp` option was removed in favor `modules.localIdentRegExp` option
<a name="2.1.1"></a>
## [2.1.1](https://github.com/webpack-contrib/css-loader/compare/v2.1.0...v2.1.1) (2019-03-07)
### Bug Fixes
* do not break selector with escaping ([#896](https://github.com/webpack-contrib/css-loader/issues/896)) ([0ba8c66](https://github.com/webpack-contrib/css-loader/commit/0ba8c66))
* source map generation when `sourceRoot` is present ([#901](https://github.com/webpack-contrib/css-loader/issues/901)) ([e9ce745](https://github.com/webpack-contrib/css-loader/commit/e9ce745))
* sourcemap generating when previous loader pass sourcemap as string ([#905](https://github.com/webpack-contrib/css-loader/issues/905)) ([3797e4d](https://github.com/webpack-contrib/css-loader/commit/3797e4d))
<a name="2.1.0"></a>
# [2.1.0](https://github.com/webpack-contrib/css-loader/compare/v2.0.2...v2.1.0) (2018-12-25)
### Features
* support `image-set` without `url` ([#879](https://github.com/webpack-contrib/css-loader/issues/879)) ([21884e2](https://github.com/webpack-contrib/css-loader/commit/21884e2))
<a name="2.0.2"></a>
## [2.0.2](https://github.com/webpack-contrib/css-loader/compare/v2.0.1...v2.0.2) (2018-12-21)
### Bug Fixes
* inappropriate modification of animation keywords ([#876](https://github.com/webpack-contrib/css-loader/issues/876)) ([dfb2f8e](https://github.com/webpack-contrib/css-loader/commit/dfb2f8e))
<a name="2.0.1"></a>
# [2.0.1](https://github.com/webpack-contrib/css-loader/compare/v2.0.0...v2.0.1) (2018-12-14)
### Bug Fixes
* safe checking if params are present for at rule ([#871](https://github.com/webpack-contrib/css-loader/issues/871)) ([a88fed1](https://github.com/webpack-contrib/css-loader/commit/a88fed1))
* `getLocalIdent` now accepts `false` value ([#865](https://github.com/webpack-contrib/css-loader/issues/865)) ([1825e8a](https://github.com/webpack-contrib/css-loader/commit/1825e8a))
<a name="2.0.0"></a>
# [2.0.0](https://github.com/webpack-contrib/css-loader/compare/v1.0.1...v2.0.0) (2018-12-07)
### Bug Fixes
* broken unucode characters ([#850](https://github.com/webpack-contrib/css-loader/issues/850)) ([f599c70](https://github.com/webpack-contrib/css-loader/commit/f599c70))
* correctly processing `urls()` with `?#hash` ([#803](https://github.com/webpack-contrib/css-loader/issues/803)) ([417d105](https://github.com/webpack-contrib/css-loader/commit/417d105))
* don't break loader on invalid or not exists url or import token ([#827](https://github.com/webpack-contrib/css-loader/issues/827)) ([9e52d26](https://github.com/webpack-contrib/css-loader/commit/9e52d26))
* don't duplicate import with same media in different case ([#819](https://github.com/webpack-contrib/css-loader/issues/819)) ([9f66e33](https://github.com/webpack-contrib/css-loader/commit/9f66e33))
* emit warnings on broken `import` at-rules ([#806](https://github.com/webpack-contrib/css-loader/issues/806)) ([4bdf08b](https://github.com/webpack-contrib/css-loader/commit/4bdf08b))
* handle uppercase `URL` in `import` at-rules ([#818](https://github.com/webpack-contrib/css-loader/issues/818)) ([3ebdcd5](https://github.com/webpack-contrib/css-loader/commit/3ebdcd5))
* inconsistent generate class names for css modules on difference os ([#812](https://github.com/webpack-contrib/css-loader/issues/812)) ([0bdf9b7](https://github.com/webpack-contrib/css-loader/commit/0bdf9b7))
* reduce number of `require` for `urls()` ([#854](https://github.com/webpack-contrib/css-loader/issues/854)) ([3338656](https://github.com/webpack-contrib/css-loader/commit/3338656))
* support deduplication of string module ids (optimization.namedModules) ([#789](https://github.com/webpack-contrib/css-loader/issues/789)) ([e3bb83a](https://github.com/webpack-contrib/css-loader/commit/e3bb83a))
* support module resolution in `composes` ([#845](https://github.com/webpack-contrib/css-loader/issues/845)) ([453248f](https://github.com/webpack-contrib/css-loader/commit/453248f))
* same `urls()` resolving logic for `modules` (`local` and `global`) and without modules ([#843](https://github.com/webpack-contrib/css-loader/issues/843)) ([fdcf687](https://github.com/webpack-contrib/css-loader/commit/fdcf687))
### Features
* allow to disable css modules and **disable their by default** ([#842](https://github.com/webpack-contrib/css-loader/issues/842)) ([889dc7f](https://github.com/webpack-contrib/css-loader/commit/889dc7f))
* disable `import` option doesn't affect on `composes` ([#822](https://github.com/webpack-contrib/css-loader/issues/822)) ([f9aa73c](https://github.com/webpack-contrib/css-loader/commit/f9aa73c))
* allow to filter `urls` ([#856](https://github.com/webpack-contrib/css-loader/issues/856)) ([5e702e7](https://github.com/webpack-contrib/css-loader/commit/5e702e7))
* allow to filter `import` at-rules ([#857](https://github.com/webpack-contrib/css-loader/issues/857)) ([5e6034c](https://github.com/webpack-contrib/css-loader/commit/5e6034c))
* emit warning on invalid `urls()` ([#832](https://github.com/webpack-contrib/css-loader/issues/832)) ([da95db8](https://github.com/webpack-contrib/css-loader/commit/da95db8))
* added `exportOnlyLocals` option ([#824](https://github.com/webpack-contrib/css-loader/issues/824)) ([e9327c0](https://github.com/webpack-contrib/css-loader/commit/e9327c0))
* reuse `postcss` ast from other loaders (i.e `postcss-loader`) ([#840](https://github.com/webpack-contrib/css-loader/issues/840)) ([1dad1fb](https://github.com/webpack-contrib/css-loader/commit/1dad1fb))
* schema options ([b97d997](https://github.com/webpack-contrib/css-loader/commit/b97d997))
### BREAKING CHANGES
* resolving logic for `url()` and `import` at-rules works the same everywhere, it does not matter whether css modules are enabled (with `global` and `local` module) or not. Examples - `url('image.png')` as `require('./image.png')`, `url('./image.png')` as `require('./image.png')`, `url('~module/image.png')` as `require('module/image.png')`.
* by default css modules are disabled (now `modules: false` disable all css modules features), you can return old behaviour change this on `modules: 'global'`
* `css-loader/locals` was dropped in favor `exportOnlyLocals` option
* `import` option only affect on `import` at-rules and doesn't affect on `composes` declarations
* invalid `@import` at rules now emit warnings
* use `postcss@7`
<a name="1.0.1"></a>
## [1.0.1](https://github.com/webpack-contrib/css-loader/compare/v1.0.0...v1.0.1) (2018-10-29)
### Bug Fixes
* **loader:** trim unquoted import urls ([#783](https://github.com/webpack-contrib/css-loader/issues/783)) ([21fcddf](https://github.com/webpack-contrib/css-loader/commit/21fcddf))
<a name="1.0.0"></a>
# [1.0.0](https://github.com/webpack-contrib/css-loader/compare/v0.28.11...v1.0.0) (2018-07-06)
### BREAKING CHANGES
* remove `minimize` option, use [`postcss-loader`](https://github.com/postcss/postcss-loader) with [`cssnano`](https://github.com/cssnano/cssnano) or use [`optimize-cssnano-plugin`](https://github.com/intervolga/optimize-cssnano-plugin) plugin
* remove `module` option, use `modules` option instead
* remove `camelcase` option, use `camelCase` option instead
* remove `root` option, use [`postcss-loader`](https://github.com/postcss/postcss-loader) with [`postcss-url`](https://github.com/postcss/postcss-url) plugin
* remove `alias` option, use [`resolve.alias`](https://webpack.js.org/configuration/resolve/) feature or use [`postcss-loader`](https://github.com/postcss/postcss-loader) with [`postcss-url`](https://github.com/postcss/postcss-url) plugin
* update `postcss` to `6` version
* minimum require `nodejs` version is `6.9`
* minimum require `webpack` version is `4`
<a name="0.28.11"></a>
## [0.28.11](https://github.com/webpack-contrib/css-loader/compare/v0.28.10...v0.28.11) (2018-03-16)
### Bug Fixes
* **lib/processCss:** don't check `mode` for `url` handling (`options.modules`) ([#698](https://github.com/webpack-contrib/css-loader/issues/698)) ([c788450](https://github.com/webpack-contrib/css-loader/commit/c788450))
<a name="0.28.10"></a>
## [0.28.10](https://github.com/webpack-contrib/css-loader/compare/v0.28.9...v0.28.10) (2018-02-22)
### Bug Fixes
* **getLocalIdent:** add `rootContext` support (`webpack >= v4.0.0`) ([#681](https://github.com/webpack-contrib/css-loader/issues/681)) ([9f876d2](https://github.com/webpack-contrib/css-loader/commit/9f876d2))
<a name="0.28.9"></a>
## [0.28.9](https://github.com/webpack-contrib/css-loader/compare/v0.28.8...v0.28.9) (2018-01-17)
### Bug Fixes
* ignore invalid URLs (`url()`) ([#663](https://github.com/webpack-contrib/css-loader/issues/663)) ([d1d8221](https://github.com/webpack-contrib/css-loader/commit/d1d8221))
<a name="0.28.8"></a>
## [0.28.8](https://github.com/webpack-contrib/css-loader/compare/v0.28.7...v0.28.8) (2018-01-05)
### Bug Fixes
* **loader:** correctly check if source map is `undefined` ([#641](https://github.com/webpack-contrib/css-loader/issues/641)) ([0dccfa9](https://github.com/webpack-contrib/css-loader/commit/0dccfa9))
* proper URL escaping and wrapping (`url()`) ([#627](https://github.com/webpack-contrib/css-loader/issues/627)) ([8897d44](https://github.com/webpack-contrib/css-loader/commit/8897d44))
<a name="0.28.7"></a>
## [0.28.7](https://github.com/webpack/css-loader/compare/v0.28.6...v0.28.7) (2017-08-30)
### Bug Fixes
* pass resolver to `localsLoader` (`options.alias`) ([#601](https://github.com/webpack/css-loader/issues/601)) ([8f1b57c](https://github.com/webpack/css-loader/commit/8f1b57c))
<a name="0.28.6"></a>
## [0.28.6](https://github.com/webpack/css-loader/compare/v0.28.5...v0.28.6) (2017-08-30)
### Bug Fixes
* add support for aliases starting with `/` (`options.alias`) ([#597](https://github.com/webpack/css-loader/issues/597)) ([63567f2](https://github.com/webpack/css-loader/commit/63567f2))
<a name="0.28.5"></a>
## [0.28.5](https://github.com/webpack/css-loader/compare/v0.28.4...v0.28.5) (2017-08-17)
### Bug Fixes
* match mutliple dashes (`options.camelCase`) ([#556](https://github.com/webpack/css-loader/issues/556)) ([1fee601](https://github.com/webpack/css-loader/commit/1fee601))
* stricter `[@import](https://github.com/import)` tolerance ([#593](https://github.com/webpack/css-loader/issues/593)) ([2e4ec09](https://github.com/webpack/css-loader/commit/2e4ec09))
<a name="0.28.4"></a>
## [0.28.4](https://github.com/webpack/css-loader/compare/v0.28.3...v0.28.4) (2017-05-30)
### Bug Fixes
* preserve leading underscore in class names ([#543](https://github.com/webpack/css-loader/issues/543)) ([f6673c8](https://github.com/webpack/css-loader/commit/f6673c8))
<a name="0.28.3"></a>
## [0.28.3](https://github.com/webpack/css-loader/compare/v0.28.2...v0.28.3) (2017-05-25)
### Bug Fixes
* correct plugin order for CSS Modules ([#534](https://github.com/webpack/css-loader/issues/534)) ([b90f492](https://github.com/webpack/css-loader/commit/b90f492))
<a name="0.28.2"></a>
## [0.28.2](https://github.com/webpack/css-loader/compare/v0.28.1...v0.28.2) (2017-05-22)
### Bug Fixes
* source maps path on `windows` ([#532](https://github.com/webpack/css-loader/issues/532)) ([c3d0d91](https://github.com/webpack/css-loader/commit/c3d0d91))
<a name="0.28.1"></a>
## [0.28.1](https://github.com/webpack/css-loader/compare/v0.28.0...v0.28.1) (2017-05-02)
### Bug Fixes
* allow to specify a full hostname as a root URL ([#521](https://github.com/webpack/css-loader/issues/521)) ([06d27a1](https://github.com/webpack/css-loader/commit/06d27a1))
* case insensitivity of [@import](https://github.com/import) ([#514](https://github.com/webpack/css-loader/issues/514)) ([de4356b](https://github.com/webpack/css-loader/commit/de4356b))
* don't handle empty [@import](https://github.com/import) and url() ([#513](https://github.com/webpack/css-loader/issues/513)) ([868fc94](https://github.com/webpack/css-loader/commit/868fc94))
* imported variables are replaced in exports if followed by a comma ([#504](https://github.com/webpack/css-loader/issues/504)) ([956bad7](https://github.com/webpack/css-loader/commit/956bad7))
* loader now correctly handles `url` with space(s) ([#495](https://github.com/webpack/css-loader/issues/495)) ([534ea55](https://github.com/webpack/css-loader/commit/534ea55))
* url with a trailing space is now handled correctly ([#494](https://github.com/webpack/css-loader/issues/494)) ([e1ec4f2](https://github.com/webpack/css-loader/commit/e1ec4f2))
* use `btoa` instead `Buffer` ([#501](https://github.com/webpack/css-loader/issues/501)) ([fbb0714](https://github.com/webpack/css-loader/commit/fbb0714))
### Performance Improvements
* generate source maps only when explicitly set ([#478](https://github.com/webpack/css-loader/issues/478)) ([b8f5c8f](https://github.com/webpack/css-loader/commit/b8f5c8f))
<a name="0.28.0"></a>
# [0.28.0](https://github.com/webpack/css-loader/compare/v0.27.3...v0.28.0) (2017-03-30)
### Features
* add alias feature to rewrite URLs ([#274](https://github.com/webpack/css-loader/issues/274)) ([c8db489](https://github.com/webpack/css-loader/commit/c8db489))
<a name="0.27.3"></a>
## [0.27.3](https://github.com/webpack/css-loader/compare/v0.27.2...v0.27.3) (2017-03-13)
<a name="0.27.2"></a>
# [0.27.2](https://github.com/webpack/css-loader/compare/v0.27.1...v0.27.2) (2017-03-12)
<a name="0.27.1"></a>
# [0.27.1](https://github.com/webpack/css-loader/compare/v0.27.0...v0.27.1) (2017-03-10)
<a name="0.27.0"></a>
# [0.27.0](https://github.com/webpack/css-loader/compare/v0.26.2...v0.27.0) (2017-03-10)
### Bug Fixes
* **sourcemaps:** use abs paths & remove sourceRoot ([c769ac3](https://github.com/webpack/css-loader/commit/c769ac3))
* `minimizeOptions` should be `query.minimize`! ([16c0858](https://github.com/webpack/css-loader/commit/16c0858))
* do not export duplicate keys ([#420](https://github.com/webpack/css-loader/issues/420)) ([a2b85d7](https://github.com/webpack/css-loader/commit/a2b85d7))
### Features
* allow removal of original class name ([#445](https://github.com/webpack/css-loader/issues/445)) ([3f78361](https://github.com/webpack/css-loader/commit/3f78361))
* Include the sourceMappingURL & sourceURL when toString() ([6da7e90](https://github.com/webpack/css-loader/commit/6da7e90))

File diff suppressed because it is too large Load Diff

View File

@ -4,32 +4,35 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class CssSyntaxError extends Error {
constructor(error) {
super(error);
const {
reason,
line,
column,
file
column
} = error;
this.name = "CssSyntaxError";
// Based on https://github.com/postcss/postcss/blob/master/lib/css-syntax-error.es6#L132
this.name = 'CssSyntaxError'; // Based on https://github.com/postcss/postcss/blob/master/lib/css-syntax-error.es6#L132
// We don't need `plugin` and `file` properties.
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
if (typeof line !== 'undefined') {
this.message += `(${line}:${column}) `;
}
this.message += file ? `${file} ` : "<css input> ";
this.message += `${reason}`;
const code = error.showSourceCode();
if (code) {
this.message += `\n\n${code}\n`;
}
} // We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
// We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
this.stack = false;
}
}
exports.default = CssSyntaxError;

View File

@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
class Warning extends Error {
constructor(warning) {
super(warning);
@ -12,18 +13,20 @@ class Warning extends Error {
line,
column
} = warning;
this.name = "Warning";
// Based on https://github.com/postcss/postcss/blob/master/lib/warning.es6#L74
this.name = 'Warning'; // Based on https://github.com/postcss/postcss/blob/master/lib/warning.es6#L74
// We don't need `plugin` properties.
this.message = `${this.name}\n\n`;
if (typeof line !== "undefined") {
if (typeof line !== 'undefined') {
this.message += `(${line}:${column}) `;
}
this.message += `${text}`;
// We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
this.message += `${text}`; // We don't need stack https://github.com/postcss/postcss/blob/master/docs/guidelines/runner.md#31-dont-show-js-stack-for-csssyntaxerror
this.stack = false;
}
}
exports.default = Warning;

View File

@ -1,5 +1,5 @@
"use strict";
const loader = require("./index");
const loader = require('./index');
module.exports = loader.default;
module.exports.defaultGetLocalIdent = require("./utils").defaultGetLocalIdent;

View File

@ -4,156 +4,140 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = loader;
var _loaderUtils = require("loader-utils");
var _postcss = _interopRequireDefault(require("postcss"));
var _package = _interopRequireDefault(require("postcss/package.json"));
var _schemaUtils = _interopRequireDefault(require("schema-utils"));
var _semver = require("semver");
var _CssSyntaxError = _interopRequireDefault(require("./CssSyntaxError"));
var _Warning = _interopRequireDefault(require("./Warning"));
var _options = _interopRequireDefault(require("./options.json"));
var _plugins = require("./plugins");
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
async function loader(content, map, meta) {
const rawOptions = this.getOptions(_options.default);
const plugins = [];
function loader(content, map, meta) {
const options = (0, _loaderUtils.getOptions)(this) || {};
(0, _schemaUtils.default)(_options.default, options, {
name: 'CSS Loader',
baseDataPath: 'options'
});
const callback = this.async();
let options;
try {
options = (0, _utils.normalizeOptions)(rawOptions, this);
} catch (error) {
callback(error);
return;
}
const replacements = [];
const exports = [];
if ((0, _utils.shouldUseModulesPlugins)(options)) {
const sourceMap = options.sourceMap || false;
const plugins = [];
if ((0, _utils.shouldUseModulesPlugins)(options.modules, this.resourcePath)) {
plugins.push(...(0, _utils.getModulesPlugins)(options, this));
}
const importPluginImports = [];
const importPluginApi = [];
let isSupportAbsoluteURL = false;
// TODO enable by default in the next major release
if (this._compilation && this._compilation.options && this._compilation.options.experiments && this._compilation.options.experiments.buildHttp) {
isSupportAbsoluteURL = true;
}
const isSupportDataURL = options.esModule && Boolean("fsStartTime" in this._compiler);
if ((0, _utils.shouldUseImportPlugin)(options)) {
const exportType = options.onlyLocals ? 'locals' : 'full';
const preRequester = (0, _utils.getPreRequester)(this);
const urlHandler = url => (0, _loaderUtils.stringifyRequest)(this, preRequester(options.importLoaders) + url);
plugins.push((0, _plugins.icssParser)({
urlHandler
}));
if (options.import !== false && exportType === 'full') {
plugins.push((0, _plugins.importParser)({
isSupportAbsoluteURL: false,
isSupportDataURL: false,
isCSSStyleSheet: options.exportType === "css-style-sheet",
loaderContext: this,
imports: importPluginImports,
api: importPluginApi,
filter: options.import.filter,
urlHandler: url => (0, _utils.stringifyRequest)(this, (0, _utils.combineRequests)((0, _utils.getPreRequester)(this)(options.importLoaders), url))
filter: (0, _utils.getFilter)(options.import, this.resourcePath),
urlHandler
}));
}
const urlPluginImports = [];
if ((0, _utils.shouldUseURLPlugin)(options)) {
const needToResolveURL = !options.esModule;
if (options.url !== false && exportType === 'full') {
plugins.push((0, _plugins.urlParser)({
isSupportAbsoluteURL,
isSupportDataURL,
imports: urlPluginImports,
replacements,
context: this.context,
rootContext: this.rootContext,
filter: (0, _utils.getFilter)(options.url.filter, this.resourcePath),
resolver: needToResolveURL ? this.getResolve({
mainFiles: [],
extensions: []
}) :
// eslint-disable-next-line no-undefined
undefined,
urlHandler: url => (0, _utils.stringifyRequest)(this, url)
// Support data urls as input in new URL added in webpack@5.38.0
filter: (0, _utils.getFilter)(options.url, this.resourcePath, value => (0, _loaderUtils.isUrlRequest)(value)),
urlHandler: url => (0, _loaderUtils.stringifyRequest)(this, url)
}));
}
} // Reuse CSS AST (PostCSS AST e.g 'postcss-loader') to avoid reparsing
const icssPluginImports = [];
const icssPluginApi = [];
const needToUseIcssPlugin = (0, _utils.shouldUseIcssPlugin)(options);
if (needToUseIcssPlugin) {
plugins.push((0, _plugins.icssParser)({
loaderContext: this,
imports: icssPluginImports,
api: icssPluginApi,
replacements,
exports,
urlHandler: url => (0, _utils.stringifyRequest)(this, (0, _utils.combineRequests)((0, _utils.getPreRequester)(this)(options.importLoaders), url))
}));
}
// Reuse CSS AST (PostCSS AST e.g 'postcss-loader') to avoid reparsing
if (meta) {
const {
ast
} = meta;
if (ast && ast.type === "postcss" && (0, _semver.satisfies)(ast.version, `^${_package.default.version}`)) {
if (ast && ast.type === 'postcss' && (0, _semver.satisfies)(ast.version, `^${_package.default.version}`)) {
// eslint-disable-next-line no-param-reassign
content = ast.root;
}
}
const {
resourcePath
} = this;
let result;
try {
result = await (0, _postcss.default)(plugins).process(content, {
hideNothingWarning: true,
from: resourcePath,
to: resourcePath,
map: options.sourceMap ? {
prev: map ? (0, _utils.normalizeSourceMap)(map, resourcePath) : null,
inline: false,
annotation: false
} : false
});
} catch (error) {
(0, _postcss.default)(plugins).process(content, {
from: this.resourcePath,
to: this.resourcePath,
map: options.sourceMap ? {
// Some loaders (example `"postcss-loader": "1.x.x"`) always generates source map, we should remove it
prev: sourceMap && map ? (0, _utils.normalizeSourceMap)(map) : null,
inline: false,
annotation: false
} : false
}).then(result => {
for (const warning of result.warnings()) {
this.emitWarning(new _Warning.default(warning));
}
const imports = [];
const apiImports = [];
const urlReplacements = [];
const icssReplacements = [];
const exports = [];
for (const message of result.messages) {
// eslint-disable-next-line default-case
switch (message.type) {
case 'import':
imports.push(message.value);
break;
case 'api-import':
apiImports.push(message.value);
break;
case 'url-replacement':
urlReplacements.push(message.value);
break;
case 'icss-replacement':
icssReplacements.push(message.value);
break;
case 'export':
exports.push(message.value);
break;
}
}
const {
localsConvention
} = options;
const esModule = typeof options.esModule !== 'undefined' ? options.esModule : false;
const importCode = (0, _utils.getImportCode)(this, exportType, imports, esModule);
const moduleCode = (0, _utils.getModuleCode)(result, exportType, sourceMap, apiImports, urlReplacements, icssReplacements, esModule);
const exportCode = (0, _utils.getExportCode)(exports, exportType, localsConvention, icssReplacements, esModule);
return callback(null, `${importCode}${moduleCode}${exportCode}`);
}).catch(error => {
if (error.file) {
this.addDependency(error.file);
}
callback(error.name === "CssSyntaxError" ? new _CssSyntaxError.default(error) : error);
return;
}
for (const warning of result.warnings()) {
this.emitWarning(new _Warning.default(warning));
}
const imports = [].concat(icssPluginImports.sort(_utils.sort)).concat(importPluginImports.sort(_utils.sort)).concat(urlPluginImports.sort(_utils.sort));
const api = [].concat(importPluginApi.sort(_utils.sort)).concat(icssPluginApi.sort(_utils.sort));
if (options.modules.exportOnlyLocals !== true) {
imports.unshift({
type: "api_import",
importName: "___CSS_LOADER_API_IMPORT___",
url: (0, _utils.stringifyRequest)(this, require.resolve("./runtime/api"))
});
if (options.sourceMap) {
imports.unshift({
importName: "___CSS_LOADER_API_SOURCEMAP_IMPORT___",
url: (0, _utils.stringifyRequest)(this, require.resolve("./runtime/sourceMaps"))
});
} else {
imports.unshift({
importName: "___CSS_LOADER_API_NO_SOURCEMAP_IMPORT___",
url: (0, _utils.stringifyRequest)(this, require.resolve("./runtime/noSourceMaps"))
});
}
}
const importCode = (0, _utils.getImportCode)(imports, options);
let moduleCode;
try {
moduleCode = (0, _utils.getModuleCode)(result, api, replacements, options, this);
} catch (error) {
callback(error);
return;
}
const exportCode = (0, _utils.getExportCode)(exports, replacements, needToUseIcssPlugin, options);
callback(null, `${importCode}${moduleCode}${exportCode}`);
callback(error.name === 'CssSyntaxError' ? new _CssSyntaxError.default(error) : error);
});
}

View File

@ -1,60 +1,42 @@
{
"title": "CSS Loader options",
"additionalProperties": false,
"properties": {
"url": {
"description": "Allows to enables/disables `url()`/`image-set()` functions handling.",
"link": "https://github.com/webpack-contrib/css-loader#url",
"description": "Enables/Disables 'url'/'image-set' functions handling (https://github.com/webpack-contrib/css-loader#url).",
"anyOf": [
{
"type": "boolean"
},
{
"type": "object",
"properties": {
"filter": {
"instanceof": "Function"
}
},
"additionalProperties": false
"instanceof": "Function"
}
]
},
"import": {
"description": "Allows to enables/disables `@import` at-rules handling.",
"link": "https://github.com/webpack-contrib/css-loader#import",
"description": "Enables/Disables '@import' at-rules handling (https://github.com/webpack-contrib/css-loader#import).",
"anyOf": [
{
"type": "boolean"
},
{
"type": "object",
"properties": {
"filter": {
"instanceof": "Function"
}
},
"additionalProperties": false
"instanceof": "Function"
}
]
},
"modules": {
"description": "Allows to enable/disable CSS Modules or ICSS and setup configuration.",
"link": "https://github.com/webpack-contrib/css-loader#modules",
"description": "Enables/Disables CSS Modules and their configuration (https://github.com/webpack-contrib/css-loader#modules).",
"anyOf": [
{
"type": "boolean"
},
{
"enum": ["local", "global", "pure", "icss"]
"enum": ["local", "global", "pure"]
},
{
"type": "object",
"additionalProperties": false,
"properties": {
"auto": {
"description": "Allows auto enable CSS modules based on filename.",
"link": "https://github.com/webpack-contrib/css-loader#auto",
"anyOf": [
{
"instanceof": "RegExp"
@ -68,141 +50,77 @@
]
},
"mode": {
"description": "Setup `mode` option.",
"link": "https://github.com/webpack-contrib/css-loader#mode",
"anyOf": [
{
"enum": ["local", "global", "pure", "icss"]
"enum": ["local", "global", "pure"]
},
{
"instanceof": "Function"
}
]
},
"exportGlobals": {
"type": "boolean"
},
"localIdentName": {
"description": "Allows to configure the generated local ident name.",
"link": "https://github.com/webpack-contrib/css-loader#localidentname",
"type": "string",
"minLength": 1
},
"localIdentContext": {
"description": "Allows to redefine basic loader context for local ident name.",
"link": "https://github.com/webpack-contrib/css-loader#localidentcontext",
"type": "string",
"minLength": 1
},
"localIdentHashSalt": {
"description": "Allows to add custom hash to generate more unique classes.",
"link": "https://github.com/webpack-contrib/css-loader#localidenthashsalt",
"type": "string",
"minLength": 1
},
"localIdentHashFunction": {
"description": "Allows to specify hash function to generate classes.",
"link": "https://github.com/webpack-contrib/css-loader#localidenthashfunction",
"type": "string",
"minLength": 1
},
"localIdentHashDigest": {
"description": "Allows to specify hash digest to generate classes.",
"link": "https://github.com/webpack-contrib/css-loader#localidenthashdigest",
"type": "string",
"minLength": 1
},
"localIdentHashDigestLength": {
"description": "Allows to specify hash digest length to generate classes.",
"link": "https://github.com/webpack-contrib/css-loader#localidenthashdigestlength",
"type": "number"
},
"hashStrategy": {
"description": "Allows to specify should localName be used when computing the hash.",
"link": "https://github.com/webpack-contrib/css-loader#hashstrategy",
"enum": ["resource-path-and-local-name", "minimal-subset"]
"type": "string"
},
"localIdentRegExp": {
"description": "Allows to specify custom RegExp for local ident name.",
"link": "https://github.com/webpack-contrib/css-loader#localidentregexp",
"anyOf": [
{
"type": "string",
"minLength": 1
"type": "string"
},
{
"instanceof": "RegExp"
}
]
},
"context": {
"type": "string"
},
"hashPrefix": {
"type": "string"
},
"getLocalIdent": {
"description": "Allows to specify a function to generate the classname.",
"link": "https://github.com/webpack-contrib/css-loader#getlocalident",
"instanceof": "Function"
},
"namedExport": {
"description": "Enables/disables ES modules named export for locals.",
"link": "https://github.com/webpack-contrib/css-loader#namedexport",
"type": "boolean"
},
"exportGlobals": {
"description": "Allows to export names from global class or id, so you can use that as local name.",
"link": "https://github.com/webpack-contrib/css-loader#exportglobals",
"type": "boolean"
},
"exportLocalsConvention": {
"description": "Style of exported classnames.",
"link": "https://github.com/webpack-contrib/css-loader#localsconvention",
"anyOf": [
{
"enum": [
"asIs",
"camelCase",
"camelCaseOnly",
"dashes",
"dashesOnly"
]
"type": "boolean"
},
{
"instanceof": "Function"
}
]
},
"exportOnlyLocals": {
"description": "Export only locals.",
"link": "https://github.com/webpack-contrib/css-loader#exportonlylocals",
"type": "boolean"
}
}
}
]
},
"sourceMap": {
"description": "Allows to enable/disable source maps.",
"link": "https://github.com/webpack-contrib/css-loader#sourcemap",
"description": "Enables/Disables generation of source maps (https://github.com/webpack-contrib/css-loader#sourcemap).",
"type": "boolean"
},
"importLoaders": {
"description": "Allows enables/disables or setups number of loaders applied before CSS loader for `@import`/CSS Modules and ICSS imports.",
"link": "https://github.com/webpack-contrib/css-loader#importloaders",
"description": "Enables/Disables or setups number of loaders applied before CSS loader (https://github.com/webpack-contrib/css-loader#importloaders).",
"anyOf": [
{
"type": "boolean"
},
{
"type": "string"
},
{
"type": "integer"
}
]
},
"esModule": {
"description": "Use the ES modules syntax.",
"link": "https://github.com/webpack-contrib/css-loader#esmodule",
"localsConvention": {
"description": "Style of exported classnames (https://github.com/webpack-contrib/css-loader#localsconvention).",
"enum": ["asIs", "camelCase", "camelCaseOnly", "dashes", "dashesOnly"]
},
"onlyLocals": {
"description": "Export only locals (https://github.com/webpack-contrib/css-loader#onlylocals).",
"type": "boolean"
},
"exportType": {
"description": "Allows exporting styles as array with modules, string or constructable stylesheet (i.e. `CSSStyleSheet`).",
"link": "https://github.com/webpack-contrib/css-loader#exporttype",
"enum": ["array", "string", "css-style-sheet"]
"esModule": {
"description": "Use the ES modules syntax (https://github.com/webpack-contrib/css-loader#esmodule).",
"type": "boolean"
}
},
"type": "object"

View File

@ -3,25 +3,29 @@
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "icssParser", {
enumerable: true,
get: function () {
return _postcssIcssParser.default;
}
});
Object.defineProperty(exports, "importParser", {
enumerable: true,
get: function () {
return _postcssImportParser.default;
}
});
Object.defineProperty(exports, "icssParser", {
enumerable: true,
get: function () {
return _postcssIcssParser.default;
}
});
Object.defineProperty(exports, "urlParser", {
enumerable: true,
get: function () {
return _postcssUrlParser.default;
}
});
var _postcssImportParser = _interopRequireDefault(require("./postcss-import-parser"));
var _postcssIcssParser = _interopRequireDefault(require("./postcss-icss-parser"));
var _postcssUrlParser = _interopRequireDefault(require("./postcss-url-parser"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

View File

@ -4,111 +4,97 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
var _icssUtils = require("icss-utils");
var _utils = require("../utils");
const plugin = (options = {}) => {
return {
postcssPlugin: "postcss-icss-parser",
async OnceExit(root) {
const importReplacements = Object.create(null);
const {
icssImports,
icssExports
} = (0, _icssUtils.extractICSS)(root);
const imports = new Map();
const tasks = [];
const {
loaderContext
} = options;
const resolver = loaderContext.getResolve({
dependencyType: "icss",
conditionNames: ["style"],
extensions: ["..."],
mainFields: ["css", "style", "main", "..."],
mainFiles: ["index", "..."],
preferRelative: true
});
// eslint-disable-next-line guard-for-in
for (const url in icssImports) {
const tokens = icssImports[url];
if (Object.keys(tokens).length === 0) {
// eslint-disable-next-line no-continue
continue;
}
let normalizedUrl = url;
let prefix = "";
const queryParts = normalizedUrl.split("!");
if (queryParts.length > 1) {
normalizedUrl = queryParts.pop();
prefix = queryParts.join("!");
}
const request = (0, _utils.requestify)((0, _utils.normalizeUrl)(normalizedUrl, true), loaderContext.rootContext);
const doResolve = async () => {
const resolvedUrl = await (0, _utils.resolveRequests)(resolver, loaderContext.context, [...new Set([normalizedUrl, request])]);
if (!resolvedUrl) {
return;
}
var _loaderUtils = require("loader-utils");
// eslint-disable-next-line consistent-return
return {
url: resolvedUrl,
prefix,
tokens
};
};
tasks.push(doResolve());
}
const results = await Promise.all(tasks);
for (let index = 0; index <= results.length - 1; index++) {
const item = results[index];
if (!item) {
// eslint-disable-next-line no-continue
continue;
}
const newUrl = item.prefix ? `${item.prefix}!${item.url}` : item.url;
const importKey = newUrl;
let importName = imports.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_ICSS_IMPORT_${imports.size}___`;
imports.set(importKey, importName);
options.imports.push({
type: "icss_import",
importName,
url: options.urlHandler(newUrl),
icss: true,
index
});
options.api.push({
importName,
dedupe: true,
index
});
}
for (const [replacementIndex, token] of Object.keys(item.tokens).entries()) {
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${index}_REPLACEMENT_${replacementIndex}___`;
const localName = item.tokens[token];
importReplacements[token] = replacementName;
options.replacements.push({
replacementName,
importName,
localName
});
}
}
if (Object.keys(importReplacements).length > 0) {
(0, _icssUtils.replaceSymbols)(root, importReplacements);
}
for (const name of Object.keys(icssExports)) {
const value = (0, _icssUtils.replaceValueSymbols)(icssExports[name], importReplacements);
options.exports.push({
name,
value
});
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function makeRequestableIcssImports(icssImports) {
return Object.keys(icssImports).reduce((accumulator, url) => {
const tokensMap = icssImports[url];
const tokens = Object.keys(tokensMap);
if (tokens.length === 0) {
return accumulator;
}
};
};
plugin.postcss = true;
var _default = plugin;
const normalizedUrl = (0, _loaderUtils.urlToRequest)(url);
if (!accumulator[normalizedUrl]) {
// eslint-disable-next-line no-param-reassign
accumulator[normalizedUrl] = tokensMap;
} else {
// eslint-disable-next-line no-param-reassign
accumulator[normalizedUrl] = { ...accumulator[normalizedUrl],
...tokensMap
};
}
return accumulator;
}, {});
}
var _default = _postcss.default.plugin('postcss-icss-parser', options => (css, result) => {
const importReplacements = Object.create(null);
const extractedICSS = (0, _icssUtils.extractICSS)(css);
const icssImports = makeRequestableIcssImports(extractedICSS.icssImports);
for (const [importIndex, url] of Object.keys(icssImports).entries()) {
const importName = `___CSS_LOADER_ICSS_IMPORT_${importIndex}___`;
result.messages.push({
type: 'import',
value: {
importName,
url: options.urlHandler ? options.urlHandler(url) : url
}
}, {
type: 'api-import',
value: {
type: 'internal',
importName,
dedupe: true
}
});
const tokenMap = icssImports[url];
const tokens = Object.keys(tokenMap);
for (const [replacementIndex, token] of tokens.entries()) {
const replacementName = `___CSS_LOADER_ICSS_IMPORT_${importIndex}_REPLACEMENT_${replacementIndex}___`;
const localName = tokenMap[token];
importReplacements[token] = replacementName;
result.messages.push({
type: 'icss-replacement',
value: {
replacementName,
importName,
localName
}
});
}
}
if (Object.keys(importReplacements).length > 0) {
(0, _icssUtils.replaceSymbols)(css, importReplacements);
}
const {
icssExports
} = extractedICSS;
for (const name of Object.keys(icssExports)) {
const value = (0, _icssUtils.replaceValueSymbols)(icssExports[name], importReplacements);
result.messages.push({
type: 'export',
value: {
name,
value
}
});
}
});
exports.default = _default;

View File

@ -4,280 +4,138 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
var _loaderUtils = require("loader-utils");
var _utils = require("../utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function parseNode(atRule, key, options) {
// Convert only top-level @import
if (atRule.parent.type !== "root") {
return;
}
if (atRule.raws && atRule.raws.afterName && atRule.raws.afterName.trim().length > 0) {
const lastCommentIndex = atRule.raws.afterName.lastIndexOf("/*");
const matched = atRule.raws.afterName.slice(lastCommentIndex).match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched && matched[2] === "true") {
const pluginName = 'postcss-import-parser';
var _default = _postcss.default.plugin(pluginName, options => (css, result) => {
const importsMap = new Map();
css.walkAtRules(/^import$/i, atRule => {
// Convert only top-level @import
if (atRule.parent.type !== 'root') {
return;
} // Nodes do not exists - `@import url('http://') :root {}`
if (atRule.nodes) {
result.warn("It looks like you didn't end your @import statement correctly. Child nodes are attached to it.", {
node: atRule
});
return;
}
}
const prevNode = atRule.prev();
if (prevNode && prevNode.type === "comment") {
const matched = prevNode.text.match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched && matched[2] === "true") {
const {
nodes
} = (0, _postcssValueParser.default)(atRule.params); // No nodes - `@import ;`
// Invalid type - `@import foo-bar;`
if (nodes.length === 0 || nodes[0].type !== 'string' && nodes[0].type !== 'function') {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule
});
return;
}
}
// Nodes do not exists - `@import url('http://') :root {}`
if (atRule.nodes) {
const error = new Error("It looks like you didn't end your @import statement correctly. Child nodes are attached to it.");
error.node = atRule;
throw error;
}
const rawParams = atRule.raws && atRule.raws[key] && typeof atRule.raws[key].raw !== "undefined" ? atRule.raws[key].raw : atRule[key];
const {
nodes: paramsNodes
} = (0, _postcssValueParser.default)(rawParams);
let isStringValue;
let url;
// No nodes - `@import ;`
// Invalid type - `@import foo-bar;`
if (paramsNodes.length === 0 || paramsNodes[0].type !== "string" && paramsNodes[0].type !== "function") {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
let isStringValue;
let url;
if (paramsNodes[0].type === "string") {
isStringValue = true;
url = paramsNodes[0].value;
} else {
// Invalid function - `@import nourl(test.css);`
if (paramsNodes[0].value.toLowerCase() !== "url") {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
if (nodes[0].type === 'string') {
isStringValue = true;
url = nodes[0].value;
} else if (nodes[0].type === 'function') {
// Invalid function - `@import nourl(test.css);`
if (nodes[0].value.toLowerCase() !== 'url') {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule
});
return;
}
isStringValue = nodes[0].nodes.length !== 0 && nodes[0].nodes[0].type === 'string';
url = isStringValue ? nodes[0].nodes[0].value : _postcssValueParser.default.stringify(nodes[0].nodes);
} // Empty url - `@import "";` or `@import url();`
if (url.trim().length === 0) {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule
});
return;
}
isStringValue = paramsNodes[0].nodes.length !== 0 && paramsNodes[0].nodes[0].type === "string";
url = isStringValue ? paramsNodes[0].nodes[0].value : _postcssValueParser.default.stringify(paramsNodes[0].nodes);
}
url = (0, _utils.normalizeUrl)(url, isStringValue);
const {
requestable,
needResolve
} = (0, _utils.isURLRequestable)(url, options);
let prefix;
if (requestable && needResolve) {
const queryParts = url.split("!");
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
}
// Empty url - `@import "";` or `@import url();`
if (url.trim().length === 0) {
const error = new Error(`Unable to find uri in "${atRule.toString()}"`);
error.node = atRule;
throw error;
}
const additionalNodes = paramsNodes.slice(1);
let supports;
let layer;
let media;
if (additionalNodes.length > 0) {
let nodes = [];
for (const node of additionalNodes) {
nodes.push(node);
const isLayerFunction = node.type === "function" && node.value.toLowerCase() === "layer";
const isLayerWord = node.type === "word" && node.value.toLowerCase() === "layer";
if (isLayerFunction || isLayerWord) {
if (isLayerFunction) {
nodes.splice(nodes.length - 1, 1, ...node.nodes);
} else {
nodes.splice(nodes.length - 1, 1, {
type: "string",
value: "",
unclosed: false
});
}
layer = _postcssValueParser.default.stringify(nodes).trim().toLowerCase();
nodes = [];
} else if (node.type === "function" && node.value.toLowerCase() === "supports") {
nodes.splice(nodes.length - 1, 1, ...node.nodes);
supports = _postcssValueParser.default.stringify(nodes).trim().toLowerCase();
nodes = [];
const isRequestable = (0, _loaderUtils.isUrlRequest)(url);
if (isRequestable) {
url = (0, _utils.normalizeUrl)(url, isStringValue); // Empty url after normalize - `@import '\
// \
// \
// ';
if (url.trim().length === 0) {
result.warn(`Unable to find uri in "${atRule.toString()}"`, {
node: atRule
});
return;
}
}
if (nodes.length > 0) {
media = _postcssValueParser.default.stringify(nodes).trim().toLowerCase();
const media = _postcssValueParser.default.stringify(nodes.slice(1)).trim().toLowerCase();
if (options.filter && !options.filter({
url,
media
})) {
return;
}
}
// eslint-disable-next-line consistent-return
return {
atRule,
prefix,
url,
layer,
supports,
media,
requestable,
needResolve
};
}
const plugin = (options = {}) => {
return {
postcssPlugin: "postcss-import-parser",
prepare(result) {
const parsedAtRules = [];
return {
AtRule: {
import(atRule) {
if (options.isCSSStyleSheet) {
options.loaderContext.emitError(new Error(atRule.error("'@import' rules are not allowed here and will not be processed").message));
return;
}
const {
isSupportDataURL,
isSupportAbsoluteURL
} = options;
let parsedAtRule;
try {
parsedAtRule = parseNode(atRule, "params", {
isSupportAbsoluteURL,
isSupportDataURL
});
} catch (error) {
result.warn(error.message, {
node: error.node
});
}
if (!parsedAtRule) {
return;
}
parsedAtRules.push(parsedAtRule);
atRule.remove();
if (isRequestable) {
const importKey = url;
let importName = importsMap.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_AT_RULE_IMPORT_${importsMap.size}___`;
importsMap.set(importKey, importName);
result.messages.push({
type: 'import',
value: {
importName,
url: options.urlHandler ? options.urlHandler(url) : url
}
},
async OnceExit() {
if (parsedAtRules.length === 0) {
return;
}
const {
loaderContext
} = options;
const resolver = loaderContext.getResolve({
dependencyType: "css",
conditionNames: ["style"],
mainFields: ["css", "style", "main", "..."],
mainFiles: ["index", "..."],
extensions: [".css", "..."],
preferRelative: true
});
const resolvedAtRules = await Promise.all(parsedAtRules.map(async parsedAtRule => {
const {
atRule,
requestable,
needResolve,
prefix,
url,
layer,
supports,
media
} = parsedAtRule;
if (options.filter) {
const needKeep = await options.filter(url, media, loaderContext.resourcePath, supports, layer);
if (!needKeep) {
return;
}
}
if (needResolve) {
const request = (0, _utils.requestify)(url, loaderContext.rootContext);
const resolvedUrl = await (0, _utils.resolveRequests)(resolver, loaderContext.context, [...new Set([request, url])]);
if (!resolvedUrl) {
return;
}
if (resolvedUrl === loaderContext.resourcePath) {
atRule.remove();
return;
}
atRule.remove();
});
}
// eslint-disable-next-line consistent-return
return {
url: resolvedUrl,
layer,
supports,
media,
prefix,
requestable
};
}
atRule.remove();
// eslint-disable-next-line consistent-return
return {
url,
layer,
supports,
media,
prefix,
requestable
};
}));
const urlToNameMap = new Map();
for (let index = 0; index <= resolvedAtRules.length - 1; index++) {
const resolvedAtRule = resolvedAtRules[index];
if (!resolvedAtRule) {
// eslint-disable-next-line no-continue
continue;
}
const {
url,
requestable,
layer,
supports,
media
} = resolvedAtRule;
if (!requestable) {
options.api.push({
url,
layer,
supports,
media,
index
});
// eslint-disable-next-line no-continue
continue;
}
const {
prefix
} = resolvedAtRule;
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = urlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_AT_RULE_IMPORT_${urlToNameMap.size}___`;
urlToNameMap.set(newUrl, importName);
options.imports.push({
type: "rule_import",
importName,
url: options.urlHandler(newUrl),
index
});
}
options.api.push({
importName,
layer,
supports,
media,
index
});
}
result.messages.push({
type: 'api-import',
value: {
type: 'internal',
importName,
media
}
};
});
return;
}
};
};
plugin.postcss = true;
var _default = plugin;
result.messages.push({
pluginName,
type: 'api-import',
value: {
type: 'external',
url,
media
}
});
});
});
exports.default = _default;

View File

@ -4,354 +4,158 @@ Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
var _postcssValueParser = _interopRequireDefault(require("postcss-value-parser"));
var _utils = require("../utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const pluginName = 'postcss-url-parser';
const isUrlFunc = /url/i;
const isImageSetFunc = /^(?:-webkit-)?image-set$/i;
const needParseDeclaration = /(?:url|(?:-webkit-)?image-set)\(/i;
const needParseDecl = /(?:url|(?:-webkit-)?image-set)\(/i;
function getNodeFromUrlFunc(node) {
return node.nodes && node.nodes[0];
}
function getWebpackIgnoreCommentValue(index, nodes, inBetween) {
if (index === 0 && typeof inBetween !== "undefined") {
return inBetween;
}
let prevValueNode = nodes[index - 1];
if (!prevValueNode) {
// eslint-disable-next-line consistent-return
return;
}
if (prevValueNode.type === "space") {
if (!nodes[index - 2]) {
// eslint-disable-next-line consistent-return
function walkUrls(parsed, callback) {
parsed.walk(node => {
if (node.type !== 'function') {
return;
}
prevValueNode = nodes[index - 2];
}
if (prevValueNode.type !== "comment") {
// eslint-disable-next-line consistent-return
return;
}
const matched = prevValueNode.value.match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);
return matched && matched[2] === "true";
}
function shouldHandleURL(url, declaration, result, options) {
if (url.length === 0) {
result.warn(`Unable to find uri in '${declaration.toString()}'`, {
node: declaration
});
return {
requestable: false,
needResolve: false
};
}
return (0, _utils.isURLRequestable)(url, options);
}
function parseDeclaration(declaration, key, result, options) {
if (!needParseDeclaration.test(declaration[key])) {
return;
}
const parsed = (0, _postcssValueParser.default)(declaration.raws && declaration.raws.value && declaration.raws.value.raw ? declaration.raws.value.raw : declaration[key]);
let inBetween;
if (declaration.raws && declaration.raws.between) {
const lastCommentIndex = declaration.raws.between.lastIndexOf("/*");
const matched = declaration.raws.between.slice(lastCommentIndex).match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched) {
inBetween = matched[2] === "true";
}
}
let isIgnoreOnDeclaration = false;
const prevNode = declaration.prev();
if (prevNode && prevNode.type === "comment") {
const matched = prevNode.text.match(_utils.WEBPACK_IGNORE_COMMENT_REGEXP);
if (matched) {
isIgnoreOnDeclaration = matched[2] === "true";
}
}
let needIgnore;
const parsedURLs = [];
parsed.walk((valueNode, index, valueNodes) => {
if (valueNode.type !== "function") {
return;
}
if (isUrlFunc.test(valueNode.value)) {
needIgnore = getWebpackIgnoreCommentValue(index, valueNodes, inBetween);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
return;
}
if (isUrlFunc.test(node.value)) {
const {
nodes
} = valueNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
let url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
url = (0, _utils.normalizeUrl)(url, isStringValue);
const {
requestable,
needResolve
} = shouldHandleURL(url, declaration, result, options);
// Do not traverse inside `url`
if (!requestable) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: getNodeFromUrlFunc(valueNode),
prefix,
url,
needQuotes: false,
needResolve
});
} = node;
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
callback(getNodeFromUrlFunc(node), url, false, isStringValue); // Do not traverse inside `url`
// eslint-disable-next-line consistent-return
return false;
} else if (isImageSetFunc.test(valueNode.value)) {
for (const [innerIndex, nNode] of valueNode.nodes.entries()) {
}
if (isImageSetFunc.test(node.value)) {
for (const nNode of node.nodes) {
const {
type,
value
} = nNode;
if (type === "function" && isUrlFunc.test(value)) {
needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
// eslint-disable-next-line no-continue
continue;
}
if (type === 'function' && isUrlFunc.test(value)) {
const {
nodes
} = nNode;
const isStringValue = nodes.length !== 0 && nodes[0].type === "string";
let url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
url = (0, _utils.normalizeUrl)(url, isStringValue);
const {
requestable,
needResolve
} = shouldHandleURL(url, declaration, result, options);
// Do not traverse inside `url`
if (!requestable) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: getNodeFromUrlFunc(nNode),
prefix,
url,
needQuotes: false,
needResolve
});
} else if (type === "string") {
needIgnore = getWebpackIgnoreCommentValue(innerIndex, valueNode.nodes);
if (isIgnoreOnDeclaration && typeof needIgnore === "undefined" || needIgnore) {
if (needIgnore) {
// eslint-disable-next-line no-undefined
needIgnore = undefined;
}
// eslint-disable-next-line no-continue
continue;
}
let url = (0, _utils.normalizeUrl)(value, true);
const {
requestable,
needResolve
} = shouldHandleURL(url, declaration, result, options);
// Do not traverse inside `url`
if (!requestable) {
// eslint-disable-next-line consistent-return
return false;
}
const queryParts = url.split("!");
let prefix;
if (queryParts.length > 1) {
url = queryParts.pop();
prefix = queryParts.join("!");
}
parsedURLs.push({
declaration,
parsed,
node: nNode,
prefix,
url,
needQuotes: true,
needResolve
});
const isStringValue = nodes.length !== 0 && nodes[0].type === 'string';
const url = isStringValue ? nodes[0].value : _postcssValueParser.default.stringify(nodes);
callback(getNodeFromUrlFunc(nNode), url, false, isStringValue);
}
}
// Do not traverse inside `image-set`
if (type === 'string') {
callback(nNode, value, true, true);
}
} // Do not traverse inside `image-set`
// eslint-disable-next-line consistent-return
return false;
}
});
// eslint-disable-next-line consistent-return
return parsedURLs;
}
const plugin = (options = {}) => {
return {
postcssPlugin: "postcss-url-parser",
prepare(result) {
const parsedDeclarations = [];
return {
Declaration(declaration) {
const {
isSupportDataURL,
isSupportAbsoluteURL
} = options;
const parsedURL = parseDeclaration(declaration, "value", result, {
isSupportDataURL,
isSupportAbsoluteURL
});
if (!parsedURL) {
return;
}
parsedDeclarations.push(...parsedURL);
},
async OnceExit() {
if (parsedDeclarations.length === 0) {
return;
}
const resolvedDeclarations = await Promise.all(parsedDeclarations.map(async parsedDeclaration => {
const {
url,
needResolve
} = parsedDeclaration;
if (options.filter) {
const needKeep = await options.filter(url);
if (!needKeep) {
// eslint-disable-next-line consistent-return
return;
}
}
if (!needResolve) {
// eslint-disable-next-line consistent-return
return parsedDeclaration;
}
const splittedUrl = url.split(/(\?)?#/);
const [pathname, query, hashOrQuery] = splittedUrl;
let hash = query ? "?" : "";
hash += hashOrQuery ? `#${hashOrQuery}` : "";
const {
resolver,
rootContext
} = options;
const request = (0, _utils.requestify)(pathname, rootContext, Boolean(resolver));
if (!resolver) {
// eslint-disable-next-line consistent-return
return {
...parsedDeclaration,
url: request,
hash
};
}
const resolvedURL = await (0, _utils.resolveRequests)(resolver, options.context, [...new Set([request, url])]);
if (!resolvedURL) {
// eslint-disable-next-line consistent-return
return;
}
// eslint-disable-next-line consistent-return
return {
...parsedDeclaration,
url: resolvedURL,
hash
};
}));
const urlToNameMap = new Map();
const urlToReplacementMap = new Map();
let hasUrlImportHelper = false;
for (let index = 0; index <= resolvedDeclarations.length - 1; index++) {
const item = resolvedDeclarations[index];
if (!item) {
// eslint-disable-next-line no-continue
continue;
}
if (!hasUrlImportHelper) {
options.imports.push({
type: "get_url_import",
importName: "___CSS_LOADER_GET_URL_IMPORT___",
url: options.urlHandler(require.resolve("../runtime/getUrl.js")),
index: -1
});
hasUrlImportHelper = true;
}
const {
url,
prefix
} = item;
const newUrl = prefix ? `${prefix}!${url}` : url;
let importName = urlToNameMap.get(newUrl);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${urlToNameMap.size}___`;
urlToNameMap.set(newUrl, importName);
options.imports.push({
type: "url",
importName,
url: options.resolver ? options.urlHandler(newUrl) : JSON.stringify(newUrl),
index
});
}
const {
hash,
needQuotes
} = item;
const replacementKey = JSON.stringify({
newUrl,
hash,
needQuotes
});
let replacementName = urlToReplacementMap.get(replacementKey);
if (!replacementName) {
replacementName = `___CSS_LOADER_URL_REPLACEMENT_${urlToReplacementMap.size}___`;
urlToReplacementMap.set(replacementKey, replacementName);
options.replacements.push({
replacementName,
importName,
hash,
needQuotes
});
}
// eslint-disable-next-line no-param-reassign
item.node.type = "word";
// eslint-disable-next-line no-param-reassign
item.node.value = replacementName;
// eslint-disable-next-line no-param-reassign
item.declaration.value = item.parsed.toString();
}
}
};
var _default = _postcss.default.plugin(pluginName, options => (css, result) => {
const importsMap = new Map();
const replacementsMap = new Map();
let hasHelper = false;
css.walkDecls(decl => {
if (!needParseDecl.test(decl.value)) {
return;
}
};
};
plugin.postcss = true;
var _default = plugin;
const parsed = (0, _postcssValueParser.default)(decl.value);
walkUrls(parsed, (node, url, needQuotes, isStringValue) => {
// https://www.w3.org/TR/css-syntax-3/#typedef-url-token
if (url.replace(/^[\s]+|[\s]+$/g, '').length === 0) {
result.warn(`Unable to find uri in '${decl ? decl.toString() : decl.value}'`, {
node: decl
});
return;
}
if (options.filter && !options.filter(url)) {
return;
}
const splittedUrl = url.split(/(\?)?#/);
const [urlWithoutHash, singleQuery, hashValue] = splittedUrl;
const hash = singleQuery || hashValue ? `${singleQuery ? '?' : ''}${hashValue ? `#${hashValue}` : ''}` : '';
const normalizedUrl = (0, _utils.normalizeUrl)(urlWithoutHash, isStringValue);
const importKey = normalizedUrl;
let importName = importsMap.get(importKey);
if (!importName) {
importName = `___CSS_LOADER_URL_IMPORT_${importsMap.size}___`;
importsMap.set(importKey, importName);
if (!hasHelper) {
const urlToHelper = require.resolve('../runtime/getUrl.js');
result.messages.push({
pluginName,
type: 'import',
value: {
importName: '___CSS_LOADER_GET_URL_IMPORT___',
url: options.urlHandler ? options.urlHandler(urlToHelper) : urlToHelper
}
});
hasHelper = true;
}
result.messages.push({
pluginName,
type: 'import',
value: {
importName,
url: options.urlHandler ? options.urlHandler(normalizedUrl) : normalizedUrl
}
});
}
const replacementKey = JSON.stringify({
importKey,
hash,
needQuotes
});
let replacementName = replacementsMap.get(replacementKey);
if (!replacementName) {
replacementName = `___CSS_LOADER_URL_REPLACEMENT_${replacementsMap.size}___`;
replacementsMap.set(replacementKey, replacementName);
result.messages.push({
pluginName,
type: 'url-replacement',
value: {
replacementName,
importName,
hash,
needQuotes
}
});
} // eslint-disable-next-line no-param-reassign
node.type = 'word'; // eslint-disable-next-line no-param-reassign
node.value = replacementName;
}); // eslint-disable-next-line no-param-reassign
decl.value = parsed.toString();
});
});
exports.default = _default;

View File

@ -4,82 +4,91 @@
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
module.exports = function (cssWithMappingToString) {
var list = [];
// css base code, injected by the css-loader
// eslint-disable-next-line func-names
module.exports = function (useSourceMap) {
var list = []; // return the list of modules as css string
// return the list of modules as css string
list.toString = function toString() {
return this.map(function (item) {
var content = "";
var needLayer = typeof item[5] !== "undefined";
if (item[4]) {
content += "@supports (".concat(item[4], ") {");
}
if (item[2]) {
content += "@media ".concat(item[2], " {");
}
if (needLayer) {
content += "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {");
}
content += cssWithMappingToString(item);
if (needLayer) {
content += "}";
}
if (item[2]) {
content += "}";
}
if (item[4]) {
content += "}";
}
return content;
}).join("");
};
var content = cssWithMappingToString(item, useSourceMap);
// import a list of modules into the list
list.i = function i(modules, media, dedupe, supports, layer) {
if (typeof modules === "string") {
modules = [[null, modules, undefined]];
if (item[2]) {
return "@media ".concat(item[2], " {").concat(content, "}");
}
return content;
}).join('');
}; // import a list of modules into the list
// eslint-disable-next-line func-names
list.i = function (modules, mediaQuery, dedupe) {
if (typeof modules === 'string') {
// eslint-disable-next-line no-param-reassign
modules = [[null, modules, '']];
}
var alreadyImportedModules = {};
if (dedupe) {
for (var k = 0; k < this.length; k++) {
var id = this[k][0];
for (var i = 0; i < this.length; i++) {
// eslint-disable-next-line prefer-destructuring
var id = this[i][0];
if (id != null) {
alreadyImportedModules[id] = true;
}
}
}
for (var _k = 0; _k < modules.length; _k++) {
var item = [].concat(modules[_k]);
for (var _i = 0; _i < modules.length; _i++) {
var item = [].concat(modules[_i]);
if (dedupe && alreadyImportedModules[item[0]]) {
// eslint-disable-next-line no-continue
continue;
}
if (typeof layer !== "undefined") {
if (typeof item[5] === "undefined") {
item[5] = layer;
} else {
item[1] = "@layer".concat(item[5].length > 0 ? " ".concat(item[5]) : "", " {").concat(item[1], "}");
item[5] = layer;
}
}
if (media) {
if (mediaQuery) {
if (!item[2]) {
item[2] = media;
item[2] = mediaQuery;
} else {
item[1] = "@media ".concat(item[2], " {").concat(item[1], "}");
item[2] = media;
}
}
if (supports) {
if (!item[4]) {
item[4] = "".concat(supports);
} else {
item[1] = "@supports (".concat(item[4], ") {").concat(item[1], "}");
item[4] = supports;
item[2] = "".concat(mediaQuery, " and ").concat(item[2]);
}
}
list.push(item);
}
};
return list;
};
function cssWithMappingToString(item, useSourceMap) {
var content = item[1] || ''; // eslint-disable-next-line prefer-destructuring
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (useSourceMap && typeof btoa === 'function') {
var sourceMapping = toComment(cssMapping);
var sourceURLs = cssMapping.sources.map(function (source) {
return "/*# sourceURL=".concat(cssMapping.sourceRoot || '').concat(source, " */");
});
return [content].concat(sourceURLs).concat([sourceMapping]).join('\n');
}
return [content].join('\n');
} // Adapted from convert-source-map (MIT)
function toComment(sourceMap) {
// eslint-disable-next-line no-undef
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap))));
var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
return "/*# ".concat(data, " */");
}

View File

@ -2,25 +2,33 @@
module.exports = function (url, options) {
if (!options) {
// eslint-disable-next-line no-param-reassign
options = {};
}
if (!url) {
return url;
}
url = String(url.__esModule ? url.default : url);
} // eslint-disable-next-line no-underscore-dangle, no-param-reassign
url = url && url.__esModule ? url.default : url;
if (typeof url !== 'string') {
return url;
} // If url is already wrapped in quotes, remove them
// If url is already wrapped in quotes, remove them
if (/^['"].*['"]$/.test(url)) {
// eslint-disable-next-line no-param-reassign
url = url.slice(1, -1);
}
if (options.hash) {
// eslint-disable-next-line no-param-reassign
url += options.hash;
} // Should url be wrapped?
// See https://drafts.csswg.org/css-values-3/#urls
if (/["'() \t\n]/.test(url) || options.needQuotes) {
return "\"".concat(url.replace(/"/g, '\\"').replace(/\n/g, '\\n'), "\"");
}
// Should url be wrapped?
// See https://drafts.csswg.org/css-values-3/#urls
if (/["'() \t\n]|(%20)/.test(url) || options.needQuotes) {
return "\"".concat(url.replace(/"/g, '\\"').replace(/\n/g, "\\n"), "\"");
}
return url;
};

View File

@ -1,5 +0,0 @@
"use strict";
module.exports = function (i) {
return i[1];
};

View File

@ -1,19 +0,0 @@
"use strict";
module.exports = function (item) {
var content = item[1];
var cssMapping = item[3];
if (!cssMapping) {
return content;
}
if (typeof btoa === "function") {
var base64 = btoa(unescape(encodeURIComponent(JSON.stringify(cssMapping))));
var data = "sourceMappingURL=data:application/json;charset=utf-8;base64,".concat(base64);
var sourceMapping = "/*# ".concat(data, " */");
var sourceURLs = cssMapping.sources.map(function (source) {
return "/*# sourceURL=".concat(cssMapping.sourceRoot || "").concat(source, " */");
});
return [content].concat(sourceURLs).concat([sourceMapping]).join("\n");
}
return [content].join("\n");
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,63 @@
declare namespace camelcase {
interface Options {
/**
Uppercase the first character: `foo-bar` `FooBar`.
@default false
*/
readonly pascalCase?: boolean;
}
}
declare const camelcase: {
/**
Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` `fooBar`.
@param input - String to convert to camel case.
@example
```
import camelCase = require('camelcase');
camelCase('foo-bar');
//=> 'fooBar'
camelCase('foo_bar');
//=> 'fooBar'
camelCase('Foo-Bar');
//=> 'fooBar'
camelCase('Foo-Bar', {pascalCase: true});
//=> 'FooBar'
camelCase('--foo.bar', {pascalCase: false});
//=> 'fooBar'
camelCase('foo bar');
//=> 'fooBar'
console.log(process.argv[3]);
//=> '--foo-bar'
camelCase(process.argv[3]);
//=> 'fooBar'
camelCase(['foo', 'bar']);
//=> 'fooBar'
camelCase(['__foo__', '--bar'], {pascalCase: true});
//=> 'FooBar'
```
*/
(input: string | ReadonlyArray<string>, options?: camelcase.Options): string;
// TODO: Remove this for the next major release, refactor the whole definition to:
// declare function camelcase(
// input: string | ReadonlyArray<string>,
// options?: camelcase.Options
// ): string;
// export = camelcase;
default: typeof camelcase;
};
export = camelcase;

View File

@ -0,0 +1,76 @@
'use strict';
const preserveCamelCase = string => {
let isLastCharLower = false;
let isLastCharUpper = false;
let isLastLastCharUpper = false;
for (let i = 0; i < string.length; i++) {
const character = string[i];
if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) {
string = string.slice(0, i) + '-' + string.slice(i);
isLastCharLower = false;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = true;
i++;
} else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) {
string = string.slice(0, i - 1) + '-' + string.slice(i - 1);
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = false;
isLastCharLower = true;
} else {
isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character;
}
}
return string;
};
const camelCase = (input, options) => {
if (!(typeof input === 'string' || Array.isArray(input))) {
throw new TypeError('Expected the input to be `string | string[]`');
}
options = Object.assign({
pascalCase: false
}, options);
const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x;
if (Array.isArray(input)) {
input = input.map(x => x.trim())
.filter(x => x.length)
.join('-');
} else {
input = input.trim();
}
if (input.length === 0) {
return '';
}
if (input.length === 1) {
return options.pascalCase ? input.toUpperCase() : input.toLowerCase();
}
const hasUpperCase = input !== input.toLowerCase();
if (hasUpperCase) {
input = preserveCamelCase(input);
}
input = input
.replace(/^[_.\- ]+/, '')
.toLowerCase()
.replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase())
.replace(/\d+(\w|$)/g, m => m.toUpperCase());
return postProcess(input);
};
module.exports = camelCase;
// TODO: Remove this for the next major release
module.exports.default = camelCase;

View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (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.

View File

@ -0,0 +1,43 @@
{
"name": "camelcase",
"version": "5.3.1",
"description": "Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`",
"license": "MIT",
"repository": "sindresorhus/camelcase",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=6"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"camelcase",
"camel-case",
"camel",
"case",
"dash",
"hyphen",
"dot",
"underscore",
"separator",
"string",
"text",
"convert",
"pascalcase",
"pascal-case"
],
"devDependencies": {
"ava": "^1.4.1",
"tsd": "^0.7.1",
"xo": "^0.24.0"
}
}

View File

@ -0,0 +1,99 @@
# camelcase [![Build Status](https://travis-ci.org/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase)
> Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar``fooBar`
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-camelcase?utm_source=npm-camelcase&utm_medium=referral&utm_campaign=readme">Get professional support for 'camelcase' with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
---
## Install
```
$ npm install camelcase
```
## Usage
```js
const camelCase = require('camelcase');
camelCase('foo-bar');
//=> 'fooBar'
camelCase('foo_bar');
//=> 'fooBar'
camelCase('Foo-Bar');
//=> 'fooBar'
camelCase('Foo-Bar', {pascalCase: true});
//=> 'FooBar'
camelCase('--foo.bar', {pascalCase: false});
//=> 'fooBar'
camelCase('foo bar');
//=> 'fooBar'
console.log(process.argv[3]);
//=> '--foo-bar'
camelCase(process.argv[3]);
//=> 'fooBar'
camelCase(['foo', 'bar']);
//=> 'fooBar'
camelCase(['__foo__', '--bar'], {pascalCase: true});
//=> 'FooBar'
```
## API
### camelCase(input, [options])
#### input
Type: `string` `string[]`
String to convert to camel case.
#### options
Type: `Object`
##### pascalCase
Type: `boolean`<br>
Default: `false`
Uppercase the first character: `foo-bar``FooBar`
## Security
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.
## Related
- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module
- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase
- [titleize](https://github.com/sindresorhus/titleize) - Capitalize every word in string
- [humanize-string](https://github.com/sindresorhus/humanize-string) - Convert a camelized/dasherized/underscored string into a humanized one
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View File

@ -1,15 +0,0 @@
The ISC License
Copyright (c) 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.

View File

@ -1,166 +0,0 @@
# lru cache
A cache object that deletes the least-recently-used items.
[![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache)
## Installation:
```javascript
npm install lru-cache --save
```
## Usage:
```javascript
var LRU = require("lru-cache")
, options = { max: 500
, length: function (n, key) { return n * 2 + key.length }
, dispose: function (key, n) { n.close() }
, maxAge: 1000 * 60 * 60 }
, cache = new LRU(options)
, otherCache = new LRU(50) // sets just the max size
cache.set("key", "value")
cache.get("key") // "value"
// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)
cache.reset() // empty the cache
```
If you put more stuff in it, then items will fall out.
If you try to put an oversized thing in it, then it'll fall out right
away.
## Options
* `max` The maximum size of the cache, checked by applying the length
function to all values in the cache. Not setting this is kind of
silly, since that's the whole purpose of this lib, but it defaults
to `Infinity`. Setting it to a non-number or negative number will
throw a `TypeError`. Setting it to 0 makes it be `Infinity`.
* `maxAge` Maximum age in ms. Items are not pro-actively pruned out
as they age, but if you try to get an item that is too old, it'll
drop it and return undefined instead of giving it to you.
Setting this to a negative value will make everything seem old!
Setting it to a non-number will throw a `TypeError`.
* `length` Function that is used to calculate the length of stored
items. If you're storing strings or buffers, then you probably want
to do something like `function(n, key){return n.length}`. The default is
`function(){return 1}`, which is fine if you want to store `max`
like-sized things. The item is passed as the first argument, and
the key is passed as the second argumnet.
* `dispose` Function that is called on items when they are dropped
from the cache. This can be handy if you want to close file
descriptors or do other cleanup tasks when items are no longer
accessible. Called with `key, value`. It's called *before*
actually removing the item from the internal cache, so if you want
to immediately put it back in, you'll have to do that in a
`nextTick` or `setTimeout` callback or it won't do anything.
* `stale` By default, if you set a `maxAge`, it'll only actually pull
stale items out of the cache when you `get(key)`. (That is, it's
not pre-emptively doing a `setTimeout` or anything.) If you set
`stale:true`, it'll return the stale value before deleting it. If
you don't set this, then it'll return `undefined` when you try to
get a stale entry, as if it had already been deleted.
* `noDisposeOnSet` By default, if you set a `dispose()` method, then
it'll be called whenever a `set()` operation overwrites an existing
key. If you set this option, `dispose()` will only be called when a
key falls out of the cache, not when it is overwritten.
* `updateAgeOnGet` When using time-expiring entries with `maxAge`,
setting this to `true` will make each item's effective time update
to the current time whenever it is retrieved from cache, causing it
to not expire. (It can still fall out of cache based on recency of
use, of course.)
## API
* `set(key, value, maxAge)`
* `get(key) => value`
Both of these will update the "recently used"-ness of the key.
They do what you think. `maxAge` is optional and overrides the
cache `maxAge` option if provided.
If the key is not found, `get()` will return `undefined`.
The key and val can be any value.
* `peek(key)`
Returns the key value (or `undefined` if not found) without
updating the "recently used"-ness of the key.
(If you find yourself using this a lot, you *might* be using the
wrong sort of data structure, but there are some use cases where
it's handy.)
* `del(key)`
Deletes a key out of the cache.
* `reset()`
Clear the cache entirely, throwing away all values.
* `has(key)`
Check if a key is in the cache, without updating the recent-ness
or deleting it for being stale.
* `forEach(function(value,key,cache), [thisp])`
Just like `Array.prototype.forEach`. Iterates over all the keys
in the cache, in order of recent-ness. (Ie, more recently used
items are iterated over first.)
* `rforEach(function(value,key,cache), [thisp])`
The same as `cache.forEach(...)` but items are iterated over in
reverse order. (ie, less recently used items are iterated over
first.)
* `keys()`
Return an array of the keys in the cache.
* `values()`
Return an array of the values in the cache.
* `length`
Return total length of objects in cache taking into account
`length` options function.
* `itemCount`
Return total quantity of objects currently in cache. Note, that
`stale` (see options) items are returned as part of this item
count.
* `dump()`
Return an array of the cache entries ready for serialization and usage
with 'destinationCache.load(arr)`.
* `load(cacheEntriesArray)`
Loads another cache entries array, obtained with `sourceCache.dump()`,
into the cache. The destination cache is reset before loading new entries
* `prune()`
Manually iterates over the entire cache proactively pruning old entries

View File

@ -1,334 +0,0 @@
'use strict'
// A linked list to keep track of recently-used-ness
const Yallist = require('yallist')
const MAX = Symbol('max')
const LENGTH = Symbol('length')
const LENGTH_CALCULATOR = Symbol('lengthCalculator')
const ALLOW_STALE = Symbol('allowStale')
const MAX_AGE = Symbol('maxAge')
const DISPOSE = Symbol('dispose')
const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')
const LRU_LIST = Symbol('lruList')
const CACHE = Symbol('cache')
const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')
const naiveLength = () => 1
// lruList is a yallist where the head is the youngest
// item, and the tail is the oldest. the list contains the Hit
// objects as the entries.
// Each Hit object has a reference to its Yallist.Node. This
// never changes.
//
// cache is a Map (or PseudoMap) that matches the keys to
// the Yallist.Node object.
class LRUCache {
constructor (options) {
if (typeof options === 'number')
options = { max: options }
if (!options)
options = {}
if (options.max && (typeof options.max !== 'number' || options.max < 0))
throw new TypeError('max must be a non-negative number')
// Kind of weird to have a default max of Infinity, but oh well.
const max = this[MAX] = options.max || Infinity
const lc = options.length || naiveLength
this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc
this[ALLOW_STALE] = options.stale || false
if (options.maxAge && typeof options.maxAge !== 'number')
throw new TypeError('maxAge must be a number')
this[MAX_AGE] = options.maxAge || 0
this[DISPOSE] = options.dispose
this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false
this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false
this.reset()
}
// resize the cache when the max changes.
set max (mL) {
if (typeof mL !== 'number' || mL < 0)
throw new TypeError('max must be a non-negative number')
this[MAX] = mL || Infinity
trim(this)
}
get max () {
return this[MAX]
}
set allowStale (allowStale) {
this[ALLOW_STALE] = !!allowStale
}
get allowStale () {
return this[ALLOW_STALE]
}
set maxAge (mA) {
if (typeof mA !== 'number')
throw new TypeError('maxAge must be a non-negative number')
this[MAX_AGE] = mA
trim(this)
}
get maxAge () {
return this[MAX_AGE]
}
// resize the cache when the lengthCalculator changes.
set lengthCalculator (lC) {
if (typeof lC !== 'function')
lC = naiveLength
if (lC !== this[LENGTH_CALCULATOR]) {
this[LENGTH_CALCULATOR] = lC
this[LENGTH] = 0
this[LRU_LIST].forEach(hit => {
hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)
this[LENGTH] += hit.length
})
}
trim(this)
}
get lengthCalculator () { return this[LENGTH_CALCULATOR] }
get length () { return this[LENGTH] }
get itemCount () { return this[LRU_LIST].length }
rforEach (fn, thisp) {
thisp = thisp || this
for (let walker = this[LRU_LIST].tail; walker !== null;) {
const prev = walker.prev
forEachStep(this, fn, walker, thisp)
walker = prev
}
}
forEach (fn, thisp) {
thisp = thisp || this
for (let walker = this[LRU_LIST].head; walker !== null;) {
const next = walker.next
forEachStep(this, fn, walker, thisp)
walker = next
}
}
keys () {
return this[LRU_LIST].toArray().map(k => k.key)
}
values () {
return this[LRU_LIST].toArray().map(k => k.value)
}
reset () {
if (this[DISPOSE] &&
this[LRU_LIST] &&
this[LRU_LIST].length) {
this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))
}
this[CACHE] = new Map() // hash of items by key
this[LRU_LIST] = new Yallist() // list of items in order of use recency
this[LENGTH] = 0 // length of items in the list
}
dump () {
return this[LRU_LIST].map(hit =>
isStale(this, hit) ? false : {
k: hit.key,
v: hit.value,
e: hit.now + (hit.maxAge || 0)
}).toArray().filter(h => h)
}
dumpLru () {
return this[LRU_LIST]
}
set (key, value, maxAge) {
maxAge = maxAge || this[MAX_AGE]
if (maxAge && typeof maxAge !== 'number')
throw new TypeError('maxAge must be a number')
const now = maxAge ? Date.now() : 0
const len = this[LENGTH_CALCULATOR](value, key)
if (this[CACHE].has(key)) {
if (len > this[MAX]) {
del(this, this[CACHE].get(key))
return false
}
const node = this[CACHE].get(key)
const item = node.value
// dispose of the old one before overwriting
// split out into 2 ifs for better coverage tracking
if (this[DISPOSE]) {
if (!this[NO_DISPOSE_ON_SET])
this[DISPOSE](key, item.value)
}
item.now = now
item.maxAge = maxAge
item.value = value
this[LENGTH] += len - item.length
item.length = len
this.get(key)
trim(this)
return true
}
const hit = new Entry(key, value, len, now, maxAge)
// oversized objects fall out of cache automatically.
if (hit.length > this[MAX]) {
if (this[DISPOSE])
this[DISPOSE](key, value)
return false
}
this[LENGTH] += hit.length
this[LRU_LIST].unshift(hit)
this[CACHE].set(key, this[LRU_LIST].head)
trim(this)
return true
}
has (key) {
if (!this[CACHE].has(key)) return false
const hit = this[CACHE].get(key).value
return !isStale(this, hit)
}
get (key) {
return get(this, key, true)
}
peek (key) {
return get(this, key, false)
}
pop () {
const node = this[LRU_LIST].tail
if (!node)
return null
del(this, node)
return node.value
}
del (key) {
del(this, this[CACHE].get(key))
}
load (arr) {
// reset the cache
this.reset()
const now = Date.now()
// A previous serialized cache has the most recent items first
for (let l = arr.length - 1; l >= 0; l--) {
const hit = arr[l]
const expiresAt = hit.e || 0
if (expiresAt === 0)
// the item was created without expiration in a non aged cache
this.set(hit.k, hit.v)
else {
const maxAge = expiresAt - now
// dont add already expired items
if (maxAge > 0) {
this.set(hit.k, hit.v, maxAge)
}
}
}
}
prune () {
this[CACHE].forEach((value, key) => get(this, key, false))
}
}
const get = (self, key, doUse) => {
const node = self[CACHE].get(key)
if (node) {
const hit = node.value
if (isStale(self, hit)) {
del(self, node)
if (!self[ALLOW_STALE])
return undefined
} else {
if (doUse) {
if (self[UPDATE_AGE_ON_GET])
node.value.now = Date.now()
self[LRU_LIST].unshiftNode(node)
}
}
return hit.value
}
}
const isStale = (self, hit) => {
if (!hit || (!hit.maxAge && !self[MAX_AGE]))
return false
const diff = Date.now() - hit.now
return hit.maxAge ? diff > hit.maxAge
: self[MAX_AGE] && (diff > self[MAX_AGE])
}
const trim = self => {
if (self[LENGTH] > self[MAX]) {
for (let walker = self[LRU_LIST].tail;
self[LENGTH] > self[MAX] && walker !== null;) {
// We know that we're about to delete this one, and also
// what the next least recently used key will be, so just
// go ahead and set it now.
const prev = walker.prev
del(self, walker)
walker = prev
}
}
}
const del = (self, node) => {
if (node) {
const hit = node.value
if (self[DISPOSE])
self[DISPOSE](hit.key, hit.value)
self[LENGTH] -= hit.length
self[CACHE].delete(hit.key)
self[LRU_LIST].removeNode(node)
}
}
class Entry {
constructor (key, value, length, now, maxAge) {
this.key = key
this.value = value
this.length = length
this.now = now
this.maxAge = maxAge || 0
}
}
const forEachStep = (self, fn, node, thisp) => {
let hit = node.value
if (isStale(self, hit)) {
del(self, node)
if (!self[ALLOW_STALE])
hit = undefined
}
if (hit)
fn.call(thisp, hit.value, hit.key, self)
}
module.exports = LRUCache

View File

@ -1,34 +0,0 @@
{
"name": "lru-cache",
"description": "A cache object that deletes the least-recently-used items.",
"version": "6.0.0",
"author": "Isaac Z. Schlueter <i@izs.me>",
"keywords": [
"mru",
"lru",
"cache"
],
"scripts": {
"test": "tap",
"snap": "tap",
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags"
},
"main": "index.js",
"repository": "git://github.com/isaacs/node-lru-cache.git",
"devDependencies": {
"benchmark": "^2.1.4",
"tap": "^14.10.7"
},
"license": "ISC",
"dependencies": {
"yallist": "^4.0.0"
},
"files": [
"index.js"
],
"engines": {
"node": ">=10"
}
}

View File

@ -0,0 +1,70 @@
# changes log
## 6.2.0
* Coerce numbers to strings when passed to semver.coerce()
* Add `rtl` option to coerce from right to left
## 6.1.3
* Handle X-ranges properly in includePrerelease mode
## 6.1.2
* Do not throw when testing invalid version strings
## 6.1.1
* Add options support for semver.coerce()
* Handle undefined version passed to Range.test
## 6.1.0
* Add semver.compareBuild function
* Support `*` in semver.intersects
## 6.0
* Fix `intersects` logic.
This is technically a bug fix, but since it is also a change to behavior
that may require users updating their code, it is marked as a major
version increment.
## 5.7
* Add `minVersion` method
## 5.6
* Move boolean `loose` param to an options object, with
backwards-compatibility protection.
* Add ability to opt out of special prerelease version handling with
the `includePrerelease` option flag.
## 5.5
* Add version coercion capabilities
## 5.4
* Add intersection checking
## 5.3
* Add `minSatisfying` method
## 5.2
* Add `prerelease(v)` that returns prerelease components
## 5.1
* Add Backus-Naur for ranges
* Remove excessively cute inspection methods
## 5.0
* Remove AMD/Browserified build artifacts
* Fix ltr and gtr when using the `*` range
* Fix for range `*` with a prerelease identifier

View File

@ -25,63 +25,6 @@ semver.valid(semver.coerce('v2')) // '2.0.0'
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
```
You can also just load the module for the function that you care about, if
you'd like to minimize your footprint.
```js
// load the whole API at once in a single object
const semver = require('semver')
// or just load the bits you need
// all of them listed here, just pick and choose what you want
// classes
const SemVer = require('semver/classes/semver')
const Comparator = require('semver/classes/comparator')
const Range = require('semver/classes/range')
// functions for working with versions
const semverParse = require('semver/functions/parse')
const semverValid = require('semver/functions/valid')
const semverClean = require('semver/functions/clean')
const semverInc = require('semver/functions/inc')
const semverDiff = require('semver/functions/diff')
const semverMajor = require('semver/functions/major')
const semverMinor = require('semver/functions/minor')
const semverPatch = require('semver/functions/patch')
const semverPrerelease = require('semver/functions/prerelease')
const semverCompare = require('semver/functions/compare')
const semverRcompare = require('semver/functions/rcompare')
const semverCompareLoose = require('semver/functions/compare-loose')
const semverCompareBuild = require('semver/functions/compare-build')
const semverSort = require('semver/functions/sort')
const semverRsort = require('semver/functions/rsort')
// low-level comparators between versions
const semverGt = require('semver/functions/gt')
const semverLt = require('semver/functions/lt')
const semverEq = require('semver/functions/eq')
const semverNeq = require('semver/functions/neq')
const semverGte = require('semver/functions/gte')
const semverLte = require('semver/functions/lte')
const semverCmp = require('semver/functions/cmp')
const semverCoerce = require('semver/functions/coerce')
// working with ranges
const semverSatisfies = require('semver/functions/satisfies')
const semverMaxSatisfying = require('semver/ranges/max-satisfying')
const semverMinSatisfying = require('semver/ranges/min-satisfying')
const semverToComparators = require('semver/ranges/to-comparators')
const semverMinVersion = require('semver/ranges/min-version')
const semverValidRange = require('semver/ranges/valid')
const semverOutside = require('semver/ranges/outside')
const semverGtr = require('semver/ranges/gtr')
const semverLtr = require('semver/ranges/ltr')
const semverIntersects = require('semver/ranges/intersects')
const simplifyRange = require('semver/ranges/simplify')
const rangeSubset = require('semver/ranges/subset')
```
As a command-line utility:
```
@ -256,39 +199,37 @@ inclusive range, then all versions that start with the supplied parts
of the tuple are accepted, but nothing that would be greater than the
provided tuple parts.
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0`
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0`
#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`
Any of `X`, `x`, or `*` may be used to "stand in" for one of the
numeric values in the `[major, minor, patch]` tuple.
* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless
`includePrerelease` is specified, in which case any version at all
satisfies)
* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions)
* `*` := `>=0.0.0` (Any version satisfies)
* `1.x` := `>=1.0.0 <2.0.0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0` (Matching major and minor versions)
A partial version range is treated as an X-Range, so the special
character is in fact optional.
* `""` (empty string) := `*` := `>=0.0.0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0`
#### Tilde Ranges `~1.2.3` `~1.2` `~1`
Allows patch-level changes if a minor version is specified on the
comparator. Allows minor-level changes if not.
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
@ -310,15 +251,15 @@ However, it presumes that there will *not* be breaking changes between
`0.2.4` and `0.2.5`. It allows for changes that are presumed to be
additive (but non-breaking), according to commonly observed practices.
* `^1.2.3` := `>=1.2.3 <2.0.0-0`
* `^0.2.3` := `>=0.2.3 <0.3.0-0`
* `^0.0.3` := `>=0.0.3 <0.0.4-0`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in
* `^1.2.3` := `>=1.2.3 <2.0.0`
* `^0.2.3` := `>=0.2.3 <0.3.0`
* `^0.0.3` := `>=0.0.3 <0.0.4`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4` Note that prereleases in the
`0.0.3` version *only* will be allowed, if they are greater than or
equal to `beta`. So, `0.0.3-pr.2` would be allowed.
@ -326,16 +267,16 @@ When parsing caret ranges, a missing `patch` value desugars to the
number `0`, but will allow flexibility within that value, even if the
major and minor versions are both `0`.
* `^1.2.x` := `>=1.2.0 <2.0.0-0`
* `^0.0.x` := `>=0.0.0 <0.1.0-0`
* `^0.0` := `>=0.0.0 <0.1.0-0`
* `^1.2.x` := `>=1.2.0 <2.0.0`
* `^0.0.x` := `>=0.0.0 <0.1.0`
* `^0.0` := `>=0.0.0 <0.1.0`
A missing `minor` and `patch` values will desugar to zero, but also
allow flexibility within those values, even if the major version is
zero.
* `^1.x` := `>=1.0.0 <2.0.0-0`
* `^0.x` := `>=0.0.0 <1.0.0-0`
* `^1.x` := `>=1.0.0 <2.0.0`
* `^0.x` := `>=0.0.0 <1.0.0`
### Range Grammar
@ -450,16 +391,6 @@ strings that they parse.
`hilo` argument must be either the string `'>'` or `'<'`. (This is
the function called by `gtr` and `ltr`.)
* `intersects(range)`: Return true if any of the ranges comparators intersect
* `simplifyRange(versions, range)`: Return a "simplified" range that
matches the same items in `versions` list as the range specified. Note
that it does *not* guarantee that it would match the same versions in all
cases, only for the set of versions provided. This is useful when
generating ranges by joining together multiple versions with `||`
programmatically, to provide the user with something a bit more
ergonomic. If the provided range is shorter in string-length than the
generated range, then that is returned.
* `subset(subRange, superRange)`: Return `true` if the `subRange` range is
entirely contained by the `superRange` range.
Note that, since ranges may be non-contiguous, a version might not be
greater than a range, less than a range, *or* satisfy a range! For
@ -486,7 +417,7 @@ surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
is not valid). The maximum length for any semver component considered for
coercion is 16 characters; longer components will be ignored
(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any
semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
semver component is `Integer.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
components are invalid (`9999999999999999.4.7.4` is likely invalid).
If the `options.rtl` flag is set, then `coerce` will return the right-most
@ -499,9 +430,7 @@ any other overlapping SemVer tuple.
* `clean(version)`: Clean a string to be a valid semver if possible
This will return a cleaned and trimmed semver version. If the provided
version is not valid a null will be returned. This does not work for
ranges.
This will return a cleaned and trimmed semver version. If the provided version is not valid a null will be returned. This does not work for ranges.
ex.
* `s.clean(' = v 2.1.5foo')`: `null`
@ -512,57 +441,3 @@ ex.
* `s.clean(' =v2.1.5')`: `2.1.5`
* `s.clean(' 2.1.5 ')`: `'2.1.5'`
* `s.clean('~1.0.0')`: `null`
## Exported Modules
<!--
TODO: Make sure that all of these items are documented (classes aren't,
eg), and then pull the module name into the documentation for that specific
thing.
-->
You may pull in just the part of this semver utility that you need, if you
are sensitive to packing and tree-shaking concerns. The main
`require('semver')` export uses getter functions to lazily load the parts
of the API that are used.
The following modules are available:
* `require('semver')`
* `require('semver/classes')`
* `require('semver/classes/comparator')`
* `require('semver/classes/range')`
* `require('semver/classes/semver')`
* `require('semver/functions/clean')`
* `require('semver/functions/cmp')`
* `require('semver/functions/coerce')`
* `require('semver/functions/compare')`
* `require('semver/functions/compare-build')`
* `require('semver/functions/compare-loose')`
* `require('semver/functions/diff')`
* `require('semver/functions/eq')`
* `require('semver/functions/gt')`
* `require('semver/functions/gte')`
* `require('semver/functions/inc')`
* `require('semver/functions/lt')`
* `require('semver/functions/lte')`
* `require('semver/functions/major')`
* `require('semver/functions/minor')`
* `require('semver/functions/neq')`
* `require('semver/functions/parse')`
* `require('semver/functions/patch')`
* `require('semver/functions/prerelease')`
* `require('semver/functions/rcompare')`
* `require('semver/functions/rsort')`
* `require('semver/functions/satisfies')`
* `require('semver/functions/sort')`
* `require('semver/functions/valid')`
* `require('semver/ranges/gtr')`
* `require('semver/ranges/intersects')`
* `require('semver/ranges/ltr')`
* `require('semver/ranges/max-satisfying')`
* `require('semver/ranges/min-satisfying')`
* `require('semver/ranges/min-version')`
* `require('semver/ranges/outside')`
* `require('semver/ranges/to-comparators')`
* `require('semver/ranges/valid')`

View File

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

View File

@ -1,136 +0,0 @@
const ANY = Symbol('SemVer ANY')
// hoisted class for cyclic dependency
class Comparator {
static get ANY () {
return ANY
}
constructor (comp, options) {
options = parseOptions(options)
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp
} else {
comp = comp.value
}
}
debug('comparator', comp, options)
this.options = options
this.loose = !!options.loose
this.parse(comp)
if (this.semver === ANY) {
this.value = ''
} else {
this.value = this.operator + this.semver.version
}
debug('comp', this)
}
parse (comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
const m = comp.match(r)
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`)
}
this.operator = m[1] !== undefined ? m[1] : ''
if (this.operator === '=') {
this.operator = ''
}
// if it literally is just '>' or '' then allow anything.
if (!m[2]) {
this.semver = ANY
} else {
this.semver = new SemVer(m[2], this.options.loose)
}
}
toString () {
return this.value
}
test (version) {
debug('Comparator.test', version, this.options.loose)
if (this.semver === ANY || version === ANY) {
return true
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
return cmp(version, this.operator, this.semver, this.options)
}
intersects (comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required')
}
if (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false,
}
}
if (this.operator === '') {
if (this.value === '') {
return true
}
return new Range(comp.value, options).test(this.value)
} else if (comp.operator === '') {
if (comp.value === '') {
return true
}
return new Range(this.value, options).test(comp.semver)
}
const sameDirectionIncreasing =
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '>=' || comp.operator === '>')
const sameDirectionDecreasing =
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '<=' || comp.operator === '<')
const sameSemVer = this.semver.version === comp.semver.version
const differentDirectionsInclusive =
(this.operator === '>=' || this.operator === '<=') &&
(comp.operator === '>=' || comp.operator === '<=')
const oppositeDirectionsLessThan =
cmp(this.semver, '<', comp.semver, options) &&
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '<=' || comp.operator === '<')
const oppositeDirectionsGreaterThan =
cmp(this.semver, '>', comp.semver, options) &&
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '>=' || comp.operator === '>')
return (
sameDirectionIncreasing ||
sameDirectionDecreasing ||
(sameSemVer && differentDirectionsInclusive) ||
oppositeDirectionsLessThan ||
oppositeDirectionsGreaterThan
)
}
}
module.exports = Comparator
const parseOptions = require('../internal/parse-options')
const { re, t } = require('../internal/re')
const cmp = require('../functions/cmp')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const Range = require('./range')

View File

@ -1,5 +0,0 @@
module.exports = {
SemVer: require('./semver.js'),
Range: require('./range.js'),
Comparator: require('./comparator.js'),
}

View File

@ -1,522 +0,0 @@
// hoisted class for cyclic dependency
class Range {
constructor (range, options) {
options = parseOptions(options)
if (range instanceof Range) {
if (
range.loose === !!options.loose &&
range.includePrerelease === !!options.includePrerelease
) {
return range
} else {
return new Range(range.raw, options)
}
}
if (range instanceof Comparator) {
// just put it in the set and return
this.raw = range.value
this.set = [[range]]
this.format()
return this
}
this.options = options
this.loose = !!options.loose
this.includePrerelease = !!options.includePrerelease
// First, split based on boolean or ||
this.raw = range
this.set = range
.split('||')
// map the range to a 2d array of comparators
.map(r => this.parseRange(r.trim()))
// throw out any comparator lists that are empty
// this generally means that it was not a valid range, which is allowed
// in loose mode, but will still throw if the WHOLE range is invalid.
.filter(c => c.length)
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${range}`)
}
// if we have any that are not the null set, throw out null sets.
if (this.set.length > 1) {
// keep the first one, in case they're all null sets
const first = this.set[0]
this.set = this.set.filter(c => !isNullSet(c[0]))
if (this.set.length === 0) {
this.set = [first]
} else if (this.set.length > 1) {
// if we have any that are *, then the range is just *
for (const c of this.set) {
if (c.length === 1 && isAny(c[0])) {
this.set = [c]
break
}
}
}
}
this.format()
}
format () {
this.range = this.set
.map((comps) => {
return comps.join(' ').trim()
})
.join('||')
.trim()
return this.range
}
toString () {
return this.range
}
parseRange (range) {
range = range.trim()
// memoize range parsing for performance.
// this is a very hot path, and fully deterministic.
const memoOpts = Object.keys(this.options).join(',')
const memoKey = `parseRange:${memoOpts}:${range}`
const cached = cache.get(memoKey)
if (cached) {
return cached
}
const loose = this.options.loose
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
debug('hyphen replace', range)
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
debug('comparator trim', range)
// `~ 1.2.3` => `~1.2.3`
range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
// normalize spaces
range = range.split(/\s+/).join(' ')
// At this point, the range is completely trimmed and
// ready to be split into comparators.
let rangeList = range
.split(' ')
.map(comp => parseComparator(comp, this.options))
.join(' ')
.split(/\s+/)
// >=0.0.0 is equivalent to *
.map(comp => replaceGTE0(comp, this.options))
if (loose) {
// in loose mode, throw out any that are not valid comparators
rangeList = rangeList.filter(comp => {
debug('loose invalid filter', comp, this.options)
return !!comp.match(re[t.COMPARATORLOOSE])
})
}
debug('range list', rangeList)
// if any comparators are the null set, then replace with JUST null set
// if more than one comparator, remove any * comparators
// also, don't include the same comparator more than once
const rangeMap = new Map()
const comparators = rangeList.map(comp => new Comparator(comp, this.options))
for (const comp of comparators) {
if (isNullSet(comp)) {
return [comp]
}
rangeMap.set(comp.value, comp)
}
if (rangeMap.size > 1 && rangeMap.has('')) {
rangeMap.delete('')
}
const result = [...rangeMap.values()]
cache.set(memoKey, result)
return result
}
intersects (range, options) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required')
}
return this.set.some((thisComparators) => {
return (
isSatisfiable(thisComparators, options) &&
range.set.some((rangeComparators) => {
return (
isSatisfiable(rangeComparators, options) &&
thisComparators.every((thisComparator) => {
return rangeComparators.every((rangeComparator) => {
return thisComparator.intersects(rangeComparator, options)
})
})
)
})
)
})
}
// if ANY of the sets match ALL of its comparators, then pass
test (version) {
if (!version) {
return false
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true
}
}
return false
}
}
module.exports = Range
const LRU = require('lru-cache')
const cache = new LRU({ max: 1000 })
const parseOptions = require('../internal/parse-options')
const Comparator = require('./comparator')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const {
re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace,
} = require('../internal/re')
const isNullSet = c => c.value === '<0.0.0-0'
const isAny = c => c.value === ''
// take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
let result = true
const remainingComparators = comparators.slice()
let testComparator = remainingComparators.pop()
while (result && remainingComparators.length) {
result = remainingComparators.every((otherComparator) => {
return testComparator.intersects(otherComparator, options)
})
testComparator = remainingComparators.pop()
}
return result
}
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const parseComparator = (comp, options) => {
debug('comp', comp, options)
comp = replaceCarets(comp, options)
debug('caret', comp)
comp = replaceTildes(comp, options)
debug('tildes', comp)
comp = replaceXRanges(comp, options)
debug('xrange', comp)
comp = replaceStars(comp, options)
debug('stars', comp)
return comp
}
const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
// ~0.0.1 --> >=0.0.1 <0.1.0-0
const replaceTildes = (comp, options) =>
comp.trim().split(/\s+/).map((c) => {
return replaceTilde(c, options)
}).join(' ')
const replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
return comp.replace(r, (_, M, m, p, pr) => {
debug('tilde', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
} else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
} else if (pr) {
debug('replaceTilde pr', pr)
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
} else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = `>=${M}.${m}.${p
} <${M}.${+m + 1}.0-0`
}
debug('tilde return', ret)
return ret
})
}
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
// ^0.0.1 --> >=0.0.1 <0.0.2-0
// ^0.1.0 --> >=0.1.0 <0.2.0-0
const replaceCarets = (comp, options) =>
comp.trim().split(/\s+/).map((c) => {
return replaceCaret(c, options)
}).join(' ')
const replaceCaret = (comp, options) => {
debug('caret', comp, options)
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
const z = options.includePrerelease ? '-0' : ''
return comp.replace(r, (_, M, m, p, pr) => {
debug('caret', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
} else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
} else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
}
} else if (pr) {
debug('replaceCaret pr', pr)
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${+M + 1}.0.0-0`
}
} else {
debug('no pr')
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p
}${z} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p
}${z} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p
} <${+M + 1}.0.0-0`
}
}
debug('caret return', ret)
return ret
})
}
const replaceXRanges = (comp, options) => {
debug('replaceXRanges', comp, options)
return comp.split(/\s+/).map((c) => {
return replaceXRange(c, options)
}).join(' ')
}
const replaceXRange = (comp, options) => {
comp = comp.trim()
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
debug('xRange', comp, ret, gtlt, M, m, p, pr)
const xM = isX(M)
const xm = xM || isX(m)
const xp = xm || isX(p)
const anyX = xp
if (gtlt === '=' && anyX) {
gtlt = ''
}
// if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options.includePrerelease ? '-0' : ''
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0'
} else {
// nothing is forbidden
ret = '*'
}
} else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0
}
p = 0
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
gtlt = '>='
if (xm) {
M = +M + 1
m = 0
p = 0
} else {
m = +m + 1
p = 0
}
} else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<'
if (xm) {
M = +M + 1
} else {
m = +m + 1
}
}
if (gtlt === '<') {
pr = '-0'
}
ret = `${gtlt + M}.${m}.${p}${pr}`
} else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
} else if (xp) {
ret = `>=${M}.${m}.0${pr
} <${M}.${+m + 1}.0-0`
}
debug('xRange return', ret)
return ret
})
}
// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
const replaceStars = (comp, options) => {
debug('replaceStars', comp, options)
// Looseness is ignored here. star is always as loose as it gets!
return comp.trim().replace(re[t.STAR], '')
}
const replaceGTE0 = (comp, options) => {
debug('replaceGTE0', comp, options)
return comp.trim()
.replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
}
// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
const hyphenReplace = incPr => ($0,
from, fM, fm, fp, fpr, fb,
to, tM, tm, tp, tpr, tb) => {
if (isX(fM)) {
from = ''
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? '-0' : ''}`
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
} else if (fpr) {
from = `>=${from}`
} else {
from = `>=${from}${incPr ? '-0' : ''}`
}
if (isX(tM)) {
to = ''
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`
} else {
to = `<=${to}`
}
return (`${from} ${to}`).trim()
}
const testSet = (set, version, options) => {
for (let i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false
}
}
if (version.prerelease.length && !options.includePrerelease) {
// Find the set of versions that are allowed to have prereleases
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
// That should allow `1.2.3-pr.2` to pass.
// However, `1.2.4-alpha.notready` should NOT be allowed,
// even though it's within the range set by the comparators.
for (let i = 0; i < set.length; i++) {
debug(set[i].semver)
if (set[i].semver === Comparator.ANY) {
continue
}
if (set[i].semver.prerelease.length > 0) {
const allowed = set[i].semver
if (allowed.major === version.major &&
allowed.minor === version.minor &&
allowed.patch === version.patch) {
return true
}
}
}
// Version has a -pre, but it's not one of the ones we like.
return false
}
return true
}

View File

@ -1,287 +0,0 @@
const debug = require('../internal/debug')
const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')
const { re, t } = require('../internal/re')
const parseOptions = require('../internal/parse-options')
const { compareIdentifiers } = require('../internal/identifiers')
class SemVer {
constructor (version, options) {
options = parseOptions(options)
if (version instanceof SemVer) {
if (version.loose === !!options.loose &&
version.includePrerelease === !!options.includePrerelease) {
return version
} else {
version = version.version
}
} else if (typeof version !== 'string') {
throw new TypeError(`Invalid Version: ${version}`)
}
if (version.length > MAX_LENGTH) {
throw new TypeError(
`version is longer than ${MAX_LENGTH} characters`
)
}
debug('SemVer', version, options)
this.options = options
this.loose = !!options.loose
// this isn't actually relevant for versions, but keep it so that we
// don't run into trouble passing this.options around.
this.includePrerelease = !!options.includePrerelease
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
if (!m) {
throw new TypeError(`Invalid Version: ${version}`)
}
this.raw = version
// these are actually numbers
this.major = +m[1]
this.minor = +m[2]
this.patch = +m[3]
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError('Invalid major version')
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError('Invalid minor version')
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError('Invalid patch version')
}
// numberify any prerelease numeric ids
if (!m[4]) {
this.prerelease = []
} else {
this.prerelease = m[4].split('.').map((id) => {
if (/^[0-9]+$/.test(id)) {
const num = +id
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num
}
}
return id
})
}
this.build = m[5] ? m[5].split('.') : []
this.format()
}
format () {
this.version = `${this.major}.${this.minor}.${this.patch}`
if (this.prerelease.length) {
this.version += `-${this.prerelease.join('.')}`
}
return this.version
}
toString () {
return this.version
}
compare (other) {
debug('SemVer.compare', this.version, this.options, other)
if (!(other instanceof SemVer)) {
if (typeof other === 'string' && other === this.version) {
return 0
}
other = new SemVer(other, this.options)
}
if (other.version === this.version) {
return 0
}
return this.compareMain(other) || this.comparePre(other)
}
compareMain (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
return (
compareIdentifiers(this.major, other.major) ||
compareIdentifiers(this.minor, other.minor) ||
compareIdentifiers(this.patch, other.patch)
)
}
comparePre (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
// NOT having a prerelease is > having one
if (this.prerelease.length && !other.prerelease.length) {
return -1
} else if (!this.prerelease.length && other.prerelease.length) {
return 1
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0
}
let i = 0
do {
const a = this.prerelease[i]
const b = other.prerelease[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
compareBuild (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
let i = 0
do {
const a = this.build[i]
const b = other.build[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
inc (release, identifier) {
switch (release) {
case 'premajor':
this.prerelease.length = 0
this.patch = 0
this.minor = 0
this.major++
this.inc('pre', identifier)
break
case 'preminor':
this.prerelease.length = 0
this.patch = 0
this.minor++
this.inc('pre', identifier)
break
case 'prepatch':
// If this is already a prerelease, it will bump to the next version
// drop any prereleases that might already exist, since they are not
// relevant at this point.
this.prerelease.length = 0
this.inc('patch', identifier)
this.inc('pre', identifier)
break
// If the input is a non-prerelease version, this acts the same as
// prepatch.
case 'prerelease':
if (this.prerelease.length === 0) {
this.inc('patch', identifier)
}
this.inc('pre', identifier)
break
case 'major':
// If this is a pre-major version, bump up to the same major version.
// Otherwise increment major.
// 1.0.0-5 bumps to 1.0.0
// 1.1.0 bumps to 2.0.0
if (
this.minor !== 0 ||
this.patch !== 0 ||
this.prerelease.length === 0
) {
this.major++
}
this.minor = 0
this.patch = 0
this.prerelease = []
break
case 'minor':
// If this is a pre-minor version, bump up to the same minor version.
// Otherwise increment minor.
// 1.2.0-5 bumps to 1.2.0
// 1.2.1 bumps to 1.3.0
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++
}
this.patch = 0
this.prerelease = []
break
case 'patch':
// If this is not a pre-release version, it will increment the patch.
// If it is a pre-release it will bump up to the same patch version.
// 1.2.0-5 patches to 1.2.0
// 1.2.0 patches to 1.2.1
if (this.prerelease.length === 0) {
this.patch++
}
this.prerelease = []
break
// This probably shouldn't be used publicly.
// 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
case 'pre':
if (this.prerelease.length === 0) {
this.prerelease = [0]
} else {
let i = this.prerelease.length
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++
i = -2
}
}
if (i === -1) {
// didn't increment anything
this.prerelease.push(0)
}
}
if (identifier) {
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
if (isNaN(this.prerelease[1])) {
this.prerelease = [identifier, 0]
}
} else {
this.prerelease = [identifier, 0]
}
}
break
default:
throw new Error(`invalid increment argument: ${release}`)
}
this.format()
this.raw = this.version
return this
}
}
module.exports = SemVer

View File

@ -1,6 +0,0 @@
const parse = require('./parse')
const clean = (version, options) => {
const s = parse(version.trim().replace(/^[=v]+/, ''), options)
return s ? s.version : null
}
module.exports = clean

View File

@ -1,52 +0,0 @@
const eq = require('./eq')
const neq = require('./neq')
const gt = require('./gt')
const gte = require('./gte')
const lt = require('./lt')
const lte = require('./lte')
const cmp = (a, op, b, loose) => {
switch (op) {
case '===':
if (typeof a === 'object') {
a = a.version
}
if (typeof b === 'object') {
b = b.version
}
return a === b
case '!==':
if (typeof a === 'object') {
a = a.version
}
if (typeof b === 'object') {
b = b.version
}
return a !== b
case '':
case '=':
case '==':
return eq(a, b, loose)
case '!=':
return neq(a, b, loose)
case '>':
return gt(a, b, loose)
case '>=':
return gte(a, b, loose)
case '<':
return lt(a, b, loose)
case '<=':
return lte(a, b, loose)
default:
throw new TypeError(`Invalid operator: ${op}`)
}
}
module.exports = cmp

View File

@ -1,52 +0,0 @@
const SemVer = require('../classes/semver')
const parse = require('./parse')
const { re, t } = require('../internal/re')
const coerce = (version, options) => {
if (version instanceof SemVer) {
return version
}
if (typeof version === 'number') {
version = String(version)
}
if (typeof version !== 'string') {
return null
}
options = options || {}
let match = null
if (!options.rtl) {
match = version.match(re[t.COERCE])
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
//
// Walk through the string checking with a /g regexp
// Manually set the index so as to pick up overlapping matches.
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
let next
while ((next = re[t.COERCERTL].exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
re[t.COERCERTL].lastIndex = -1
}
if (match === null) {
return null
}
return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
}
module.exports = coerce

View File

@ -1,7 +0,0 @@
const SemVer = require('../classes/semver')
const compareBuild = (a, b, loose) => {
const versionA = new SemVer(a, loose)
const versionB = new SemVer(b, loose)
return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
module.exports = compareBuild

View File

@ -1,3 +0,0 @@
const compare = require('./compare')
const compareLoose = (a, b) => compare(a, b, true)
module.exports = compareLoose

View File

@ -1,5 +0,0 @@
const SemVer = require('../classes/semver')
const compare = (a, b, loose) =>
new SemVer(a, loose).compare(new SemVer(b, loose))
module.exports = compare

View File

@ -1,23 +0,0 @@
const parse = require('./parse')
const eq = require('./eq')
const diff = (version1, version2) => {
if (eq(version1, version2)) {
return null
} else {
const v1 = parse(version1)
const v2 = parse(version2)
const hasPre = v1.prerelease.length || v2.prerelease.length
const prefix = hasPre ? 'pre' : ''
const defaultResult = hasPre ? 'prerelease' : ''
for (const key in v1) {
if (key === 'major' || key === 'minor' || key === 'patch') {
if (v1[key] !== v2[key]) {
return prefix + key
}
}
}
return defaultResult // may be undefined
}
}
module.exports = diff

View File

@ -1,3 +0,0 @@
const compare = require('./compare')
const eq = (a, b, loose) => compare(a, b, loose) === 0
module.exports = eq

View File

@ -1,3 +0,0 @@
const compare = require('./compare')
const gt = (a, b, loose) => compare(a, b, loose) > 0
module.exports = gt

View File

@ -1,3 +0,0 @@
const compare = require('./compare')
const gte = (a, b, loose) => compare(a, b, loose) >= 0
module.exports = gte

View File

@ -1,18 +0,0 @@
const SemVer = require('../classes/semver')
const inc = (version, release, options, identifier) => {
if (typeof (options) === 'string') {
identifier = options
options = undefined
}
try {
return new SemVer(
version instanceof SemVer ? version.version : version,
options
).inc(release, identifier).version
} catch (er) {
return null
}
}
module.exports = inc

View File

@ -1,3 +0,0 @@
const compare = require('./compare')
const lt = (a, b, loose) => compare(a, b, loose) < 0
module.exports = lt

View File

@ -1,3 +0,0 @@
const compare = require('./compare')
const lte = (a, b, loose) => compare(a, b, loose) <= 0
module.exports = lte

View File

@ -1,3 +0,0 @@
const SemVer = require('../classes/semver')
const major = (a, loose) => new SemVer(a, loose).major
module.exports = major

View File

@ -1,3 +0,0 @@
const SemVer = require('../classes/semver')
const minor = (a, loose) => new SemVer(a, loose).minor
module.exports = minor

View File

@ -1,3 +0,0 @@
const compare = require('./compare')
const neq = (a, b, loose) => compare(a, b, loose) !== 0
module.exports = neq

View File

@ -1,33 +0,0 @@
const { MAX_LENGTH } = require('../internal/constants')
const { re, t } = require('../internal/re')
const SemVer = require('../classes/semver')
const parseOptions = require('../internal/parse-options')
const parse = (version, options) => {
options = parseOptions(options)
if (version instanceof SemVer) {
return version
}
if (typeof version !== 'string') {
return null
}
if (version.length > MAX_LENGTH) {
return null
}
const r = options.loose ? re[t.LOOSE] : re[t.FULL]
if (!r.test(version)) {
return null
}
try {
return new SemVer(version, options)
} catch (er) {
return null
}
}
module.exports = parse

View File

@ -1,3 +0,0 @@
const SemVer = require('../classes/semver')
const patch = (a, loose) => new SemVer(a, loose).patch
module.exports = patch

View File

@ -1,6 +0,0 @@
const parse = require('./parse')
const prerelease = (version, options) => {
const parsed = parse(version, options)
return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
module.exports = prerelease

View File

@ -1,3 +0,0 @@
const compare = require('./compare')
const rcompare = (a, b, loose) => compare(b, a, loose)
module.exports = rcompare

View File

@ -1,3 +0,0 @@
const compareBuild = require('./compare-build')
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
module.exports = rsort

View File

@ -1,10 +0,0 @@
const Range = require('../classes/range')
const satisfies = (version, range, options) => {
try {
range = new Range(range, options)
} catch (er) {
return false
}
return range.test(version)
}
module.exports = satisfies

View File

@ -1,3 +0,0 @@
const compareBuild = require('./compare-build')
const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
module.exports = sort

View File

@ -1,6 +0,0 @@
const parse = require('./parse')
const valid = (version, options) => {
const v = parse(version, options)
return v ? v.version : null
}
module.exports = valid

View File

@ -1,88 +0,0 @@
// just pre-load all the stuff that index.js lazily exports
const internalRe = require('./internal/re')
const constants = require('./internal/constants')
const SemVer = require('./classes/semver')
const identifiers = require('./internal/identifiers')
const parse = require('./functions/parse')
const valid = require('./functions/valid')
const clean = require('./functions/clean')
const inc = require('./functions/inc')
const diff = require('./functions/diff')
const major = require('./functions/major')
const minor = require('./functions/minor')
const patch = require('./functions/patch')
const prerelease = require('./functions/prerelease')
const compare = require('./functions/compare')
const rcompare = require('./functions/rcompare')
const compareLoose = require('./functions/compare-loose')
const compareBuild = require('./functions/compare-build')
const sort = require('./functions/sort')
const rsort = require('./functions/rsort')
const gt = require('./functions/gt')
const lt = require('./functions/lt')
const eq = require('./functions/eq')
const neq = require('./functions/neq')
const gte = require('./functions/gte')
const lte = require('./functions/lte')
const cmp = require('./functions/cmp')
const coerce = require('./functions/coerce')
const Comparator = require('./classes/comparator')
const Range = require('./classes/range')
const satisfies = require('./functions/satisfies')
const toComparators = require('./ranges/to-comparators')
const maxSatisfying = require('./ranges/max-satisfying')
const minSatisfying = require('./ranges/min-satisfying')
const minVersion = require('./ranges/min-version')
const validRange = require('./ranges/valid')
const outside = require('./ranges/outside')
const gtr = require('./ranges/gtr')
const ltr = require('./ranges/ltr')
const intersects = require('./ranges/intersects')
const simplifyRange = require('./ranges/simplify')
const subset = require('./ranges/subset')
module.exports = {
parse,
valid,
clean,
inc,
diff,
major,
minor,
patch,
prerelease,
compare,
rcompare,
compareLoose,
compareBuild,
sort,
rsort,
gt,
lt,
eq,
neq,
gte,
lte,
cmp,
coerce,
Comparator,
Range,
satisfies,
toComparators,
maxSatisfying,
minSatisfying,
minVersion,
validRange,
outside,
gtr,
ltr,
intersects,
simplifyRange,
subset,
SemVer,
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
compareIdentifiers: identifiers.compareIdentifiers,
rcompareIdentifiers: identifiers.rcompareIdentifiers,
}

View File

@ -1,17 +0,0 @@
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0'
const MAX_LENGTH = 256
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */ 9007199254740991
// Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16
module.exports = {
SEMVER_SPEC_VERSION,
MAX_LENGTH,
MAX_SAFE_INTEGER,
MAX_SAFE_COMPONENT_LENGTH,
}

View File

@ -1,9 +0,0 @@
const debug = (
typeof process === 'object' &&
process.env &&
process.env.NODE_DEBUG &&
/\bsemver\b/i.test(process.env.NODE_DEBUG)
) ? (...args) => console.error('SEMVER', ...args)
: () => {}
module.exports = debug

View File

@ -1,23 +0,0 @@
const numeric = /^[0-9]+$/
const compareIdentifiers = (a, b) => {
const anum = numeric.test(a)
const bnum = numeric.test(b)
if (anum && bnum) {
a = +a
b = +b
}
return a === b ? 0
: (anum && !bnum) ? -1
: (bnum && !anum) ? 1
: a < b ? -1
: 1
}
const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
module.exports = {
compareIdentifiers,
rcompareIdentifiers,
}

View File

@ -1,11 +0,0 @@
// parse out just the options we care about so we always get a consistent
// obj with keys in a consistent order.
const opts = ['includePrerelease', 'loose', 'rtl']
const parseOptions = options =>
!options ? {}
: typeof options !== 'object' ? { loose: true }
: opts.filter(k => options[k]).reduce((o, k) => {
o[k] = true
return o
}, {})
module.exports = parseOptions

View File

@ -1,182 +0,0 @@
const { MAX_SAFE_COMPONENT_LENGTH } = require('./constants')
const debug = require('./debug')
exports = module.exports = {}
// The actual regexps go on exports.re
const re = exports.re = []
const src = exports.src = []
const t = exports.t = {}
let R = 0
const createToken = (name, value, isGlobal) => {
const index = R++
debug(name, index, value)
t[name] = index
src[index] = value
re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
}
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+')
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*')
// ## Main Version
// Three dot-separated numeric identifiers.
createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})`)
createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})`)
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]
}|${src[t.NONNUMERICIDENTIFIER]})`)
createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]
}|${src[t.NONNUMERICIDENTIFIER]})`)
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+')
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups. The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
}${src[t.PRERELEASE]}?${
src[t.BUILD]}?`)
createToken('FULL', `^${src[t.FULLPLAIN]}$`)
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
}${src[t.PRERELEASELOOSE]}?${
src[t.BUILD]}?`)
createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
createToken('GTLT', '((?:<|>)?=?)')
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:${src[t.PRERELEASE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:${src[t.PRERELEASELOOSE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCE', `${'(^|[^\\d])' +
'(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
`(?:$|[^\\d])`)
createToken('COERCERTL', src[t.COERCE], true)
// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)')
createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
exports.tildeTrimReplace = '$1~'
createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)')
createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
exports.caretTrimReplace = '$1^'
createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
exports.comparatorTrimReplace = '$1$2$3'
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAIN]})` +
`\\s*$`)
createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAINLOOSE]})` +
`\\s*$`)
// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*')
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')

View File

@ -1,86 +1,28 @@
{
"name": "semver",
"version": "7.3.8",
"version": "6.3.0",
"description": "The semantic version parser used by npm.",
"main": "index.js",
"main": "semver.js",
"scripts": {
"test": "tap",
"snap": "tap",
"lint": "eslint \"**/*.js\"",
"postlint": "template-oss-check",
"lintfix": "npm run lint -- --fix",
"posttest": "npm run lint",
"template-oss-apply": "template-oss-apply --force"
"preversion": "npm test",
"postversion": "npm publish",
"postpublish": "git push origin --follow-tags"
},
"devDependencies": {
"@npmcli/eslint-config": "^3.0.1",
"@npmcli/template-oss": "4.4.4",
"tap": "^16.0.0"
"tap": "^14.3.1"
},
"license": "ISC",
"repository": {
"type": "git",
"url": "https://github.com/npm/node-semver.git"
},
"repository": "https://github.com/npm/node-semver",
"bin": {
"semver": "bin/semver.js"
"semver": "./bin/semver.js"
},
"files": [
"bin/",
"lib/",
"classes/",
"functions/",
"internal/",
"ranges/",
"index.js",
"preload.js",
"range.bnf"
"bin",
"range.bnf",
"semver.js"
],
"tap": {
"check-coverage": true,
"coverage-map": "map.js",
"nyc-arg": [
"--exclude",
"tap-snapshots/**"
]
},
"engines": {
"node": ">=10"
},
"dependencies": {
"lru-cache": "^6.0.0"
},
"author": "GitHub Inc.",
"templateOSS": {
"//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
"version": "4.4.4",
"engines": ">=10",
"content": "./scripts",
"ciVersions": [
"10.0.0",
"10.x",
"12.x",
"14.x",
"16.x",
"18.x"
],
"distPaths": [
"classes/",
"functions/",
"internal/",
"ranges/",
"index.js",
"preload.js",
"range.bnf"
],
"allowPaths": [
"/classes/",
"/functions/",
"/internal/",
"/ranges/",
"/index.js",
"/preload.js",
"/range.bnf"
]
"check-coverage": true
}
}

View File

@ -1,2 +0,0 @@
// XXX remove in v8 or beyond
module.exports = require('./index.js')

View File

@ -1,4 +0,0 @@
// Determine if version is greater than all the versions possible in the range.
const outside = require('./outside')
const gtr = (version, range, options) => outside(version, range, '>', options)
module.exports = gtr

View File

@ -1,7 +0,0 @@
const Range = require('../classes/range')
const intersects = (r1, r2, options) => {
r1 = new Range(r1, options)
r2 = new Range(r2, options)
return r1.intersects(r2)
}
module.exports = intersects

View File

@ -1,4 +0,0 @@
const outside = require('./outside')
// Determine if version is less than all the versions possible in the range
const ltr = (version, range, options) => outside(version, range, '<', options)
module.exports = ltr

View File

@ -1,25 +0,0 @@
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const maxSatisfying = (versions, range, options) => {
let max = null
let maxSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!max || maxSV.compare(v) === -1) {
// compare(max, v, true)
max = v
maxSV = new SemVer(max, options)
}
}
})
return max
}
module.exports = maxSatisfying

View File

@ -1,24 +0,0 @@
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const minSatisfying = (versions, range, options) => {
let min = null
let minSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!min || minSV.compare(v) === 1) {
// compare(min, v, true)
min = v
minSV = new SemVer(min, options)
}
}
})
return min
}
module.exports = minSatisfying

View File

@ -1,61 +0,0 @@
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const gt = require('../functions/gt')
const minVersion = (range, loose) => {
range = new Range(range, loose)
let minver = new SemVer('0.0.0')
if (range.test(minver)) {
return minver
}
minver = new SemVer('0.0.0-0')
if (range.test(minver)) {
return minver
}
minver = null
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i]
let setMin = null
comparators.forEach((comparator) => {
// Clone to avoid manipulating the comparator's semver object.
const compver = new SemVer(comparator.semver.version)
switch (comparator.operator) {
case '>':
if (compver.prerelease.length === 0) {
compver.patch++
} else {
compver.prerelease.push(0)
}
compver.raw = compver.format()
/* fallthrough */
case '':
case '>=':
if (!setMin || gt(compver, setMin)) {
setMin = compver
}
break
case '<':
case '<=':
/* Ignore maximum versions */
break
/* istanbul ignore next */
default:
throw new Error(`Unexpected operation: ${comparator.operator}`)
}
})
if (setMin && (!minver || gt(minver, setMin))) {
minver = setMin
}
}
if (minver && range.test(minver)) {
return minver
}
return null
}
module.exports = minVersion

View File

@ -1,80 +0,0 @@
const SemVer = require('../classes/semver')
const Comparator = require('../classes/comparator')
const { ANY } = Comparator
const Range = require('../classes/range')
const satisfies = require('../functions/satisfies')
const gt = require('../functions/gt')
const lt = require('../functions/lt')
const lte = require('../functions/lte')
const gte = require('../functions/gte')
const outside = (version, range, hilo, options) => {
version = new SemVer(version, options)
range = new Range(range, options)
let gtfn, ltefn, ltfn, comp, ecomp
switch (hilo) {
case '>':
gtfn = gt
ltefn = lte
ltfn = lt
comp = '>'
ecomp = '>='
break
case '<':
gtfn = lt
ltefn = gte
ltfn = gt
comp = '<'
ecomp = '<='
break
default:
throw new TypeError('Must provide a hilo val of "<" or ">"')
}
// If it satisfies the range it is not outside
if (satisfies(version, range, options)) {
return false
}
// From now on, variable terms are as if we're in "gtr" mode.
// but note that everything is flipped for the "ltr" function.
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i]
let high = null
let low = null
comparators.forEach((comparator) => {
if (comparator.semver === ANY) {
comparator = new Comparator('>=0.0.0')
}
high = high || comparator
low = low || comparator
if (gtfn(comparator.semver, high.semver, options)) {
high = comparator
} else if (ltfn(comparator.semver, low.semver, options)) {
low = comparator
}
})
// If the edge version comparator has a operator then our version
// isn't outside it
if (high.operator === comp || high.operator === ecomp) {
return false
}
// If the lowest version comparator has an operator and our version
// is less than it then it isn't higher than the range
if ((!low.operator || low.operator === comp) &&
ltefn(version, low.semver)) {
return false
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
return false
}
}
return true
}
module.exports = outside

View File

@ -1,47 +0,0 @@
// given a set of versions and a range, create a "simplified" range
// that includes the same versions that the original range does
// If the original range is shorter than the simplified one, return that.
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')
module.exports = (versions, range, options) => {
const set = []
let first = null
let prev = null
const v = versions.sort((a, b) => compare(a, b, options))
for (const version of v) {
const included = satisfies(version, range, options)
if (included) {
prev = version
if (!first) {
first = version
}
} else {
if (prev) {
set.push([first, prev])
}
prev = null
first = null
}
}
if (first) {
set.push([first, null])
}
const ranges = []
for (const [min, max] of set) {
if (min === max) {
ranges.push(min)
} else if (!max && min === v[0]) {
ranges.push('*')
} else if (!max) {
ranges.push(`>=${min}`)
} else if (min === v[0]) {
ranges.push(`<=${max}`)
} else {
ranges.push(`${min} - ${max}`)
}
}
const simplified = ranges.join(' || ')
const original = typeof range.raw === 'string' ? range.raw : String(range)
return simplified.length < original.length ? simplified : range
}

View File

@ -1,244 +0,0 @@
const Range = require('../classes/range.js')
const Comparator = require('../classes/comparator.js')
const { ANY } = Comparator
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')
// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
// - Every simple range `r1, r2, ...` is a null set, OR
// - Every simple range `r1, r2, ...` which is not a null set is a subset of
// some `R1, R2, ...`
//
// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
// - If c is only the ANY comparator
// - If C is only the ANY comparator, return true
// - Else if in prerelease mode, return false
// - else replace c with `[>=0.0.0]`
// - If C is only the ANY comparator
// - if in prerelease mode, return true
// - else replace C with `[>=0.0.0]`
// - Let EQ be the set of = comparators in c
// - If EQ is more than one, return true (null set)
// - Let GT be the highest > or >= comparator in c
// - Let LT be the lowest < or <= comparator in c
// - If GT and LT, and GT.semver > LT.semver, return true (null set)
// - If any C is a = range, and GT or LT are set, return false
// - If EQ
// - If GT, and EQ does not satisfy GT, return true (null set)
// - If LT, and EQ does not satisfy LT, return true (null set)
// - If EQ satisfies every C, return true
// - Else return false
// - If GT
// - If GT.semver is lower than any > or >= comp in C, return false
// - If GT is >=, and GT.semver does not satisfy every C, return false
// - If GT.semver has a prerelease, and not in prerelease mode
// - If no C has a prerelease and the GT.semver tuple, return false
// - If LT
// - If LT.semver is greater than any < or <= comp in C, return false
// - If LT is <=, and LT.semver does not satisfy every C, return false
// - If GT.semver has a prerelease, and not in prerelease mode
// - If no C has a prerelease and the LT.semver tuple, return false
// - Else return true
const subset = (sub, dom, options = {}) => {
if (sub === dom) {
return true
}
sub = new Range(sub, options)
dom = new Range(dom, options)
let sawNonNull = false
OUTER: for (const simpleSub of sub.set) {
for (const simpleDom of dom.set) {
const isSub = simpleSubset(simpleSub, simpleDom, options)
sawNonNull = sawNonNull || isSub !== null
if (isSub) {
continue OUTER
}
}
// the null set is a subset of everything, but null simple ranges in
// a complex range should be ignored. so if we saw a non-null range,
// then we know this isn't a subset, but if EVERY simple range was null,
// then it is a subset.
if (sawNonNull) {
return false
}
}
return true
}
const simpleSubset = (sub, dom, options) => {
if (sub === dom) {
return true
}
if (sub.length === 1 && sub[0].semver === ANY) {
if (dom.length === 1 && dom[0].semver === ANY) {
return true
} else if (options.includePrerelease) {
sub = [new Comparator('>=0.0.0-0')]
} else {
sub = [new Comparator('>=0.0.0')]
}
}
if (dom.length === 1 && dom[0].semver === ANY) {
if (options.includePrerelease) {
return true
} else {
dom = [new Comparator('>=0.0.0')]
}
}
const eqSet = new Set()
let gt, lt
for (const c of sub) {
if (c.operator === '>' || c.operator === '>=') {
gt = higherGT(gt, c, options)
} else if (c.operator === '<' || c.operator === '<=') {
lt = lowerLT(lt, c, options)
} else {
eqSet.add(c.semver)
}
}
if (eqSet.size > 1) {
return null
}
let gtltComp
if (gt && lt) {
gtltComp = compare(gt.semver, lt.semver, options)
if (gtltComp > 0) {
return null
} else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
return null
}
}
// will iterate one or zero times
for (const eq of eqSet) {
if (gt && !satisfies(eq, String(gt), options)) {
return null
}
if (lt && !satisfies(eq, String(lt), options)) {
return null
}
for (const c of dom) {
if (!satisfies(eq, String(c), options)) {
return false
}
}
return true
}
let higher, lower
let hasDomLT, hasDomGT
// if the subset has a prerelease, we need a comparator in the superset
// with the same tuple and a prerelease, or it's not a subset
let needDomLTPre = lt &&
!options.includePrerelease &&
lt.semver.prerelease.length ? lt.semver : false
let needDomGTPre = gt &&
!options.includePrerelease &&
gt.semver.prerelease.length ? gt.semver : false
// exception: <1.2.3-0 is the same as <1.2.3
if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
needDomLTPre = false
}
for (const c of dom) {
hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
if (gt) {
if (needDomGTPre) {
if (c.semver.prerelease && c.semver.prerelease.length &&
c.semver.major === needDomGTPre.major &&
c.semver.minor === needDomGTPre.minor &&
c.semver.patch === needDomGTPre.patch) {
needDomGTPre = false
}
}
if (c.operator === '>' || c.operator === '>=') {
higher = higherGT(gt, c, options)
if (higher === c && higher !== gt) {
return false
}
} else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
return false
}
}
if (lt) {
if (needDomLTPre) {
if (c.semver.prerelease && c.semver.prerelease.length &&
c.semver.major === needDomLTPre.major &&
c.semver.minor === needDomLTPre.minor &&
c.semver.patch === needDomLTPre.patch) {
needDomLTPre = false
}
}
if (c.operator === '<' || c.operator === '<=') {
lower = lowerLT(lt, c, options)
if (lower === c && lower !== lt) {
return false
}
} else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
return false
}
}
if (!c.operator && (lt || gt) && gtltComp !== 0) {
return false
}
}
// if there was a < or >, and nothing in the dom, then must be false
// UNLESS it was limited by another range in the other direction.
// Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
if (gt && hasDomLT && !lt && gtltComp !== 0) {
return false
}
if (lt && hasDomGT && !gt && gtltComp !== 0) {
return false
}
// we needed a prerelease range in a specific tuple, but didn't get one
// then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,
// because it includes prereleases in the 1.2.3 tuple
if (needDomGTPre || needDomLTPre) {
return false
}
return true
}
// >=1.2.3 is lower than >1.2.3
const higherGT = (a, b, options) => {
if (!a) {
return b
}
const comp = compare(a.semver, b.semver, options)
return comp > 0 ? a
: comp < 0 ? b
: b.operator === '>' && a.operator === '>=' ? b
: a
}
// <=1.2.3 is higher than <1.2.3
const lowerLT = (a, b, options) => {
if (!a) {
return b
}
const comp = compare(a.semver, b.semver, options)
return comp < 0 ? a
: comp > 0 ? b
: b.operator === '<' && a.operator === '<=' ? b
: a
}
module.exports = subset

View File

@ -1,8 +0,0 @@
const Range = require('../classes/range')
// Mostly just for testing and legacy API reasons
const toComparators = (range, options) =>
new Range(range, options).set
.map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
module.exports = toComparators

View File

@ -1,11 +0,0 @@
const Range = require('../classes/range')
const validRange = (range, options) => {
try {
// Return '*' instead of '' so that truthiness works.
// This will throw if it's invalid anyway
return new Range(range, options).range || '*'
} catch (er) {
return null
}
}
module.exports = validRange

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +0,0 @@
The ISC License
Copyright (c) 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.

View File

@ -1,204 +0,0 @@
# yallist
Yet Another Linked List
There are many doubly-linked list implementations like it, but this
one is mine.
For when an array would be too big, and a Map can't be iterated in
reverse order.
[![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist)
## basic usage
```javascript
var yallist = require('yallist')
var myList = yallist.create([1, 2, 3])
myList.push('foo')
myList.unshift('bar')
// of course pop() and shift() are there, too
console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo']
myList.forEach(function (k) {
// walk the list head to tail
})
myList.forEachReverse(function (k, index, list) {
// walk the list tail to head
})
var myDoubledList = myList.map(function (k) {
return k + k
})
// now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo']
// mapReverse is also a thing
var myDoubledListReverse = myList.mapReverse(function (k) {
return k + k
}) // ['foofoo', 6, 4, 2, 'barbar']
var reduced = myList.reduce(function (set, entry) {
set += entry
return set
}, 'start')
console.log(reduced) // 'startfoo123bar'
```
## api
The whole API is considered "public".
Functions with the same name as an Array method work more or less the
same way.
There's reverse versions of most things because that's the point.
### Yallist
Default export, the class that holds and manages a list.
Call it with either a forEach-able (like an array) or a set of
arguments, to initialize the list.
The Array-ish methods all act like you'd expect. No magic length,
though, so if you change that it won't automatically prune or add
empty spots.
### Yallist.create(..)
Alias for Yallist function. Some people like factories.
#### yallist.head
The first node in the list
#### yallist.tail
The last node in the list
#### yallist.length
The number of nodes in the list. (Change this at your peril. It is
not magic like Array length.)
#### yallist.toArray()
Convert the list to an array.
#### yallist.forEach(fn, [thisp])
Call a function on each item in the list.
#### yallist.forEachReverse(fn, [thisp])
Call a function on each item in the list, in reverse order.
#### yallist.get(n)
Get the data at position `n` in the list. If you use this a lot,
probably better off just using an Array.
#### yallist.getReverse(n)
Get the data at position `n`, counting from the tail.
#### yallist.map(fn, thisp)
Create a new Yallist with the result of calling the function on each
item.
#### yallist.mapReverse(fn, thisp)
Same as `map`, but in reverse.
#### yallist.pop()
Get the data from the list tail, and remove the tail from the list.
#### yallist.push(item, ...)
Insert one or more items to the tail of the list.
#### yallist.reduce(fn, initialValue)
Like Array.reduce.
#### yallist.reduceReverse
Like Array.reduce, but in reverse.
#### yallist.reverse
Reverse the list in place.
#### yallist.shift()
Get the data from the list head, and remove the head from the list.
#### yallist.slice([from], [to])
Just like Array.slice, but returns a new Yallist.
#### yallist.sliceReverse([from], [to])
Just like yallist.slice, but the result is returned in reverse.
#### yallist.toArray()
Create an array representation of the list.
#### yallist.toArrayReverse()
Create a reversed array representation of the list.
#### yallist.unshift(item, ...)
Insert one or more items to the head of the list.
#### yallist.unshiftNode(node)
Move a Node object to the front of the list. (That is, pull it out of
wherever it lives, and make it the new head.)
If the node belongs to a different list, then that list will remove it
first.
#### yallist.pushNode(node)
Move a Node object to the end of the list. (That is, pull it out of
wherever it lives, and make it the new tail.)
If the node belongs to a list already, then that list will remove it
first.
#### yallist.removeNode(node)
Remove a node from the list, preserving referential integrity of head
and tail and other nodes.
Will throw an error if you try to have a list remove a node that
doesn't belong to it.
### Yallist.Node
The class that holds the data and is actually the list.
Call with `var n = new Node(value, previousNode, nextNode)`
Note that if you do direct operations on Nodes themselves, it's very
easy to get into weird states where the list is broken. Be careful :)
#### node.next
The next node in the list.
#### node.prev
The previous node in the list.
#### node.value
The data the node contains.
#### node.list
The list to which this node belongs. (Null if it does not belong to
any list.)

View File

@ -1,8 +0,0 @@
'use strict'
module.exports = function (Yallist) {
Yallist.prototype[Symbol.iterator] = function* () {
for (let walker = this.head; walker; walker = walker.next) {
yield walker.value
}
}
}

View File

@ -1,29 +0,0 @@
{
"name": "yallist",
"version": "4.0.0",
"description": "Yet Another Linked List",
"main": "yallist.js",
"directories": {
"test": "test"
},
"files": [
"yallist.js",
"iterator.js"
],
"dependencies": {},
"devDependencies": {
"tap": "^12.1.0"
},
"scripts": {
"test": "tap test/*.js --100",
"preversion": "npm test",
"postversion": "npm publish",
"postpublish": "git push origin --all; git push origin --tags"
},
"repository": {
"type": "git",
"url": "git+https://github.com/isaacs/yallist.git"
},
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)",
"license": "ISC"
}

View File

@ -1,426 +0,0 @@
'use strict'
module.exports = Yallist
Yallist.Node = Node
Yallist.create = Yallist
function Yallist (list) {
var self = this
if (!(self instanceof Yallist)) {
self = new Yallist()
}
self.tail = null
self.head = null
self.length = 0
if (list && typeof list.forEach === 'function') {
list.forEach(function (item) {
self.push(item)
})
} else if (arguments.length > 0) {
for (var i = 0, l = arguments.length; i < l; i++) {
self.push(arguments[i])
}
}
return self
}
Yallist.prototype.removeNode = function (node) {
if (node.list !== this) {
throw new Error('removing node which does not belong to this list')
}
var next = node.next
var prev = node.prev
if (next) {
next.prev = prev
}
if (prev) {
prev.next = next
}
if (node === this.head) {
this.head = next
}
if (node === this.tail) {
this.tail = prev
}
node.list.length--
node.next = null
node.prev = null
node.list = null
return next
}
Yallist.prototype.unshiftNode = function (node) {
if (node === this.head) {
return
}
if (node.list) {
node.list.removeNode(node)
}
var head = this.head
node.list = this
node.next = head
if (head) {
head.prev = node
}
this.head = node
if (!this.tail) {
this.tail = node
}
this.length++
}
Yallist.prototype.pushNode = function (node) {
if (node === this.tail) {
return
}
if (node.list) {
node.list.removeNode(node)
}
var tail = this.tail
node.list = this
node.prev = tail
if (tail) {
tail.next = node
}
this.tail = node
if (!this.head) {
this.head = node
}
this.length++
}
Yallist.prototype.push = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
push(this, arguments[i])
}
return this.length
}
Yallist.prototype.unshift = function () {
for (var i = 0, l = arguments.length; i < l; i++) {
unshift(this, arguments[i])
}
return this.length
}
Yallist.prototype.pop = function () {
if (!this.tail) {
return undefined
}
var res = this.tail.value
this.tail = this.tail.prev
if (this.tail) {
this.tail.next = null
} else {
this.head = null
}
this.length--
return res
}
Yallist.prototype.shift = function () {
if (!this.head) {
return undefined
}
var res = this.head.value
this.head = this.head.next
if (this.head) {
this.head.prev = null
} else {
this.tail = null
}
this.length--
return res
}
Yallist.prototype.forEach = function (fn, thisp) {
thisp = thisp || this
for (var walker = this.head, i = 0; walker !== null; i++) {
fn.call(thisp, walker.value, i, this)
walker = walker.next
}
}
Yallist.prototype.forEachReverse = function (fn, thisp) {
thisp = thisp || this
for (var walker = this.tail, i = this.length - 1; walker !== null; i--) {
fn.call(thisp, walker.value, i, this)
walker = walker.prev
}
}
Yallist.prototype.get = function (n) {
for (var i = 0, walker = this.head; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.next
}
if (i === n && walker !== null) {
return walker.value
}
}
Yallist.prototype.getReverse = function (n) {
for (var i = 0, walker = this.tail; walker !== null && i < n; i++) {
// abort out of the list early if we hit a cycle
walker = walker.prev
}
if (i === n && walker !== null) {
return walker.value
}
}
Yallist.prototype.map = function (fn, thisp) {
thisp = thisp || this
var res = new Yallist()
for (var walker = this.head; walker !== null;) {
res.push(fn.call(thisp, walker.value, this))
walker = walker.next
}
return res
}
Yallist.prototype.mapReverse = function (fn, thisp) {
thisp = thisp || this
var res = new Yallist()
for (var walker = this.tail; walker !== null;) {
res.push(fn.call(thisp, walker.value, this))
walker = walker.prev
}
return res
}
Yallist.prototype.reduce = function (fn, initial) {
var acc
var walker = this.head
if (arguments.length > 1) {
acc = initial
} else if (this.head) {
walker = this.head.next
acc = this.head.value
} else {
throw new TypeError('Reduce of empty list with no initial value')
}
for (var i = 0; walker !== null; i++) {
acc = fn(acc, walker.value, i)
walker = walker.next
}
return acc
}
Yallist.prototype.reduceReverse = function (fn, initial) {
var acc
var walker = this.tail
if (arguments.length > 1) {
acc = initial
} else if (this.tail) {
walker = this.tail.prev
acc = this.tail.value
} else {
throw new TypeError('Reduce of empty list with no initial value')
}
for (var i = this.length - 1; walker !== null; i--) {
acc = fn(acc, walker.value, i)
walker = walker.prev
}
return acc
}
Yallist.prototype.toArray = function () {
var arr = new Array(this.length)
for (var i = 0, walker = this.head; walker !== null; i++) {
arr[i] = walker.value
walker = walker.next
}
return arr
}
Yallist.prototype.toArrayReverse = function () {
var arr = new Array(this.length)
for (var i = 0, walker = this.tail; walker !== null; i++) {
arr[i] = walker.value
walker = walker.prev
}
return arr
}
Yallist.prototype.slice = function (from, to) {
to = to || this.length
if (to < 0) {
to += this.length
}
from = from || 0
if (from < 0) {
from += this.length
}
var ret = new Yallist()
if (to < from || to < 0) {
return ret
}
if (from < 0) {
from = 0
}
if (to > this.length) {
to = this.length
}
for (var i = 0, walker = this.head; walker !== null && i < from; i++) {
walker = walker.next
}
for (; walker !== null && i < to; i++, walker = walker.next) {
ret.push(walker.value)
}
return ret
}
Yallist.prototype.sliceReverse = function (from, to) {
to = to || this.length
if (to < 0) {
to += this.length
}
from = from || 0
if (from < 0) {
from += this.length
}
var ret = new Yallist()
if (to < from || to < 0) {
return ret
}
if (from < 0) {
from = 0
}
if (to > this.length) {
to = this.length
}
for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) {
walker = walker.prev
}
for (; walker !== null && i > from; i--, walker = walker.prev) {
ret.push(walker.value)
}
return ret
}
Yallist.prototype.splice = function (start, deleteCount, ...nodes) {
if (start > this.length) {
start = this.length - 1
}
if (start < 0) {
start = this.length + start;
}
for (var i = 0, walker = this.head; walker !== null && i < start; i++) {
walker = walker.next
}
var ret = []
for (var i = 0; walker && i < deleteCount; i++) {
ret.push(walker.value)
walker = this.removeNode(walker)
}
if (walker === null) {
walker = this.tail
}
if (walker !== this.head && walker !== this.tail) {
walker = walker.prev
}
for (var i = 0; i < nodes.length; i++) {
walker = insert(this, walker, nodes[i])
}
return ret;
}
Yallist.prototype.reverse = function () {
var head = this.head
var tail = this.tail
for (var walker = head; walker !== null; walker = walker.prev) {
var p = walker.prev
walker.prev = walker.next
walker.next = p
}
this.head = tail
this.tail = head
return this
}
function insert (self, node, value) {
var inserted = node === self.head ?
new Node(value, null, node, self) :
new Node(value, node, node.next, self)
if (inserted.next === null) {
self.tail = inserted
}
if (inserted.prev === null) {
self.head = inserted
}
self.length++
return inserted
}
function push (self, item) {
self.tail = new Node(item, self.tail, null, self)
if (!self.head) {
self.head = self.tail
}
self.length++
}
function unshift (self, item) {
self.head = new Node(item, null, self.head, self)
if (!self.tail) {
self.tail = self.head
}
self.length++
}
function Node (value, prev, next, list) {
if (!(this instanceof Node)) {
return new Node(value, prev, next, list)
}
this.list = list
this.value = value
if (prev) {
prev.next = this
this.prev = prev
} else {
this.prev = null
}
if (next) {
next.prev = this
this.next = next
} else {
this.next = null
}
}
try {
// add if support for Symbol.iterator is present
require('./iterator.js')(Yallist)
} catch (er) {}

View File

@ -1,6 +1,6 @@
{
"name": "css-loader",
"version": "6.7.2",
"version": "3.6.0",
"description": "css loader module for webpack",
"license": "MIT",
"repository": "webpack-contrib/css-loader",
@ -13,7 +13,7 @@
},
"main": "dist/cjs.js",
"engines": {
"node": ">= 12.13.0"
"node": ">= 8.9.0"
},
"scripts": {
"start": "npm run build -- -w",
@ -23,7 +23,7 @@
"build": "cross-env NODE_ENV=production babel src -d dist --copy-files",
"postbuild": "npm run validate:runtime",
"commitlint": "commitlint --from=master",
"security": "npm audit --production",
"security": "npm audit",
"lint:prettier": "prettier --list-different .",
"lint:js": "eslint --cache .",
"lint": "npm-run-all -l -p \"lint:**\"",
@ -32,62 +32,62 @@
"test:coverage": "npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage",
"pretest": "npm run lint",
"test": "npm run test:coverage",
"prepare": "husky install && npm run build",
"release": "standard-version"
"prepare": "npm run build",
"release": "standard-version",
"defaults": "webpack-defaults"
},
"files": [
"dist"
],
"peerDependencies": {
"webpack": "^5.0.0"
"webpack": "^4.0.0 || ^5.0.0"
},
"dependencies": {
"icss-utils": "^5.1.0",
"postcss": "^8.4.18",
"postcss-modules-extract-imports": "^3.0.0",
"postcss-modules-local-by-default": "^4.0.0",
"postcss-modules-scope": "^3.0.0",
"postcss-modules-values": "^4.0.0",
"postcss-value-parser": "^4.2.0",
"semver": "^7.3.8"
"camelcase": "^5.3.1",
"cssesc": "^3.0.0",
"icss-utils": "^4.1.1",
"loader-utils": "^1.2.3",
"normalize-path": "^3.0.0",
"postcss": "^7.0.32",
"postcss-modules-extract-imports": "^2.0.0",
"postcss-modules-local-by-default": "^3.0.2",
"postcss-modules-scope": "^2.2.0",
"postcss-modules-values": "^3.0.0",
"postcss-value-parser": "^4.1.0",
"schema-utils": "^2.7.0",
"semver": "^6.3.0"
},
"devDependencies": {
"@babel/cli": "^7.19.3",
"@babel/core": "^7.19.6",
"@babel/preset-env": "^7.19.4",
"@commitlint/cli": "^16.3.0",
"@commitlint/config-conventional": "^16.2.4",
"@babel/cli": "^7.10.1",
"@babel/core": "^7.10.2",
"@babel/preset-env": "^7.10.2",
"@commitlint/cli": "^8.3.5",
"@commitlint/config-conventional": "^8.3.4",
"@webpack-contrib/defaults": "^6.3.0",
"@webpack-contrib/eslint-config-webpack": "^3.0.0",
"babel-jest": "^28.1.3",
"cross-env": "^7.0.3",
"del": "^6.1.1",
"del-cli": "^4.0.1",
"es-check": "^7.0.1",
"eslint": "^8.26.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.26.0",
"file-loader": "^6.2.0",
"husky": "^7.0.1",
"jest": "^28.1.3",
"jest-environment-jsdom": "^28.1.3",
"less": "^4.1.3",
"less-loader": "^10.0.1",
"lint-staged": "^12.5.0",
"memfs": "^3.4.9",
"mini-css-extract-plugin": "^2.6.1",
"babel-jest": "^25.5.1",
"cross-env": "^7.0.2",
"del": "^5.1.0",
"del-cli": "^3.0.1",
"es-check": "^5.1.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-import": "^2.21.2",
"file-loader": "^6.0.0",
"husky": "^4.2.5",
"jest": "^25.5.4",
"lint-staged": "^10.2.10",
"memfs": "^3.2.0",
"npm-run-all": "^4.1.5",
"postcss-loader": "^6.2.1",
"postcss-preset-env": "^7.8.2",
"prettier": "^2.7.1",
"sass": "^1.55.0",
"sass-loader": "^12.6.0",
"standard-version": "^9.5.0",
"postcss-loader": "^3.0.0",
"postcss-preset-env": "^6.7.0",
"prettier": "^2.0.5",
"sass": "^1.26.8",
"sass-loader": "^8.0.2",
"standard-version": "^8.0.0",
"strip-ansi": "^6.0.0",
"style-loader": "^3.1.0",
"stylus": "^0.56.0",
"stylus-loader": "^6.1.0",
"url-loader": "^4.1.1",
"webpack": "^5.74.0"
"url-loader": "^4.1.0",
"webpack": "^4.43.0"
},
"keywords": [
"webpack",

View File

@ -1,30 +0,0 @@
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [5.1.0] - 2020-11-19
### Features
- feat: support at-rule versions of `import`/`export`
## [5.0.0] - 2020-10-12
### BREAKING CHANGE
- minimum supported `postcss` version is `^8.1.0`
### Fixes
- minimum supported `Node.js` version is `^10 || ^12 || >= 14`
- compatibility with PostCSS 8
## [5.0.0-rc.0] - 2020-09-21
### BREAKING CHANGE
- minimum supported `Node.js` version is `>= 10.13.0 || >= 12.13.0 || >= 14`
- minimum supported `postcss` version is `^8.0.0`
- `postcss` was moved to `peerDependencies`, you need to install `postcss` in your project before use the plugin
- you need to pass `postcss` API to using `createICSSRules` (third argument)

View File

@ -26,9 +26,9 @@ A symbol is a string of alphanumeric, `-` or `_` characters. A replacement can b
- In the value of a declaration, i.e. `color: my_symbol;` or `box-shadow: 0 0 blur spread shadow-color`
- In a media expression i.e. `@media small {}` or `@media screen and not-large {}`
## extractICSS(css, removeRules = true, mode = 'auto')
## extractICSS(css, removeRules = true)
Extracts and remove (if removeRules is equal true) from PostCSS tree `:import`, `@icss-import`, `:export` and `@icss-export` statements.
Extracts and remove (if removeRules is equal true) from PostCSS tree `:import` and `:export` statements.
```js
import postcss from "postcss";
@ -58,10 +58,7 @@ extractICSS(css);
*/
```
By default both the pseudo and at-rule form of the import and export statements
will be removed. Pass the `mode` option to limit to only one type.
## createICSSRules(icssImports, icssExports, mode = 'rule')
## createICSSRules(icssImports, icssExports)
Converts icss imports and exports definitions to postcss ast
@ -69,22 +66,15 @@ Converts icss imports and exports definitions to postcss ast
createICSSRules(
{
colors: {
a: "b",
},
a: "b"
}
},
{
c: "d",
},
// Need pass `rule` and `decl` from postcss
// Please look at `Step 4` https://evilmartians.com/chronicles/postcss-8-plugin-migration
postcss
c: "d"
}
);
```
By default it will create pseudo selector rules (`:import` and `:export`). Pass
`at-rule` for `mode` to instead generate `@icss-import` and `@icss-export`, which
may be more resilient to post processing by other tools.
## License
ISC

View File

@ -0,0 +1,65 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _postcss = _interopRequireDefault(require("postcss"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const createImports = imports => {
return Object.keys(imports).map(path => {
const aliases = imports[path];
const declarations = Object.keys(aliases).map(key => _postcss.default.decl({
prop: key,
value: aliases[key],
raws: {
before: "\n "
}
}));
const hasDeclarations = declarations.length > 0;
const rule = _postcss.default.rule({
selector: `:import('${path}')`,
raws: {
after: hasDeclarations ? "\n" : ""
}
});
if (hasDeclarations) {
rule.append(declarations);
}
return rule;
});
};
const createExports = exports => {
const declarations = Object.keys(exports).map(key => _postcss.default.decl({
prop: key,
value: exports[key],
raws: {
before: "\n "
}
}));
if (declarations.length === 0) {
return [];
}
const rule = _postcss.default.rule({
selector: `:export`,
raws: {
after: "\n"
}
}).append(declarations);
return [rule];
};
const createICSSRules = (imports, exports) => [...createImports(imports), ...createExports(exports)];
var _default = createICSSRules;
exports.default = _default;

View File

@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const importPattern = /^:import\(("[^"]*"|'[^']*'|[^"']+)\)$/;
const getDeclsObject = rule => {
const object = {};
rule.walkDecls(decl => {
const before = decl.raws.before ? decl.raws.before.trim() : "";
object[before + decl.prop] = decl.value;
});
return object;
};
const extractICSS = (css, removeRules = true) => {
const icssImports = {};
const icssExports = {};
css.each(node => {
if (node.type === "rule") {
if (node.selector.slice(0, 7) === ":import") {
const matches = importPattern.exec(node.selector);
if (matches) {
const path = matches[1].replace(/'|"/g, "");
icssImports[path] = Object.assign(icssImports[path] || {}, getDeclsObject(node));
if (removeRules) {
node.remove();
}
}
}
if (node.selector === ":export") {
Object.assign(icssExports, getDeclsObject(node));
if (removeRules) {
node.remove();
}
}
}
});
return {
icssImports,
icssExports
};
};
var _default = extractICSS;
exports.default = _default;

View File

@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "replaceValueSymbols", {
enumerable: true,
get: function get() {
return _replaceValueSymbols.default;
}
});
Object.defineProperty(exports, "replaceSymbols", {
enumerable: true,
get: function get() {
return _replaceSymbols.default;
}
});
Object.defineProperty(exports, "extractICSS", {
enumerable: true,
get: function get() {
return _extractICSS.default;
}
});
Object.defineProperty(exports, "createICSSRules", {
enumerable: true,
get: function get() {
return _createICSSRules.default;
}
});
var _replaceValueSymbols = _interopRequireDefault(require("./replaceValueSymbols.js"));
var _replaceSymbols = _interopRequireDefault(require("./replaceSymbols.js"));
var _extractICSS = _interopRequireDefault(require("./extractICSS.js"));
var _createICSSRules = _interopRequireDefault(require("./createICSSRules.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

View File

@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _replaceValueSymbols = _interopRequireDefault(require("./replaceValueSymbols.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const replaceSymbols = (css, replacements) => {
css.walk(node => {
if (node.type === "decl" && node.value) {
node.value = (0, _replaceValueSymbols.default)(node.value.toString(), replacements);
} else if (node.type === "rule" && node.selector) {
node.selector = (0, _replaceValueSymbols.default)(node.selector.toString(), replacements);
} else if (node.type === "atrule" && node.params) {
node.params = (0, _replaceValueSymbols.default)(node.params.toString(), replacements);
}
});
};
var _default = replaceSymbols;
exports.default = _default;

View File

@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
const matchValueName = /[$]?[\w-]+/g;
const replaceValueSymbols = (value, replacements) => {
let matches;
while (matches = matchValueName.exec(value)) {
const replacement = replacements[matches[0]];
if (replacement) {
value = value.slice(0, matches.index) + replacement + value.slice(matchValueName.lastIndex);
matchValueName.lastIndex -= matches[0].length - replacement.length;
}
}
return value;
};
var _default = replaceValueSymbols;
exports.default = _default;

View File

@ -1,24 +1,56 @@
{
"name": "icss-utils",
"version": "5.1.0",
"version": "4.1.1",
"description": "ICSS utils for postcss ast",
"main": "src/index.js",
"main": "lib/index.js",
"engines": {
"node": "^10 || ^12 || >= 14"
"node": ">= 6"
},
"files": [
"src"
"lib"
],
"scripts": {
"prettier": "prettier -l --ignore-path .gitignore . \"!test/test-cases\"",
"eslint": "eslint --ignore-path .gitignore .",
"lint": "yarn eslint && yarn prettier",
"lint": "eslint . --ignore-path .gitignore",
"build": "babel --out-dir lib src",
"pretest": "npm run lint",
"test": "npm run test:only",
"test:only": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage --collectCoverageFrom=\"src/**/*\"",
"pretest": "yarn lint",
"test": "yarn test:coverage",
"prepublishOnly": "yarn test"
"prepublish": "yarn test && yarn run build"
},
"babel": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"node": 6
}
}
]
]
},
"eslintConfig": {
"parser": "babel-eslint",
"parserOptions": {
"sourceType": "module"
},
"env": {
"es6": true,
"jest": true
},
"extends": "eslint:recommended"
},
"lint-staged": {
"*.js": [
"prettier --write",
"eslint",
"git add"
]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"repository": {
"type": "git",
@ -36,17 +68,19 @@
"url": "https://github.com/css-modules/icss-utils/issues"
},
"homepage": "https://github.com/css-modules/icss-utils#readme",
"devDependencies": {
"coveralls": "^3.1.0",
"eslint": "^7.9.0",
"eslint-config-prettier": "^6.12.0",
"husky": "^4.3.0",
"jest": "^26.4.2",
"lint-staged": "^10.4.0",
"postcss": "^8.1.0",
"prettier": "^2.1.2"
"dependencies": {
"postcss": "^7.0.14"
},
"peerDependencies": {
"postcss": "^8.1.0"
"devDependencies": {
"@babel/cli": "^7.1.0",
"@babel/core": "^7.1.0",
"@babel/preset-env": "^7.1.0",
"babel-eslint": "^10.0.1",
"babel-jest": "^24.1.0",
"eslint": "^5.14.1",
"husky": "^1.3.1",
"jest": "^24.1.0",
"lint-staged": "^8.1.4",
"prettier": "^1.16.4"
}
}

View File

@ -1,67 +0,0 @@
const createImports = (imports, postcss, mode = "rule") => {
return Object.keys(imports).map((path) => {
const aliases = imports[path];
const declarations = Object.keys(aliases).map((key) =>
postcss.decl({
prop: key,
value: aliases[key],
raws: { before: "\n " },
})
);
const hasDeclarations = declarations.length > 0;
const rule =
mode === "rule"
? postcss.rule({
selector: `:import('${path}')`,
raws: { after: hasDeclarations ? "\n" : "" },
})
: postcss.atRule({
name: "icss-import",
params: `'${path}'`,
raws: { after: hasDeclarations ? "\n" : "" },
});
if (hasDeclarations) {
rule.append(declarations);
}
return rule;
});
};
const createExports = (exports, postcss, mode = "rule") => {
const declarations = Object.keys(exports).map((key) =>
postcss.decl({
prop: key,
value: exports[key],
raws: { before: "\n " },
})
);
if (declarations.length === 0) {
return [];
}
const rule =
mode === "rule"
? postcss.rule({
selector: `:export`,
raws: { after: "\n" },
})
: postcss.atRule({
name: "icss-export",
raws: { after: "\n" },
});
rule.append(declarations);
return [rule];
};
const createICSSRules = (imports, exports, postcss, mode) => [
...createImports(imports, postcss, mode),
...createExports(exports, postcss, mode),
];
module.exports = createICSSRules;

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