Bump the npm group with 4 updates (#2419)

* Bump the npm group with 4 updates

Bumps the npm group with 4 updates: [adm-zip](https://github.com/cthackers/adm-zip), [@eslint/js](https://github.com/eslint/eslint/tree/HEAD/packages/js), [@typescript-eslint/eslint-plugin](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/eslint-plugin) and [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser).


Updates `adm-zip` from 0.5.14 to 0.5.15
- [Release notes](https://github.com/cthackers/adm-zip/releases)
- [Changelog](https://github.com/cthackers/adm-zip/blob/master/history.md)
- [Commits](https://github.com/cthackers/adm-zip/compare/v0.5.14...v0.5.15)

Updates `@eslint/js` from 9.8.0 to 9.9.0
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/commits/v9.9.0/packages/js)

Updates `@typescript-eslint/eslint-plugin` from 8.0.1 to 8.1.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.1.0/packages/eslint-plugin)

Updates `@typescript-eslint/parser` from 8.0.1 to 8.1.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.1.0/packages/parser)

---
updated-dependencies:
- dependency-name: adm-zip
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm
- dependency-name: "@eslint/js"
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm
- dependency-name: "@typescript-eslint/eslint-plugin"
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm
- dependency-name: "@typescript-eslint/parser"
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm
...

Signed-off-by: dependabot[bot] <support@github.com>

* Update checked-in dependencies

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
dependabot[bot] 2024-08-12 11:04:43 -07:00 committed by GitHub
parent 25ad3c8e40
commit d620faa0b4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
103 changed files with 1631 additions and 740 deletions

95
node_modules/.package-lock.json generated vendored
View file

@ -455,9 +455,9 @@
} }
}, },
"node_modules/@eslint/js": { "node_modules/@eslint/js": {
"version": "9.8.0", "version": "9.9.0",
"resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.8.0.tgz", "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.9.0.tgz",
"integrity": "sha512-MfluB7EUfxXtv3i/++oh89uzAr4PDI4nn201hsp+qaXqsjAWzinlZEHEfPgAX4doIlKvPG/i0A9dpKxOLII8yA==", "integrity": "sha512-hhetes6ZHP3BlXLxmd8K2SNgkhNSi+UcecbnwWKwpP7kyi/uC75DJ1lOOBO3xrC4jyojtGE3YxKZPHfk4yrgug==",
"dev": true, "dev": true,
"engines": { "engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0" "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@ -916,16 +916,16 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@typescript-eslint/eslint-plugin": { "node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.0.1", "version": "8.1.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.0.1.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.1.0.tgz",
"integrity": "sha512-5g3Y7GDFsJAnY4Yhvk8sZtFfV6YNF2caLzjrRPUBzewjPCaj0yokePB4LJSobyCzGMzjZZYFbwuzbfDHlimXbQ==", "integrity": "sha512-LlNBaHFCEBPHyD4pZXb35mzjGkuGKXU5eeCA1SxvHfiRES0E82dOounfVpL4DCqYvJEKab0bZIA0gCRpdLKkCw==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"@eslint-community/regexpp": "^4.10.0", "@eslint-community/regexpp": "^4.10.0",
"@typescript-eslint/scope-manager": "8.0.1", "@typescript-eslint/scope-manager": "8.1.0",
"@typescript-eslint/type-utils": "8.0.1", "@typescript-eslint/type-utils": "8.1.0",
"@typescript-eslint/utils": "8.0.1", "@typescript-eslint/utils": "8.1.0",
"@typescript-eslint/visitor-keys": "8.0.1", "@typescript-eslint/visitor-keys": "8.1.0",
"graphemer": "^1.4.0", "graphemer": "^1.4.0",
"ignore": "^5.3.1", "ignore": "^5.3.1",
"natural-compare": "^1.4.0", "natural-compare": "^1.4.0",
@ -949,15 +949,15 @@
} }
}, },
"node_modules/@typescript-eslint/parser": { "node_modules/@typescript-eslint/parser": {
"version": "8.0.1", "version": "8.1.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.0.1.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.1.0.tgz",
"integrity": "sha512-5IgYJ9EO/12pOUwiBKFkpU7rS3IU21mtXzB81TNwq2xEybcmAZrE9qwDtsb5uQd9aVO9o0fdabFyAmKveXyujg==", "integrity": "sha512-U7iTAtGgJk6DPX9wIWPPOlt1gO57097G06gIcl0N0EEnNw8RGD62c+2/DiP/zL7KrkqnnqF7gtFGR7YgzPllTA==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.0.1", "@typescript-eslint/scope-manager": "8.1.0",
"@typescript-eslint/types": "8.0.1", "@typescript-eslint/types": "8.1.0",
"@typescript-eslint/typescript-estree": "8.0.1", "@typescript-eslint/typescript-estree": "8.1.0",
"@typescript-eslint/visitor-keys": "8.0.1", "@typescript-eslint/visitor-keys": "8.1.0",
"debug": "^4.3.4" "debug": "^4.3.4"
}, },
"engines": { "engines": {
@ -977,13 +977,13 @@
} }
}, },
"node_modules/@typescript-eslint/scope-manager": { "node_modules/@typescript-eslint/scope-manager": {
"version": "8.0.1", "version": "8.1.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.0.1.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.1.0.tgz",
"integrity": "sha512-NpixInP5dm7uukMiRyiHjRKkom5RIFA4dfiHvalanD2cF0CLUuQqxfg8PtEUo9yqJI2bBhF+pcSafqnG3UBnRQ==", "integrity": "sha512-DsuOZQji687sQUjm4N6c9xABJa7fjvfIdjqpSIIVOgaENf2jFXiM9hIBZOL3hb6DHK9Nvd2d7zZnoMLf9e0OtQ==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.0.1", "@typescript-eslint/types": "8.1.0",
"@typescript-eslint/visitor-keys": "8.0.1" "@typescript-eslint/visitor-keys": "8.1.0"
}, },
"engines": { "engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0" "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@ -994,13 +994,13 @@
} }
}, },
"node_modules/@typescript-eslint/type-utils": { "node_modules/@typescript-eslint/type-utils": {
"version": "8.0.1", "version": "8.1.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.0.1.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.1.0.tgz",
"integrity": "sha512-+/UT25MWvXeDX9YaHv1IS6KI1fiuTto43WprE7pgSMswHbn1Jm9GEM4Txp+X74ifOWV8emu2AWcbLhpJAvD5Ng==", "integrity": "sha512-oLYvTxljVvsMnldfl6jIKxTaU7ok7km0KDrwOt1RHYu6nxlhN3TIx8k5Q52L6wR33nOwDgM7VwW1fT1qMNfFIA==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"@typescript-eslint/typescript-estree": "8.0.1", "@typescript-eslint/typescript-estree": "8.1.0",
"@typescript-eslint/utils": "8.0.1", "@typescript-eslint/utils": "8.1.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"ts-api-utils": "^1.3.0" "ts-api-utils": "^1.3.0"
}, },
@ -1018,9 +1018,9 @@
} }
}, },
"node_modules/@typescript-eslint/types": { "node_modules/@typescript-eslint/types": {
"version": "8.0.1", "version": "8.1.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.0.1.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.1.0.tgz",
"integrity": "sha512-PpqTVT3yCA/bIgJ12czBuE3iBlM3g4inRSC5J0QOdQFAn07TYrYEQBBKgXH1lQpglup+Zy6c1fxuwTk4MTNKIw==", "integrity": "sha512-q2/Bxa0gMOu/2/AKALI0tCKbG2zppccnRIRCW6BaaTlRVaPKft4oVYPp7WOPpcnsgbr0qROAVCVKCvIQ0tbWog==",
"dev": true, "dev": true,
"engines": { "engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0" "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@ -1031,13 +1031,13 @@
} }
}, },
"node_modules/@typescript-eslint/typescript-estree": { "node_modules/@typescript-eslint/typescript-estree": {
"version": "8.0.1", "version": "8.1.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.0.1.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.1.0.tgz",
"integrity": "sha512-8V9hriRvZQXPWU3bbiUV4Epo7EvgM6RTs+sUmxp5G//dBGy402S7Fx0W0QkB2fb4obCF8SInoUzvTYtc3bkb5w==", "integrity": "sha512-NTHhmufocEkMiAord/g++gWKb0Fr34e9AExBRdqgWdVBaKoei2dIyYKD9Q0jBnvfbEA5zaf8plUFMUH6kQ0vGg==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.0.1", "@typescript-eslint/types": "8.1.0",
"@typescript-eslint/visitor-keys": "8.0.1", "@typescript-eslint/visitor-keys": "8.1.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"globby": "^11.1.0", "globby": "^11.1.0",
"is-glob": "^4.0.3", "is-glob": "^4.0.3",
@ -1083,15 +1083,15 @@
} }
}, },
"node_modules/@typescript-eslint/utils": { "node_modules/@typescript-eslint/utils": {
"version": "8.0.1", "version": "8.1.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.0.1.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.1.0.tgz",
"integrity": "sha512-CBFR0G0sCt0+fzfnKaciu9IBsKvEKYwN9UZ+eeogK1fYHg4Qxk1yf/wLQkLXlq8wbU2dFlgAesxt8Gi76E8RTA==", "integrity": "sha512-ypRueFNKTIFwqPeJBfeIpxZ895PQhNyH4YID6js0UoBImWYoSjBsahUn9KMiJXh94uOjVBgHD9AmkyPsPnFwJA==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.4.0", "@eslint-community/eslint-utils": "^4.4.0",
"@typescript-eslint/scope-manager": "8.0.1", "@typescript-eslint/scope-manager": "8.1.0",
"@typescript-eslint/types": "8.0.1", "@typescript-eslint/types": "8.1.0",
"@typescript-eslint/typescript-estree": "8.0.1" "@typescript-eslint/typescript-estree": "8.1.0"
}, },
"engines": { "engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0" "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@ -1105,12 +1105,12 @@
} }
}, },
"node_modules/@typescript-eslint/visitor-keys": { "node_modules/@typescript-eslint/visitor-keys": {
"version": "8.0.1", "version": "8.1.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.0.1.tgz", "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.1.0.tgz",
"integrity": "sha512-W5E+o0UfUcK5EgchLZsyVWqARmsM7v54/qEq6PY3YI5arkgmCzHiuk0zKSJJbm71V0xdRna4BGomkCTXz2/LkQ==", "integrity": "sha512-ba0lNI19awqZ5ZNKh6wCModMwoZs457StTebQ0q1NP58zSi2F6MOZRXwfKZy+jB78JNJ/WH8GSh2IQNzXX8Nag==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.0.1", "@typescript-eslint/types": "8.1.0",
"eslint-visitor-keys": "^3.4.3" "eslint-visitor-keys": "^3.4.3"
}, },
"engines": { "engines": {
@ -1165,8 +1165,9 @@
} }
}, },
"node_modules/adm-zip": { "node_modules/adm-zip": {
"version": "0.5.14", "version": "0.5.15",
"license": "MIT", "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.15.tgz",
"integrity": "sha512-jYPWSeOA8EFoZnucrKCNihqBjoEGQSU4HKgHYQgKNEQ0pQF9a/DYuo/+fAxY76k4qe75LUlLWpAM1QWcBMTOKw==",
"engines": { "engines": {
"node": ">=12.0" "node": ">=12.0"
} }

View file

@ -1,6 +1,6 @@
{ {
"name": "@eslint/js", "name": "@eslint/js",
"version": "9.8.0", "version": "9.9.0",
"description": "ESLint JavaScript language implementation", "description": "ESLint JavaScript language implementation",
"main": "./src/index.js", "main": "./src/index.js",
"scripts": {}, "scripts": {},

View file

@ -245,7 +245,9 @@ function getNodeType(node) {
case utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration: case utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration:
return 'constructor'; return 'constructor';
case utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition: case utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition:
case utils_1.AST_NODE_TYPES.TSPropertySignature:
return node.readonly ? 'readonly-field' : 'field'; return node.readonly ? 'readonly-field' : 'field';
case utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty:
case utils_1.AST_NODE_TYPES.AccessorProperty: case utils_1.AST_NODE_TYPES.AccessorProperty:
return 'accessor'; return 'accessor';
case utils_1.AST_NODE_TYPES.PropertyDefinition: case utils_1.AST_NODE_TYPES.PropertyDefinition:
@ -254,8 +256,6 @@ function getNodeType(node) {
: node.readonly : node.readonly
? 'readonly-field' ? 'readonly-field'
: 'field'; : 'field';
case utils_1.AST_NODE_TYPES.TSPropertySignature:
return node.readonly ? 'readonly-field' : 'field';
case utils_1.AST_NODE_TYPES.TSIndexSignature: case utils_1.AST_NODE_TYPES.TSIndexSignature:
return node.readonly ? 'readonly-signature' : 'signature'; return node.readonly ? 'readonly-signature' : 'signature';
case utils_1.AST_NODE_TYPES.StaticBlock: case utils_1.AST_NODE_TYPES.StaticBlock:
@ -286,7 +286,9 @@ function getMemberName(node, sourceCode) {
switch (node.type) { switch (node.type) {
case utils_1.AST_NODE_TYPES.TSPropertySignature: case utils_1.AST_NODE_TYPES.TSPropertySignature:
case utils_1.AST_NODE_TYPES.TSMethodSignature: case utils_1.AST_NODE_TYPES.TSMethodSignature:
case utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty:
case utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition: case utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition:
case utils_1.AST_NODE_TYPES.AccessorProperty:
case utils_1.AST_NODE_TYPES.PropertyDefinition: case utils_1.AST_NODE_TYPES.PropertyDefinition:
return getMemberRawName(node, sourceCode); return getMemberRawName(node, sourceCode);
case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition: case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition:
@ -317,7 +319,9 @@ function isMemberOptional(node) {
switch (node.type) { switch (node.type) {
case utils_1.AST_NODE_TYPES.TSPropertySignature: case utils_1.AST_NODE_TYPES.TSPropertySignature:
case utils_1.AST_NODE_TYPES.TSMethodSignature: case utils_1.AST_NODE_TYPES.TSMethodSignature:
case utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty:
case utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition: case utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition:
case utils_1.AST_NODE_TYPES.AccessorProperty:
case utils_1.AST_NODE_TYPES.PropertyDefinition: case utils_1.AST_NODE_TYPES.PropertyDefinition:
case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition: case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition:
case utils_1.AST_NODE_TYPES.MethodDefinition: case utils_1.AST_NODE_TYPES.MethodDefinition:
@ -370,7 +374,8 @@ function getRank(node, orderConfig, supportsModifiers) {
// shouldn't happen but just in case, put it on the end // shouldn't happen but just in case, put it on the end
return orderConfig.length - 1; return orderConfig.length - 1;
} }
const abstract = node.type === utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition || const abstract = node.type === utils_1.AST_NODE_TYPES.TSAbstractAccessorProperty ||
node.type === utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition ||
node.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition; node.type === utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition;
const scope = 'static' in node && node.static const scope = 'static' in node && node.static
? 'static' ? 'static'
@ -387,6 +392,7 @@ function getRank(node, orderConfig, supportsModifiers) {
(type === 'readonly-field' || (type === 'readonly-field' ||
type === 'field' || type === 'field' ||
type === 'method' || type === 'method' ||
type === 'accessor' ||
type === 'get' || type === 'get' ||
type === 'set')) { type === 'set')) {
memberGroups.push(`${accessibility}-decorated-${type}`); memberGroups.push(`${accessibility}-decorated-${type}`);

File diff suppressed because one or more lines are too long

View file

@ -165,13 +165,11 @@ exports.default = (0, util_1.createRule)({
const identifiers = getIdentifiersFromPattern(node.id); const identifiers = getIdentifiersFromPattern(node.id);
const baseModifiers = new Set(); const baseModifiers = new Set();
const parent = node.parent; const parent = node.parent;
if (parent.type === utils_1.AST_NODE_TYPES.VariableDeclaration) { if (parent.kind === 'const') {
if (parent.kind === 'const') { baseModifiers.add(naming_convention_utils_1.Modifiers.const);
baseModifiers.add(naming_convention_utils_1.Modifiers.const); }
} if (isGlobal(context.sourceCode.getScope(node))) {
if (isGlobal(context.sourceCode.getScope(node))) { baseModifiers.add(naming_convention_utils_1.Modifiers.global);
baseModifiers.add(naming_convention_utils_1.Modifiers.global);
}
} }
identifiers.forEach(id => { identifiers.forEach(id => {
const modifiers = new Set(baseModifiers); const modifiers = new Set(baseModifiers);

File diff suppressed because one or more lines are too long

View file

@ -137,6 +137,10 @@ exports.default = (0, util_1.createRule)({
]; ];
}, },
}, },
{
messageId: 'floatingFixAwait',
fix: (fixer) => addAwait(fixer, expression, node),
},
], ],
}); });
} }
@ -149,20 +153,7 @@ exports.default = (0, util_1.createRule)({
suggest: [ suggest: [
{ {
messageId: 'floatingFixAwait', messageId: 'floatingFixAwait',
fix(fixer) { fix: (fixer) => addAwait(fixer, expression, node),
if (expression.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
expression.operator === 'void') {
return fixer.replaceTextRange([expression.range[0], expression.range[0] + 4], 'await');
}
const tsNode = services.esTreeNodeToTSNodeMap.get(node.expression);
if (isHigherPrecedenceThanUnary(tsNode)) {
return fixer.insertTextBefore(node, 'await ');
}
return [
fixer.insertTextBefore(node, 'await ('),
fixer.insertTextAfterRange([expression.range[1], expression.range[1]], ')'),
];
},
}, },
], ],
}); });
@ -170,6 +161,20 @@ exports.default = (0, util_1.createRule)({
} }
}, },
}; };
function addAwait(fixer, expression, node) {
if (expression.type === utils_1.AST_NODE_TYPES.UnaryExpression &&
expression.operator === 'void') {
return fixer.replaceTextRange([expression.range[0], expression.range[0] + 4], 'await');
}
const tsNode = services.esTreeNodeToTSNodeMap.get(node.expression);
if (isHigherPrecedenceThanUnary(tsNode)) {
return fixer.insertTextBefore(node, 'await ');
}
return [
fixer.insertTextBefore(node, 'await ('),
fixer.insertTextAfterRange([expression.range[1], expression.range[1]], ')'),
];
}
function isKnownSafePromiseReturn(node) { function isKnownSafePromiseReturn(node) {
if (node.type !== utils_1.AST_NODE_TYPES.CallExpression) { if (node.type !== utils_1.AST_NODE_TYPES.CallExpression) {
return false; return false;

File diff suppressed because one or more lines are too long

View file

@ -36,6 +36,7 @@ function parseChecksVoidReturn(checksVoidReturn) {
return { return {
arguments: true, arguments: true,
attributes: true, attributes: true,
inheritedMethods: true,
properties: true, properties: true,
returns: true, returns: true,
variables: true, variables: true,
@ -44,6 +45,7 @@ function parseChecksVoidReturn(checksVoidReturn) {
return { return {
arguments: checksVoidReturn.arguments ?? true, arguments: checksVoidReturn.arguments ?? true,
attributes: checksVoidReturn.attributes ?? true, attributes: checksVoidReturn.attributes ?? true,
inheritedMethods: checksVoidReturn.inheritedMethods ?? true,
properties: checksVoidReturn.properties ?? true, properties: checksVoidReturn.properties ?? true,
returns: checksVoidReturn.returns ?? true, returns: checksVoidReturn.returns ?? true,
variables: checksVoidReturn.variables ?? true, variables: checksVoidReturn.variables ?? true,
@ -60,10 +62,11 @@ exports.default = (0, util_1.createRule)({
}, },
messages: { messages: {
voidReturnArgument: 'Promise returned in function argument where a void return was expected.', voidReturnArgument: 'Promise returned in function argument where a void return was expected.',
voidReturnVariable: 'Promise-returning function provided to variable where a void return was expected.', voidReturnAttribute: 'Promise-returning function provided to attribute where a void return was expected.',
voidReturnInheritedMethod: "Promise-returning method provided where a void return was expected by extended/implemented type '{{ heritageTypeName }}'.",
voidReturnProperty: 'Promise-returning function provided to property where a void return was expected.', voidReturnProperty: 'Promise-returning function provided to property where a void return was expected.',
voidReturnReturnValue: 'Promise-returning function provided to return value where a void return was expected.', voidReturnReturnValue: 'Promise-returning function provided to return value where a void return was expected.',
voidReturnAttribute: 'Promise-returning function provided to attribute where a void return was expected.', voidReturnVariable: 'Promise-returning function provided to variable where a void return was expected.',
conditional: 'Expected non-Promise value in a boolean conditional.', conditional: 'Expected non-Promise value in a boolean conditional.',
spread: 'Expected a non-Promise value to be spreaded in an object.', spread: 'Expected a non-Promise value to be spreaded in an object.',
}, },
@ -83,6 +86,7 @@ exports.default = (0, util_1.createRule)({
properties: { properties: {
arguments: { type: 'boolean' }, arguments: { type: 'boolean' },
attributes: { type: 'boolean' }, attributes: { type: 'boolean' },
inheritedMethods: { type: 'boolean' },
properties: { type: 'boolean' }, properties: { type: 'boolean' },
returns: { type: 'boolean' }, returns: { type: 'boolean' },
variables: { type: 'boolean' }, variables: { type: 'boolean' },
@ -131,6 +135,11 @@ exports.default = (0, util_1.createRule)({
...(checksVoidReturn.attributes && { ...(checksVoidReturn.attributes && {
JSXAttribute: checkJSXAttribute, JSXAttribute: checkJSXAttribute,
}), }),
...(checksVoidReturn.inheritedMethods && {
ClassDeclaration: checkClassLikeOrInterfaceNode,
ClassExpression: checkClassLikeOrInterfaceNode,
TSInterfaceDeclaration: checkClassLikeOrInterfaceNode,
}),
...(checksVoidReturn.properties && { ...(checksVoidReturn.properties && {
Property: checkProperty, Property: checkProperty,
}), }),
@ -379,6 +388,51 @@ exports.default = (0, util_1.createRule)({
}); });
} }
} }
function checkClassLikeOrInterfaceNode(node) {
const tsNode = services.esTreeNodeToTSNodeMap.get(node);
const heritageTypes = getHeritageTypes(checker, tsNode);
if (!heritageTypes?.length) {
return;
}
for (const nodeMember of tsNode.members) {
const memberName = nodeMember.name?.getText();
if (memberName === undefined) {
// Call/construct/index signatures don't have names. TS allows call signatures to mismatch,
// and construct signatures can't be async.
// TODO - Once we're able to use `checker.isTypeAssignableTo` (v8), we can check an index
// signature here against its compatible index signatures in `heritageTypes`
continue;
}
if (!returnsThenable(checker, nodeMember)) {
continue;
}
for (const heritageType of heritageTypes) {
checkHeritageTypeForMemberReturningVoid(nodeMember, heritageType, memberName);
}
}
}
/**
* Checks `heritageType` for a member named `memberName` that returns void; reports the
* 'voidReturnInheritedMethod' message if found.
* @param nodeMember Node member that returns a Promise
* @param heritageType Heritage type to check against
* @param memberName Name of the member to check for
*/
function checkHeritageTypeForMemberReturningVoid(nodeMember, heritageType, memberName) {
const heritageMember = getMemberIfExists(heritageType, memberName);
if (heritageMember === undefined) {
return;
}
const memberType = checker.getTypeOfSymbolAtLocation(heritageMember, nodeMember);
if (!isVoidReturningFunctionType(checker, nodeMember, memberType)) {
return;
}
context.report({
node: services.tsNodeToESTreeNodeMap.get(nodeMember),
messageId: 'voidReturnInheritedMethod',
data: { heritageTypeName: checker.typeToString(heritageType) },
});
}
function checkJSXAttribute(node) { function checkJSXAttribute(node) {
if (node.value == null || if (node.value == null ||
node.value.type !== utils_1.AST_NODE_TYPES.JSXExpressionContainer) { node.value.type !== utils_1.AST_NODE_TYPES.JSXExpressionContainer) {
@ -592,4 +646,17 @@ function returnsThenable(checker, node) {
.unionTypeParts(type) .unionTypeParts(type)
.some(t => anySignatureIsThenableType(checker, node, t)); .some(t => anySignatureIsThenableType(checker, node, t));
} }
function getHeritageTypes(checker, tsNode) {
return tsNode.heritageClauses
?.flatMap(clause => clause.types)
.map(typeExpression => checker.getTypeAtLocation(typeExpression));
}
/**
* @returns The member with the given name in `type`, if it exists.
*/
function getMemberIfExists(type, memberName) {
const escapedMemberName = ts.escapeLeadingUnderscores(memberName);
const symbolMemberMatch = type.getSymbol()?.members?.get(escapedMemberName);
return (symbolMemberMatch ?? tsutils.getPropertyOfType(type, escapedMemberName));
}
//# sourceMappingURL=no-misused-promises.js.map //# sourceMappingURL=no-misused-promises.js.map

File diff suppressed because one or more lines are too long

View file

@ -279,8 +279,8 @@ exports.default = (0, util_1.createRule)({
if (isInRange(node.init, location)) { if (isInRange(node.init, location)) {
return true; return true;
} }
if ((node.parent.parent?.type === utils_1.AST_NODE_TYPES.ForInStatement || if ((node.parent.parent.type === utils_1.AST_NODE_TYPES.ForInStatement ||
node.parent.parent?.type === utils_1.AST_NODE_TYPES.ForOfStatement) && node.parent.parent.type === utils_1.AST_NODE_TYPES.ForOfStatement) &&
isInRange(node.parent.parent.right, location)) { isInRange(node.parent.parent.right, location)) {
return true; return true;
} }

File diff suppressed because one or more lines are too long

View file

@ -31,12 +31,12 @@ exports.default = (0, util_1.createRule)({
defaultOptions: [], defaultOptions: [],
meta: { meta: {
docs: { docs: {
description: 'Disallow type parameters that only appear once', description: "Disallow type parameters that aren't used multiple times",
requiresTypeChecking: true, requiresTypeChecking: true,
recommended: 'strict', recommended: 'strict',
}, },
messages: { messages: {
sole: 'Type parameter {{name}} is used only once.', sole: 'Type parameter {{name}} is {{uses}} in the {{descriptor}} signature.',
}, },
schema: [], schema: [],
type: 'problem', type: 'problem',
@ -44,11 +44,38 @@ exports.default = (0, util_1.createRule)({
name: 'no-unnecessary-type-parameters', name: 'no-unnecessary-type-parameters',
create(context) { create(context) {
const parserServices = (0, util_1.getParserServices)(context); const parserServices = (0, util_1.getParserServices)(context);
function checkNode(node, descriptor) {
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node);
const checker = parserServices.program.getTypeChecker();
let counts;
for (const typeParameter of tsNode.typeParameters) {
const esTypeParameter = parserServices.tsNodeToESTreeNodeMap.get(typeParameter);
const scope = context.sourceCode.getScope(esTypeParameter);
// Quick path: if the type parameter is used multiple times in the AST,
// we don't need to dip into types to know it's repeated.
if (isTypeParameterRepeatedInAST(esTypeParameter, scope.references, node.body?.range[0] ?? node.returnType?.range[1])) {
continue;
}
// For any inferred types, we have to dip into type checking.
counts ??= countTypeParameterUsage(checker, tsNode);
const identifierCounts = counts.get(typeParameter.name);
if (!identifierCounts || identifierCounts > 2) {
continue;
}
context.report({
data: {
descriptor,
uses: identifierCounts === 1 ? 'never used' : 'used only once',
name: typeParameter.name.text,
},
node: esTypeParameter,
messageId: 'sole',
});
}
}
return { return {
[[ [[
'ArrowFunctionExpression[typeParameters]', 'ArrowFunctionExpression[typeParameters]',
'ClassDeclaration[typeParameters]',
'ClassExpression[typeParameters]',
'FunctionDeclaration[typeParameters]', 'FunctionDeclaration[typeParameters]',
'FunctionExpression[typeParameters]', 'FunctionExpression[typeParameters]',
'TSCallSignatureDeclaration[typeParameters]', 'TSCallSignatureDeclaration[typeParameters]',
@ -58,43 +85,29 @@ exports.default = (0, util_1.createRule)({
'TSFunctionType[typeParameters]', 'TSFunctionType[typeParameters]',
'TSMethodSignature[typeParameters]', 'TSMethodSignature[typeParameters]',
].join(', ')](node) { ].join(', ')](node) {
const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node); checkNode(node, 'function');
const checker = parserServices.program.getTypeChecker(); },
let counts; [[
for (const typeParameter of tsNode.typeParameters) { 'ClassDeclaration[typeParameters]',
const esTypeParameter = parserServices.tsNodeToESTreeNodeMap.get(typeParameter); 'ClassExpression[typeParameters]',
const scope = context.sourceCode.getScope(esTypeParameter); ].join(', ')](node) {
// Quick path: if the type parameter is used multiple times in the AST, checkNode(node, 'class');
// we don't need to dip into types to know it's repeated.
if (isTypeParameterRepeatedInAST(esTypeParameter, scope.references)) {
continue;
}
// For any inferred types, we have to dip into type checking.
counts ??= countTypeParameterUsage(checker, tsNode);
const identifierCounts = counts.get(typeParameter.name);
if (!identifierCounts || identifierCounts > 2) {
continue;
}
context.report({
data: {
name: typeParameter.name.text,
},
node: esTypeParameter,
messageId: 'sole',
});
}
}, },
}; };
}, },
}); });
function isTypeParameterRepeatedInAST(node, references) { function isTypeParameterRepeatedInAST(node, references, startOfBody = Infinity) {
let total = 0; let total = 0;
for (const reference of references) { for (const reference of references) {
// References inside the type parameter's definition don't count. // References inside the type parameter's definition don't count...
if (reference.identifier.range[0] < node.range[1] && if (reference.identifier.range[0] < node.range[1] &&
reference.identifier.range[1] > node.range[0]) { reference.identifier.range[1] > node.range[0]) {
continue; continue;
} }
// ...nor references that are outside the declaring signature.
if (reference.identifier.range[0] > startOfBody) {
continue;
}
// Neither do references that aren't to the same type parameter, // Neither do references that aren't to the same type parameter,
// namely value-land (non-type) identifiers of the type parameter's type, // namely value-land (non-type) identifiers of the type parameter's type,
// and references to different type parameters or values. // and references to different type parameters or values.

File diff suppressed because one or more lines are too long

View file

@ -37,9 +37,9 @@ exports.default = (0, util_1.createRule)({
requiresTypeChecking: true, requiresTypeChecking: true,
}, },
messages: { messages: {
unsafeReturn: 'Unsafe return of an {{type}} typed value.', unsafeReturn: 'Unsafe return of a value of type {{type}}.',
unsafeReturnThis: [ unsafeReturnThis: [
'Unsafe return of an `{{type}}` typed value. `this` is typed as `any`.', 'Unsafe return of a value of type `{{type}}`. `this` is typed as `any`.',
'You can try to fix this by turning on the `noImplicitThis` compiler option, or adding a `this` parameter to the function.', 'You can try to fix this by turning on the `noImplicitThis` compiler option, or adding a `this` parameter to the function.',
].join('\n'), ].join('\n'),
unsafeReturnAssignment: 'Unsafe return of type `{{sender}}` from function with return type `{{receiver}}`.', unsafeReturnAssignment: 'Unsafe return of type `{{sender}}` from function with return type `{{receiver}}`.',
@ -68,7 +68,8 @@ exports.default = (0, util_1.createRule)({
} }
function checkReturn(returnNode, reportingNode = returnNode) { function checkReturn(returnNode, reportingNode = returnNode) {
const tsNode = services.esTreeNodeToTSNodeMap.get(returnNode); const tsNode = services.esTreeNodeToTSNodeMap.get(returnNode);
const anyType = (0, util_1.isAnyOrAnyArrayTypeDiscriminated)(tsNode, checker); const type = checker.getTypeAtLocation(tsNode);
const anyType = (0, util_1.discriminateAnyType)(type, checker, services.program, tsNode);
const functionNode = getParentFunctionNode(returnNode); const functionNode = getParentFunctionNode(returnNode);
/* istanbul ignore if */ if (!functionNode) { /* istanbul ignore if */ if (!functionNode) {
return; return;
@ -87,20 +88,31 @@ exports.default = (0, util_1.createRule)({
if (!functionType) { if (!functionType) {
functionType = services.getTypeAtLocation(functionNode); functionType = services.getTypeAtLocation(functionNode);
} }
const callSignatures = tsutils.getCallSignaturesOfType(functionType);
// If there is an explicit type annotation *and* that type matches the actual // If there is an explicit type annotation *and* that type matches the actual
// function return type, we shouldn't complain (it's intentional, even if unsafe) // function return type, we shouldn't complain (it's intentional, even if unsafe)
if (functionTSNode.type) { if (functionTSNode.type) {
for (const signature of tsutils.getCallSignaturesOfType(functionType)) { for (const signature of callSignatures) {
if (returnNodeType === signature.getReturnType() || const signatureReturnType = signature.getReturnType();
(0, util_1.isTypeFlagSet)(signature.getReturnType(), ts.TypeFlags.Any | ts.TypeFlags.Unknown)) { if (returnNodeType === signatureReturnType ||
(0, util_1.isTypeFlagSet)(signatureReturnType, ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
return; return;
} }
if (functionNode.async) {
const awaitedSignatureReturnType = checker.getAwaitedType(signatureReturnType);
const awaitedReturnNodeType = checker.getAwaitedType(returnNodeType);
if (awaitedReturnNodeType === awaitedSignatureReturnType ||
(awaitedSignatureReturnType &&
(0, util_1.isTypeFlagSet)(awaitedSignatureReturnType, ts.TypeFlags.Any | ts.TypeFlags.Unknown))) {
return;
}
}
} }
} }
if (anyType !== util_1.AnyType.Safe) { if (anyType !== util_1.AnyType.Safe) {
// Allow cases when the declared return type of the function is either unknown or unknown[] // Allow cases when the declared return type of the function is either unknown or unknown[]
// and the function is returning any or any[]. // and the function is returning any or any[].
for (const signature of functionType.getCallSignatures()) { for (const signature of callSignatures) {
const functionReturnType = signature.getReturnType(); const functionReturnType = signature.getReturnType();
if (anyType === util_1.AnyType.Any && if (anyType === util_1.AnyType.Any &&
(0, util_1.isTypeUnknownType)(functionReturnType)) { (0, util_1.isTypeUnknownType)(functionReturnType)) {
@ -110,6 +122,15 @@ exports.default = (0, util_1.createRule)({
(0, util_1.isTypeUnknownArrayType)(functionReturnType, checker)) { (0, util_1.isTypeUnknownArrayType)(functionReturnType, checker)) {
return; return;
} }
const awaitedType = checker.getAwaitedType(functionReturnType);
if (awaitedType &&
anyType === util_1.AnyType.PromiseAny &&
(0, util_1.isTypeUnknownType)(awaitedType)) {
return;
}
}
if (anyType === util_1.AnyType.PromiseAny && !functionNode.async) {
return;
} }
let messageId = 'unsafeReturn'; let messageId = 'unsafeReturn';
const isErrorType = tsutils.isIntrinsicErrorType(returnNodeType); const isErrorType = tsutils.isIntrinsicErrorType(returnNodeType);
@ -130,7 +151,9 @@ exports.default = (0, util_1.createRule)({
? 'error' ? 'error'
: anyType === util_1.AnyType.Any : anyType === util_1.AnyType.Any
? '`any`' ? '`any`'
: '`any[]`', : anyType === util_1.AnyType.PromiseAny
? '`Promise<any>`'
: '`any[]`',
}, },
}); });
} }

View file

@ -1 +1 @@
{"version":3,"file":"no-unsafe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OAAO;gBACT,CAAC;gBAED,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAC;gBACpC,OAAO,OAAO,CAAC,MAAM,CAAC;oBACpB,IAAI,EAAE,aAAa;oBACnB,SAAS,EAAE,wBAAwB;oBACnC,IAAI,EAAE;wBACJ,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,MAAM,CAAC;wBACpC,QAAQ,EAAE,OAAO,CAAC,YAAY,CAAC,QAAQ,CAAC;qBACzC;iBACF,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,OAAO;YACL,eAAe,CAAC,IAAI;gBAClB,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;gBAC/B,IAAI,CAAC,QAAQ,EAAE,CAAC;oBACd,OAAO;gBACT,CAAC;gBAED,WAAW,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;YAC9B,CAAC;YACD,qDAAqD,EAAE,WAAW;SACnE,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}

View file

@ -130,8 +130,8 @@ function isInInitializer(variable, reference) {
if (isInRange(node.init, location)) { if (isInRange(node.init, location)) {
return true; return true;
} }
if ((node.parent.parent?.type === utils_1.AST_NODE_TYPES.ForInStatement || if ((node.parent.parent.type === utils_1.AST_NODE_TYPES.ForInStatement ||
node.parent.parent?.type === utils_1.AST_NODE_TYPES.ForOfStatement) && node.parent.parent.type === utils_1.AST_NODE_TYPES.ForOfStatement) &&
isInRange(node.parent.parent.right, location)) { isInRange(node.parent.parent.right, location)) {
return true; return true;
} }

File diff suppressed because one or more lines are too long

View file

@ -133,7 +133,35 @@ const analyzeOrChainOperand = (parserServices, operand, index, chain) => {
return null; return null;
} }
}; };
function getFixer(sourceCode, parserServices, operator, options, chain) { /**
* Returns the range that needs to be reported from the chain.
* @param chain The chain of logical expressions.
* @param boundary The boundary range that the range to report cannot fall outside.
* @param sourceCode The source code to get tokens.
* @returns The range to report.
*/
function getReportRange(chain, boundary, sourceCode) {
const leftNode = chain[0].node;
const rightNode = chain[chain.length - 1].node;
let leftMost = (0, util_1.nullThrows)(sourceCode.getFirstToken(leftNode), util_1.NullThrowsReasons.MissingToken('any token', leftNode.type));
let rightMost = (0, util_1.nullThrows)(sourceCode.getLastToken(rightNode), util_1.NullThrowsReasons.MissingToken('any token', rightNode.type));
while (leftMost.range[0] > boundary[0]) {
const token = sourceCode.getTokenBefore(leftMost);
if (!token || !(0, util_1.isOpeningParenToken)(token) || token.range[0] < boundary[0]) {
break;
}
leftMost = token;
}
while (rightMost.range[1] < boundary[1]) {
const token = sourceCode.getTokenAfter(rightMost);
if (!token || !(0, util_1.isClosingParenToken)(token) || token.range[1] > boundary[1]) {
break;
}
rightMost = token;
}
return [leftMost.range[0], rightMost.range[1]];
}
function getReportDescriptor(sourceCode, parserServices, node, operator, options, chain) {
const lastOperand = chain[chain.length - 1]; const lastOperand = chain[chain.length - 1];
let useSuggestionFixer; let useSuggestionFixer;
if (options.allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing === if (options.allowPotentiallyUnsafeFixesThatModifyTheReturnTypeIKnowWhatImDoing ===
@ -269,10 +297,22 @@ function getFixer(sourceCode, parserServices, operator, options, chain) {
else if (lastOperand.comparisonType === "NotBoolean" /* NullishComparisonType.NotBoolean */) { else if (lastOperand.comparisonType === "NotBoolean" /* NullishComparisonType.NotBoolean */) {
newCode = `!${newCode}`; newCode = `!${newCode}`;
} }
const fix = fixer => fixer.replaceTextRange([chain[0].node.range[0], lastOperand.node.range[1]], newCode); const reportRange = getReportRange(chain, node.range, sourceCode);
return useSuggestionFixer const fix = fixer => fixer.replaceTextRange(reportRange, newCode);
? { suggest: [{ fix, messageId: 'optionalChainSuggest' }] } return {
: { fix }; messageId: 'preferOptionalChain',
loc: {
start: sourceCode.getLocFromIndex(reportRange[0]),
end: sourceCode.getLocFromIndex(reportRange[1]),
},
...(0, util_1.getFixOrSuggest)({
useFix: !useSuggestionFixer,
suggestion: {
messageId: 'optionalChainSuggest',
fix,
},
}),
};
function flattenChainExpression(sourceCode, node) { function flattenChainExpression(sourceCode, node) {
switch (node.type) { switch (node.type) {
case utils_1.AST_NODE_TYPES.ChainExpression: case utils_1.AST_NODE_TYPES.ChainExpression:
@ -332,7 +372,7 @@ function getFixer(sourceCode, parserServices, operator, options, chain) {
} }
} }
} }
function analyzeChain(context, parserServices, options, operator, chain) { function analyzeChain(context, parserServices, options, node, operator, chain) {
// need at least 2 operands in a chain for it to be a chain // need at least 2 operands in a chain for it to be a chain
if (chain.length <= 1 || if (chain.length <= 1 ||
/* istanbul ignore next -- previous checks make this unreachable, but keep it for exhaustiveness check */ /* istanbul ignore next -- previous checks make this unreachable, but keep it for exhaustiveness check */
@ -353,14 +393,7 @@ function analyzeChain(context, parserServices, options, operator, chain) {
const maybeReportThenReset = (newChainSeed) => { const maybeReportThenReset = (newChainSeed) => {
if (subChain.length > 1) { if (subChain.length > 1) {
const subChainFlat = subChain.flat(); const subChainFlat = subChain.flat();
(0, checkNullishAndReport_1.checkNullishAndReport)(context, parserServices, options, subChainFlat.slice(0, -1).map(({ node }) => node), { (0, checkNullishAndReport_1.checkNullishAndReport)(context, parserServices, options, subChainFlat.slice(0, -1).map(({ node }) => node), getReportDescriptor(context.sourceCode, parserServices, node, operator, options, subChainFlat));
messageId: 'preferOptionalChain',
loc: {
start: subChainFlat[0].node.loc.start,
end: subChainFlat[subChainFlat.length - 1].node.loc.end,
},
...getFixer(context.sourceCode, parserServices, operator, options, subChainFlat),
});
} }
// we've reached the end of a chain of logical expressions // we've reached the end of a chain of logical expressions
// i.e. the current operand doesn't belong to the previous chain. // i.e. the current operand doesn't belong to the previous chain.

File diff suppressed because one or more lines are too long

View file

@ -156,7 +156,7 @@ exports.default = (0, util_1.createRule)({
let currentChain = []; let currentChain = [];
for (const operand of operands) { for (const operand of operands) {
if (operand.type === "Invalid" /* OperandValidity.Invalid */) { if (operand.type === "Invalid" /* OperandValidity.Invalid */) {
(0, analyzeChain_1.analyzeChain)(context, parserServices, options, node.operator, currentChain); (0, analyzeChain_1.analyzeChain)(context, parserServices, options, node, node.operator, currentChain);
currentChain = []; currentChain = [];
} }
else { else {
@ -165,7 +165,7 @@ exports.default = (0, util_1.createRule)({
} }
// make sure to check whatever's left // make sure to check whatever's left
if (currentChain.length > 0) { if (currentChain.length > 0) {
(0, analyzeChain_1.analyzeChain)(context, parserServices, options, node.operator, currentChain); (0, analyzeChain_1.analyzeChain)(context, parserServices, options, node, node.operator, currentChain);
} }
}, },
}; };

View file

@ -1 +1 @@
{"version":3,"file":"prefer-optional-chain.js","sourceRoot":"","sources":["../../src/rules/prefer-optional-chain.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,oDAA0D;AAE1D,+CAAiC;AAEjC,kCAKiB;AACjB,6EAA0E;AAC1E,+FAA4F;AAE5F,+FAG6D;AAM7D,kBAAe,IAAA,iBAAU,EAGvB;IACA,IAAI,EAAE,uBAAuB;IAC7B,IAAI,EAAE;QACJ,IAAI,EAAE,YAAY;QAClB,IAAI,EAAE;YACJ,WAAW,EACT,yHAAyH;YAC3H,WAAW,EAAE,WAAW;YACxB,oBAAoB,EAAE,IAAI;SAC3B;QACD,OAAO,EAAE,MAAM;QACf,cAAc,EAAE,IAAI;QACpB,QAAQ,EAAE;YACR,mBAAmB,EACjB,6FAA6F;YAC/F,oBAAoB,EAAE,8BAA8B;SACrD;QACD,MAAM,EAAE;YACN;gBACE,IAAI,EAAE,QAAQ;gBACd,oBAAoB,EAAE,KAAK;gBAC3B,UAAU,EAAE;oBACV,QAAQ,EAAE;wBACR,IAAI,EAAE,SAAS;wBACf,WAAW,EACT,kFAAkF;qBACrF;oBACD,YAAY,EAAE;wBACZ,IAAI,EAAE,SAAS;wBACf,WAAW,EACT,sFAAsF;qBACzF;oBACD,WAAW,EAAE;wBACX,IAAI,EAAE,SAAS;wBACf,WAAW,EACT,qFAAqF;qBACxF;oBACD,WAAW,EAAE;wBACX,IAAI,EAAE,SAAS;wBACf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,gBAAgB,CAC3B,UAAU,CAAC,KAAK,EAChB,GAAG,oBAAoB,KAAK,oBAAoB,EAAE,CACnD,CAAC;4BACJ,CAAC;yBACF;qBACF;iBACF,CAAC,CAAC;YACL,CAAC;YAED,mCAAmC,CACjC,IAAgC;gBAEhC,IAAI,YAAY,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;oBAC3B,OAAO;gBACT,CAAC;gBAED,MAAM,EAAE,QAAQ,EAAE,iBAAiB,EAAE,GAAG,IAAA,6CAAqB,EAC3D,IAAI,EACJ,cAAc,EACd,OAAO,CAAC,UAAU,EAClB,OAAO,CACR,CAAC;gBAEF,KAAK,MAAM,OAAO,IAAI,iBAAiB,EAAE,CAAC;oBACxC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;gBAC5B,CAAC;gBAED,IAAI,YAAY,GAAmB,EAAE,CAAC;gBACtC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;oBAC/B,IAAI,OAAO,CAAC,IAAI,4CAA4B,EAAE,CAAC;wBAC7C,IAAA,2BAAY,EACV,OAAO,EACP,cAAc,EACd,OAAO,EACP,IAAI,CAAC,QAAQ,EACb,YAAY,CACb,CAAC;wBACF,YAAY,GAAG,EAAE,CAAC;oBACpB,CAAC;yBAAM,CAAC;wBACN,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBAC7B,CAAC;gBACH,CAAC;gBAED,qCAAqC;gBACrC,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBAC5B,IAAA,2BAAY,EACV,OAAO,EACP,cAAc,EACd,OAAO,EACP,IAAI,CAAC,QAAQ,EACb,YAAY,CACb,CAAC;gBACJ,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"} {"version":3,"file":"prefer-optional-chain.js","sourceRoot":"","sources":["../../src/rules/prefer-optional-chain.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AACA,o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BACxC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;gBAC5B,CAAC;gBAED,IAAI,YAAY,GAAmB,EAAE,CAAC;gBACtC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;oBAC/B,IAAI,OAAO,CAAC,IAAI,4CAA4B,EAAE,CAAC;wBAC7C,IAAA,2BAAY,EACV,OAAO,EACP,cAAc,EACd,OAAO,EACP,IAAI,EACJ,IAAI,CAAC,QAAQ,EACb,YAAY,CACb,CAAC;wBACF,YAAY,GAAG,EAAE,CAAC;oBACpB,CAAC;yBAAM,CAAC;wBACN,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;oBAC7B,CAAC;gBACH,CAAC;gBAED,qCAAqC;gBACrC,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBAC5B,IAAA,2BAAY,EACV,OAAO,EACP,cAAc,EACd,OAAO,EACP,IAAI,EACJ,IAAI,CAAC,QAAQ,EACb,YAAY,CACb,CAAC;gBACJ,CAAC;YACH,CAAC;SACF,CAAC;IACJ,CAAC;CACF,CAAC,CAAC"}

View file

@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getFixOrSuggest = getFixOrSuggest;
function getFixOrSuggest({ useFix, suggestion, }) {
return useFix ? { fix: suggestion.fix } : { suggest: [suggestion] };
}
//# sourceMappingURL=getFixOrSuggest.js.map

View file

@ -0,0 +1 @@
{"version":3,"file":"getFixOrSuggest.js","sourceRoot":"","sources":["../../src/util/getFixOrSuggest.ts"],"names":[],"mappings":";;AAEA,0CAUC;AAVD,SAAgB,eAAe,CAA2B,EACxD,MAAM,EACN,UAAU,GAIX;IAGC,OAAO,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC;AACtE,CAAC"}

View file

@ -35,7 +35,7 @@ function getWrappingFixer(params) {
} }
} }
// check if we need to insert semicolon // check if we need to insert semicolon
if (/^[`([]/.exec(code) && isMissingSemicolonBefore(node, sourceCode)) { if (/^[`([]/.test(code) && isMissingSemicolonBefore(node, sourceCode)) {
code = `;${code}`; code = `;${code}`;
} }
return fixer.replaceText(node, code); return fixer.replaceText(node, code);

View file

@ -34,6 +34,7 @@ __exportStar(require("./objectIterators"), exports);
__exportStar(require("./scopeUtils"), exports); __exportStar(require("./scopeUtils"), exports);
__exportStar(require("./types"), exports); __exportStar(require("./types"), exports);
__exportStar(require("./isAssignee"), exports); __exportStar(require("./isAssignee"), exports);
__exportStar(require("./getFixOrSuggest"), exports);
// this is done for convenience - saves migrating all of the old rules // this is done for convenience - saves migrating all of the old rules
__exportStar(require("@typescript-eslint/type-utils"), exports); __exportStar(require("@typescript-eslint/type-utils"), exports);
const { applyDefault, deepMerge, isObjectNotArray, getParserServices, nullThrows, NullThrowsReasons, } = utils_1.ESLintUtils; const { applyDefault, deepMerge, isObjectNotArray, getParserServices, nullThrows, NullThrowsReasons, } = utils_1.ESLintUtils;

View file

@ -1 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/util/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,oDAAuD;AAEvD,6CAA2B;AAC3B,2DAAyC;AACzC,+CAA6B;AAC7B,uDAAqC;AACrC,0DAAwC;AACxC,yDAAuC;AACvC,oDAAkC;AAClC,2DAAyC;AACzC,sDAAoC;AACpC,qDAAmC;AACnC,gDAA8B;AAC9B,kDAAgC;AAChC,0DAAwC;AACxC,yCAAuB;AACvB,oDAAkC;AAClC,+CAA6B;AAC7B,0CAAwB;AACxB,+CAA6B;AAE7B,sEAAsE;AACtE,gEAA8C;AAC9C,MAAM,EACJ,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,EACV,iBAAiB,GAClB,GAAG,mBAAW,CAAC;AAMd,oCAAY;AACZ,8BAAS;AACT,4CAAgB;AAChB,8CAAiB;AACjB,gCAAU;AAGV,8CAAiB"} {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/util/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,oDAAuD;AAEvD,6CAA2B;AAC3B,2DAAyC;AACzC,+CAA6B;AAC7B,uDAAqC;AACrC,0DAAwC;AACxC,yDAAuC;AACvC,oDAAkC;AAClC,2DAAyC;AACzC,sDAAoC;AACpC,qDAAmC;AACnC,gDAA8B;AAC9B,kDAAgC;AAChC,0DAAwC;AACxC,yCAAuB;AACvB,oDAAkC;AAClC,+CAA6B;AAC7B,0CAAwB;AACxB,+CAA6B;AAC7B,oDAAkC;AAElC,sEAAsE;AACtE,gEAA8C;AAC9C,MAAM,EACJ,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,iBAAiB,EACjB,UAAU,EACV,iBAAiB,GAClB,GAAG,mBAAW,CAAC;AAMd,oCAAY;AACZ,8BAAS;AACT,4CAAgB;AAChB,8CAAiB;AACjB,gCAAU;AAGV,8CAAiB"}

View file

@ -1 +1 @@
{"version":3,"file":"misc.js","sourceRoot":"","sources":["../../src/util/misc.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;;;;;;;;;;;;;;;;;;;;;AAuOD,8CAAiB;AACjB,wCAAc;AAGd,0CAAe;AACf,wCAAc;AACd,oCAAY;AACZ,8DAAyB;AACzB,8CAAiB;AACjB,4CAAgB;AAChB,gEAA0B;AAC1B,4DAAwB;AAGxB,kEAA2B;AAC3B,wCAAc;AACd,sCAAa;AArPf,8DAAgE;AAEhE,oDAA0D;AAC1D,+CAAiC;AAEjC,yCAA6C;AAE7C,MAAM,qBAAqB,GAAG;IAC5B,EAAE,CAAC,SAAS,CAAC,GAAG;IAChB,EAAE,CAAC,SAAS,CAAC,IAAI;IACjB,EAAE,CAAC,SAAS,CAAC,IAAI;CACT,CAAC;AACX;;GAEG;AACH,SAAS,gBAAgB,CAAC,QAAgB;IACxC,MAAM,aAAa,GAA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C;AACJ,CAAC;AAED,SAAS,0BAA0B,CAAC,IAAoB;IACtD,OAAO,EAAE,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC;AAC7D,CAAC;AAED,SAAS,wBAAwB,CAC/B,IAAsC,EACtC,UAA+B;IAE/B,OAAO,CACL,IAAI,CAAC,MAAM,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,IAAA,0BAAe,EAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,UAAU,CAAC,CACzE,CAAC;AACJ,CAAC"}

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
The old `ban-types` rule encompassed multiple areas of functionality, and so has been split into several rules. The old `ban-types` rule encompassed multiple areas of functionality, and so has been split into several rules.

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been deprecated in favour of the [`naming-convention`](./naming-convention.mdx) rule. This rule has been deprecated in favour of the [`naming-convention`](./naming-convention.mdx) rule.

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been deprecated in favour of the [`import/no-duplicates`](https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-duplicates.md) rule. This rule has been deprecated in favour of the [`import/no-duplicates`](https://github.com/import-js/eslint-plugin-import/blob/HEAD/docs/rules/no-duplicates.md) rule.

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -37,10 +37,89 @@ If you don't want to check conditionals, you can configure the rule with `"check
Doing so prevents the rule from looking at code like `if (somePromise)`. Doing so prevents the rule from looking at code like `if (somePromise)`.
Examples of code for this rule with `checksConditionals: true`: ### `checksVoidReturn`
Likewise, if you don't want to check functions that return promises where a void return is
expected, your configuration will look like this:
```json
{
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksVoidReturn": false
}
]
}
```
You can disable selective parts of the `checksVoidReturn` option by providing an object that disables specific checks. For example, if you don't mind that passing a `() => Promise<void>` to a `() => void` parameter or JSX attribute can lead to a floating unhandled Promise:
```json
{
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksVoidReturn": {
"arguments": false,
"attributes": false
}
}
]
}
```
The following sub-options are supported:
#### `arguments`
Disables checking an asynchronous function passed as argument where the parameter type expects a function that returns `void`.
#### `attributes`
Disables checking an asynchronous function passed as a JSX attribute expected to be a function that returns `void`.
#### `inheritedMethods`
Disables checking an asynchronous method in a type that extends or implements another type expecting that method to return `void`.
:::note
For now, `no-misused-promises` only checks _named_ methods against extended/implemented types: that is, call/construct/index signatures are ignored. Call signatures are not required in TypeScript to be consistent with one another, and construct signatures cannot be `async` in the first place. Index signature checking may be implemented in the future.
:::
#### `properties`
Disables checking an asynchronous function passed as an object property expected to be a function that returns `void`.
#### `returns`
Disables checking an asynchronous function returned in a function whose return type is a function that returns `void`.
#### `variables`
Disables checking an asynchronous function used as a variable whose return type is a function that returns `void`.
### `checksSpreads`
If you don't want to check object spreads, you can add this configuration:
```json
{
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksSpreads": false
}
]
}
```
## Examples ## Examples
### `checksConditionals`
Examples of code for this rule with `checksConditionals: true`:
<Tabs> <Tabs>
<TabItem value="❌ Incorrect"> <TabItem value="❌ Incorrect">
@ -81,45 +160,6 @@ while (await promise) {
### `checksVoidReturn` ### `checksVoidReturn`
Likewise, if you don't want to check functions that return promises where a void return is
expected, your configuration will look like this:
```json
{
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksVoidReturn": false
}
]
}
```
You can disable selective parts of the `checksVoidReturn` option by providing an object that disables specific checks.
The following options are supported:
- `arguments`: Disables checking an asynchronous function passed as argument where the parameter type expects a function that returns `void`
- `attributes`: Disables checking an asynchronous function passed as a JSX attribute expected to be a function that returns `void`
- `properties`: Disables checking an asynchronous function passed as an object property expected to be a function that returns `void`
- `returns`: Disables checking an asynchronous function returned in a function whose return type is a function that returns `void`
- `variables`: Disables checking an asynchronous function used as a variable whose return type is a function that returns `void`
For example, if you don't mind that passing a `() => Promise<void>` to a `() => void` parameter or JSX attribute can lead to a floating unhandled Promise:
```json
{
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksVoidReturn": {
"arguments": false,
"attributes": false
}
}
]
}
```
Examples of code for this rule with `checksVoidReturn: true`: Examples of code for this rule with `checksVoidReturn: true`:
<Tabs> <Tabs>
@ -140,6 +180,15 @@ document.addEventListener('click', async () => {
await fetch('/'); await fetch('/');
console.log('synchronous call'); console.log('synchronous call');
}); });
interface MySyncInterface {
setThing(): void;
}
class MyClass implements MySyncInterface {
async setThing(): Promise<void> {
this.thing = await fetchThing();
}
}
``` ```
</TabItem> </TabItem>
@ -182,6 +231,15 @@ document.addEventListener('click', () => {
handler().catch(handleError); handler().catch(handleError);
}); });
interface MyAsyncInterface {
setThing(): Promise<void>;
}
class MyClass implements MyAsyncInterface {
async setThing(): Promise<void> {
this.thing = await fetchThing();
}
}
``` ```
</TabItem> </TabItem>
@ -189,19 +247,6 @@ document.addEventListener('click', () => {
### `checksSpreads` ### `checksSpreads`
If you don't want to check object spreads, you can add this configuration:
```json
{
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksSpreads": false
}
]
}
```
Examples of code for this rule with `checksSpreads: true`: Examples of code for this rule with `checksSpreads: true`:
<Tabs> <Tabs>

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been deprecated in favour of the [`parameter-properties`](https://typescript-eslint.io/rules/parameter-properties/) rule. This rule has been deprecated in favour of the [`parameter-properties`](https://typescript-eslint.io/rules/parameter-properties/) rule.

View file

@ -1,5 +1,5 @@
--- ---
description: 'Disallow type parameters that only appear once.' description: "Disallow type parameters that aren't used multiple times."
--- ---
import Tabs from '@theme/Tabs'; import Tabs from '@theme/Tabs';
@ -9,10 +9,10 @@ import TabItem from '@theme/TabItem';
> >
> See **https://typescript-eslint.io/rules/no-unnecessary-type-parameters** for documentation. > See **https://typescript-eslint.io/rules/no-unnecessary-type-parameters** for documentation.
This rule forbids type parameters that only appear once in a function, method, or class definition. This rule forbids type parameters that aren't used multiple times in a function, method, or class definition.
Type parameters relate two types. Type parameters relate two types.
If a type parameter only appears once, then it is not relating anything. If a type parameter is only used once, then it is not relating anything.
It can usually be replaced with explicit types such as `unknown`. It can usually be replaced with explicit types such as `unknown`.
At best unnecessary type parameters make code harder to read. At best unnecessary type parameters make code harder to read.

View file

@ -15,7 +15,7 @@ Using `any` disables many type checking rules and is generally best used only as
Despite your best intentions, the `any` type can sometimes leak into your codebase. Despite your best intentions, the `any` type can sometimes leak into your codebase.
Returning an an `any`-typed value from a function creates a potential type safety hole and source of bugs in your codebase. Returning an an `any`-typed value from a function creates a potential type safety hole and source of bugs in your codebase.
This rule disallows returning `any` or `any[]` from a function. This rule disallows returning `any` or `any[]` from a function and returning `Promise<any>` from an async function.
This rule also compares generic type argument types to ensure you don't return an unsafe `any` in a generic position to a function that's expecting a specific type. This rule also compares generic type argument types to ensure you don't return an unsafe `any` in a generic position to a function that's expecting a specific type.
For example, it will error if you return `Set<any>` from a function declared as returning `Set<string>`. For example, it will error if you return `Set<any>` from a function declared as returning `Set<string>`.
@ -56,6 +56,10 @@ const foo10 = () => [] as any[];
const foo11 = (): string[] => [1, 2, 3] as any[]; const foo11 = (): string[] => [1, 2, 3] as any[];
async function foo13() {
return Promise.resolve({} as any);
}
// generic position examples // generic position examples
function assignability1(): Set<string> { function assignability1(): Set<string> {
return new Set<any>([1]); return new Set<any>([1]);
@ -78,6 +82,10 @@ function foo2() {
const foo3 = () => []; const foo3 = () => [];
const foo4 = () => ['a']; const foo4 = () => ['a'];
async function foo5() {
return Promise.resolve(1);
}
function assignability1(): Set<string> { function assignability1(): Set<string> {
return new Set<string>(['foo']); return new Set<string>(['foo']);
} }

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been renamed to [`no-unnecessary-template-expression`](./no-unnecessary-template-expression.mdx). See [#8544](https://github.com/typescript-eslint/typescript-eslint/issues/8544) for more information. This rule has been renamed to [`no-unnecessary-template-expression`](./no-unnecessary-template-expression.mdx). See [#8544](https://github.com/typescript-eslint/typescript-eslint/issues/8544) for more information.

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been renamed to [`sort-type-constituents`](https://typescript-eslint.io/rules/sort-type-constituents). This rule has been renamed to [`sort-type-constituents`](https://typescript-eslint.io/rules/sort-type-constituents).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -30,13 +30,13 @@ The following nodes are considered boolean expressions and their type is checked
```ts ```ts
// nullable numbers are considered unsafe by default // nullable numbers are considered unsafe by default
let num: number | undefined = 0; declare const num: number | undefined;
if (num) { if (num) {
console.log('num is defined'); console.log('num is defined');
} }
// nullable strings are considered unsafe by default // nullable strings are considered unsafe by default
let str: string | null = null; declare const str: string | null;
if (!str) { if (!str) {
console.log('str is empty'); console.log('str is empty');
} }

View file

@ -1,3 +1,7 @@
---
displayed_sidebar: rulesSidebar
---
:::danger Deprecated :::danger Deprecated
This rule has been moved to the [ESLint stylistic plugin](https://eslint.style). This rule has been moved to the [ESLint stylistic plugin](https://eslint.style).

View file

@ -1,6 +1,6 @@
{ {
"name": "@typescript-eslint/eslint-plugin", "name": "@typescript-eslint/eslint-plugin",
"version": "8.0.1", "version": "8.1.0",
"description": "TypeScript plugin for ESLint", "description": "TypeScript plugin for ESLint",
"files": [ "files": [
"dist", "dist",
@ -60,10 +60,10 @@
}, },
"dependencies": { "dependencies": {
"@eslint-community/regexpp": "^4.10.0", "@eslint-community/regexpp": "^4.10.0",
"@typescript-eslint/scope-manager": "8.0.1", "@typescript-eslint/scope-manager": "8.1.0",
"@typescript-eslint/type-utils": "8.0.1", "@typescript-eslint/type-utils": "8.1.0",
"@typescript-eslint/utils": "8.0.1", "@typescript-eslint/utils": "8.1.0",
"@typescript-eslint/visitor-keys": "8.0.1", "@typescript-eslint/visitor-keys": "8.1.0",
"graphemer": "^1.4.0", "graphemer": "^1.4.0",
"ignore": "^5.3.1", "ignore": "^5.3.1",
"natural-compare": "^1.4.0", "natural-compare": "^1.4.0",
@ -74,8 +74,8 @@
"@types/marked": "^5.0.2", "@types/marked": "^5.0.2",
"@types/mdast": "^4.0.3", "@types/mdast": "^4.0.3",
"@types/natural-compare": "*", "@types/natural-compare": "*",
"@typescript-eslint/rule-schema-to-typescript-types": "8.0.1", "@typescript-eslint/rule-schema-to-typescript-types": "8.1.0",
"@typescript-eslint/rule-tester": "8.0.1", "@typescript-eslint/rule-tester": "8.1.0",
"ajv": "^6.12.6", "ajv": "^6.12.6",
"cross-env": "^7.0.3", "cross-env": "^7.0.3",
"cross-fetch": "*", "cross-fetch": "*",

View file

@ -1,6 +1,6 @@
{ {
"name": "@typescript-eslint/parser", "name": "@typescript-eslint/parser",
"version": "8.0.1", "version": "8.1.0",
"description": "An ESLint custom parser which leverages TypeScript ESTree", "description": "An ESLint custom parser which leverages TypeScript ESTree",
"files": [ "files": [
"dist", "dist",
@ -52,10 +52,10 @@
"eslint": "^8.57.0 || ^9.0.0" "eslint": "^8.57.0 || ^9.0.0"
}, },
"dependencies": { "dependencies": {
"@typescript-eslint/scope-manager": "8.0.1", "@typescript-eslint/scope-manager": "8.1.0",
"@typescript-eslint/types": "8.0.1", "@typescript-eslint/types": "8.1.0",
"@typescript-eslint/typescript-estree": "8.0.1", "@typescript-eslint/typescript-estree": "8.1.0",
"@typescript-eslint/visitor-keys": "8.0.1", "@typescript-eslint/visitor-keys": "8.1.0",
"debug": "^4.3.4" "debug": "^4.3.4"
}, },
"devDependencies": { "devDependencies": {

View file

@ -1,6 +1,6 @@
{ {
"name": "@typescript-eslint/scope-manager", "name": "@typescript-eslint/scope-manager",
"version": "8.0.1", "version": "8.1.0",
"description": "TypeScript scope analyser for ESLint", "description": "TypeScript scope analyser for ESLint",
"files": [ "files": [
"dist", "dist",
@ -46,13 +46,13 @@
"typecheck": "npx nx typecheck" "typecheck": "npx nx typecheck"
}, },
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.0.1", "@typescript-eslint/types": "8.1.0",
"@typescript-eslint/visitor-keys": "8.0.1" "@typescript-eslint/visitor-keys": "8.1.0"
}, },
"devDependencies": { "devDependencies": {
"@jest/types": "29.6.3", "@jest/types": "29.6.3",
"@types/glob": "*", "@types/glob": "*",
"@typescript-eslint/typescript-estree": "8.0.1", "@typescript-eslint/typescript-estree": "8.1.0",
"glob": "*", "glob": "*",
"jest-specific-snapshot": "*", "jest-specific-snapshot": "*",
"make-dir": "*", "make-dir": "*",

View file

@ -31,14 +31,15 @@ export declare function isTypeAnyArrayType(type: ts.Type, checker: ts.TypeChecke
export declare function isTypeUnknownArrayType(type: ts.Type, checker: ts.TypeChecker): boolean; export declare function isTypeUnknownArrayType(type: ts.Type, checker: ts.TypeChecker): boolean;
export declare enum AnyType { export declare enum AnyType {
Any = 0, Any = 0,
AnyArray = 1, PromiseAny = 1,
Safe = 2 AnyArray = 2,
Safe = 3
} }
/** /**
* @returns `AnyType.Any` if the type is `any`, `AnyType.AnyArray` if the type is `any[]` or `readonly any[]`, * @returns `AnyType.Any` if the type is `any`, `AnyType.AnyArray` if the type is `any[]` or `readonly any[]`, `AnyType.PromiseAny` if the type is `Promise<any>`,
* otherwise it returns `AnyType.Safe`. * otherwise it returns `AnyType.Safe`.
*/ */
export declare function isAnyOrAnyArrayTypeDiscriminated(node: ts.Node, checker: ts.TypeChecker): AnyType; export declare function discriminateAnyType(type: ts.Type, checker: ts.TypeChecker, program: ts.Program, tsNode: ts.Node): AnyType;
/** /**
* @returns Whether a type is an instance of the parent type, including for the parent's base types. * @returns Whether a type is an instance of the parent type, including for the parent's base types.
*/ */

View file

@ -1 +1 @@
{"version":3,"file":"predicates.d.ts","sourceRoot":"","sources":["../src/predicates.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAMjC;;GAEG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CAQrD;AAED;;;GAGG;AACH,wBAAgB,kCAAkC,CAChD,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,OAAO,EAAE,EAAE,CAAC,WAAW,GACtB,OAAO,CAQT;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CAEtD;AAED;;GAEG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CAExD;AAYD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,IAAI,IAAI,EAAE,CAAC,aAAa,CAM3E;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,GAAG,OAAO,CAQpD;AAED;;GAEG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,OAAO,EAAE,EAAE,CAAC,WAAW,GACtB,OAAO,CAKT;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,OAAO,EAAE,EAAE,CAAC,WAAW,GACtB,OAAO,CAKT;AAED,oBAAY,OAAO;IACjB,GAAG,IAAA;IACH,QAAQ,IAAA;IACR,IAAI,IAAA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EAAE,CAAC,WAAW,GACtB,OAAO,CAKT;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,OAAO,EAAE,EAAE,CAAC,WAAW,GACtB,OAAO,CAKT;AAED,oBAAY,OAAO;IACjB,GAAG,IAAA;IACH,UAAU,IAAA;IACV,QAAQ,IAAA;IACR,IAAI,IAAA;CACL;AACD;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,OAAO,EAAE,EAAE,CAAC,WAAW,EACvB,OAAO,EAAE,EAAE,CAAC,OAAO,EACnB,MAAM,EAAE,EAAE,CAAC,IAAI,GACd,OAAO,CAyBT;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,EAAE,CAAC,IAAI,EACb,UAAU,EAAE,EAAE,CAAC,IAAI,GAClB,OAAO,CAqBT;AAED,wBAAgB,uBAAuB,CACrC,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,IAAI,IAAI,EAAE,CAAC,iBAAiB,CAE9B;AAED,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,EAAE,CAAC,IAAI,GACZ,IAAI,IAAI,EAAE,CAAC,mBAAmB,CAEhC"}

View file

@ -35,7 +35,7 @@ exports.isTypeReferenceType = isTypeReferenceType;
exports.isTypeAnyType = isTypeAnyType; exports.isTypeAnyType = isTypeAnyType;
exports.isTypeAnyArrayType = isTypeAnyArrayType; exports.isTypeAnyArrayType = isTypeAnyArrayType;
exports.isTypeUnknownArrayType = isTypeUnknownArrayType; exports.isTypeUnknownArrayType = isTypeUnknownArrayType;
exports.isAnyOrAnyArrayTypeDiscriminated = isAnyOrAnyArrayTypeDiscriminated; exports.discriminateAnyType = discriminateAnyType;
exports.typeIsOrHasBaseType = typeIsOrHasBaseType; exports.typeIsOrHasBaseType = typeIsOrHasBaseType;
exports.isTypeBigIntLiteralType = isTypeBigIntLiteralType; exports.isTypeBigIntLiteralType = isTypeBigIntLiteralType;
exports.isTypeTemplateLiteralType = isTypeTemplateLiteralType; exports.isTypeTemplateLiteralType = isTypeTemplateLiteralType;
@ -122,21 +122,32 @@ function isTypeUnknownArrayType(type, checker) {
var AnyType; var AnyType;
(function (AnyType) { (function (AnyType) {
AnyType[AnyType["Any"] = 0] = "Any"; AnyType[AnyType["Any"] = 0] = "Any";
AnyType[AnyType["AnyArray"] = 1] = "AnyArray"; AnyType[AnyType["PromiseAny"] = 1] = "PromiseAny";
AnyType[AnyType["Safe"] = 2] = "Safe"; AnyType[AnyType["AnyArray"] = 2] = "AnyArray";
AnyType[AnyType["Safe"] = 3] = "Safe";
})(AnyType || (exports.AnyType = AnyType = {})); })(AnyType || (exports.AnyType = AnyType = {}));
/** /**
* @returns `AnyType.Any` if the type is `any`, `AnyType.AnyArray` if the type is `any[]` or `readonly any[]`, * @returns `AnyType.Any` if the type is `any`, `AnyType.AnyArray` if the type is `any[]` or `readonly any[]`, `AnyType.PromiseAny` if the type is `Promise<any>`,
* otherwise it returns `AnyType.Safe`. * otherwise it returns `AnyType.Safe`.
*/ */
function isAnyOrAnyArrayTypeDiscriminated(node, checker) { function discriminateAnyType(type, checker, program, tsNode) {
const type = checker.getTypeAtLocation(node);
if (isTypeAnyType(type)) { if (isTypeAnyType(type)) {
return AnyType.Any; return AnyType.Any;
} }
if (isTypeAnyArrayType(type, checker)) { if (isTypeAnyArrayType(type, checker)) {
return AnyType.AnyArray; return AnyType.AnyArray;
} }
for (const part of tsutils.typeParts(type)) {
if (tsutils.isThenableType(checker, tsNode, type)) {
const awaitedType = checker.getAwaitedType(part);
if (awaitedType) {
const awaitedAnyType = discriminateAnyType(awaitedType, checker, program, tsNode);
if (awaitedAnyType === AnyType.Any) {
return AnyType.PromiseAny;
}
}
}
}
return AnyType.Safe; return AnyType.Safe;
} }
/** /**

View file

@ -1 +1 @@
{"version":3,"file":"predicates.js","sourceRoot":"","sources":["../src/predicates.ts"],"names":[],"mappings":";;;;;;;;;;;;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oBACnC,OAAO,OAAO,CAAC,UAAU,CAAC;gBAC5B,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC,IAAI,CAAC;AACtB,CAAC;AAED;;GAEG;AACH,SAAgB,mBAAmB,CACjC,IAAa,EACb,UAAmB;IAEnB,MAAM,YAAY,GAAG,UAAU,CAAC,SAAS,EAAE,CAAC;IAC5C,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,YAAY,EAAE,CAAC;QACvC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,gBAAgB,GAAG,CAAC,IAAI,CAAC,CAAC;IAChC,MAAM,aAAa,GAAG,IAAI,CAAC,YAAY,EAAE,CAAC;IAE1C,IAAI,aAAa,EAAE,CAAC;QAClB,gBAAgB,CAAC,IAAI,CAAC,GAAG,aAAa,CAAC,CAAC;IAC1C,CAAC;IAED,KAAK,MAAM,QAAQ,IAAI,gBAAgB,EAAE,CAAC;QACxC,MAAM,UAAU,GAAG,QAAQ,CAAC,SAAS,EAAE,CAAC;QACxC,IAAI,UAAU,IAAI,UAAU,CAAC,IAAI,KAAK,YAAY,CAAC,IAAI,EAAE,CAAC;YACxD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAgB,uBAAuB,CACrC,IAAa;IAEb,OAAO,IAAA,6BAAa,EAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,aAAa,CAAC,CAAC;AACzD,CAAC;AAED,SAAgB,yBAAyB,CACvC,IAAa;IAEb,OAAO,IAAA,6BAAa,EAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,eAAe,CAAC,CAAC;AAC3D,CAAC"}

View file

@ -1,6 +1,6 @@
{ {
"name": "@typescript-eslint/type-utils", "name": "@typescript-eslint/type-utils",
"version": "8.0.1", "version": "8.1.0",
"description": "Type utilities for working with TypeScript + ESLint together", "description": "Type utilities for working with TypeScript + ESLint together",
"files": [ "files": [
"dist", "dist",
@ -46,14 +46,14 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@typescript-eslint/typescript-estree": "8.0.1", "@typescript-eslint/typescript-estree": "8.1.0",
"@typescript-eslint/utils": "8.0.1", "@typescript-eslint/utils": "8.1.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"ts-api-utils": "^1.3.0" "ts-api-utils": "^1.3.0"
}, },
"devDependencies": { "devDependencies": {
"@jest/types": "29.6.3", "@jest/types": "29.6.3",
"@typescript-eslint/parser": "8.0.1", "@typescript-eslint/parser": "8.1.0",
"ajv": "^6.12.6", "ajv": "^6.12.6",
"downlevel-dts": "*", "downlevel-dts": "*",
"jest": "29.7.0", "jest": "29.7.0",

View file

@ -445,6 +445,18 @@ export declare interface ConditionalExpression extends BaseNode {
consequent: Expression; consequent: Expression;
alternate: Expression; alternate: Expression;
} }
export declare interface ConstDeclaration extends LetOrConstOrVarDeclarationBase {
kind: 'const';
/**
* In a `declare const` declaration, the declarators may have initializers, but
* not definite assignment assertions. Each declarator cannot have both an
* initializer and a type annotation.
*
* Even if the declaration has no `declare`, it may still be ambient and have
* no initializer.
*/
declarations: VariableDeclaratorMaybeInit[];
}
export declare interface ContinueStatement extends BaseNode { export declare interface ContinueStatement extends BaseNode {
type: AST_NODE_TYPES.ContinueStatement; type: AST_NODE_TYPES.ContinueStatement;
label: Identifier | null; label: Identifier | null;
@ -917,11 +929,12 @@ export declare interface LabeledStatement extends BaseNode {
body: Statement; body: Statement;
} }
export declare type LeftHandSideExpression = ArrayExpression | ArrayPattern | ArrowFunctionExpression | CallExpression | ClassExpression | FunctionExpression | Identifier | JSXElement | JSXFragment | LiteralExpression | MemberExpression | MetaProperty | ObjectExpression | ObjectPattern | SequenceExpression | Super | TaggedTemplateExpression | ThisExpression | TSAsExpression | TSNonNullExpression | TSTypeAssertion; export declare type LeftHandSideExpression = ArrayExpression | ArrayPattern | ArrowFunctionExpression | CallExpression | ClassExpression | FunctionExpression | Identifier | JSXElement | JSXFragment | LiteralExpression | MemberExpression | MetaProperty | ObjectExpression | ObjectPattern | SequenceExpression | Super | TaggedTemplateExpression | ThisExpression | TSAsExpression | TSNonNullExpression | TSTypeAssertion;
export declare interface LetOrConstOrVarDeclaration extends BaseNode { export declare type LetOrConstOrVarDeclaration = ConstDeclaration | LetOrVarDeclaredDeclaration | LetOrVarNonDeclaredDeclaration;
declare interface LetOrConstOrVarDeclarationBase extends BaseNode {
type: AST_NODE_TYPES.VariableDeclaration; type: AST_NODE_TYPES.VariableDeclaration;
/** /**
* The variables declared by this declaration. * The variables declared by this declaration.
* Note that there may be 0 declarations (i.e. `const;`). * Always non-empty.
* @example * @example
* ```ts * ```ts
* let x; * let x;
@ -948,11 +961,30 @@ export declare interface LetOrConstOrVarDeclaration extends BaseNode {
*/ */
kind: 'const' | 'let' | 'var'; kind: 'const' | 'let' | 'var';
} }
export declare interface LetOrConstOrVarDeclarator extends BaseNode { export declare type LetOrConstOrVarDeclarator = VariableDeclaratorDefiniteAssignment | VariableDeclaratorMaybeInit | VariableDeclaratorNoInit;
type: AST_NODE_TYPES.VariableDeclarator; export declare interface LetOrVarDeclaredDeclaration extends LetOrConstOrVarDeclarationBase {
id: BindingName; kind: 'let' | 'var';
init: Expression | null; declare: true;
definite: boolean; /**
* In a `declare let` declaration, the declarators must not have definite assignment
* assertions or initializers.
*
* @example
* ```ts
* using x = 1;
* using y =1, z = 2;
* ```
*/
declarations: VariableDeclaratorNoInit[];
}
export declare interface LetOrVarNonDeclaredDeclaration extends LetOrConstOrVarDeclarationBase {
kind: 'let' | 'var';
declare: false;
/**
* In a `let`/`var` declaration, the declarators may have definite assignment
* assertions or initializers, but not both.
*/
declarations: (VariableDeclaratorDefiniteAssignment | VariableDeclaratorMaybeInit)[];
} }
export declare interface LineComment extends BaseToken { export declare interface LineComment extends BaseToken {
type: AST_TOKEN_TYPES.Line; type: AST_TOKEN_TYPES.Line;
@ -1996,57 +2028,8 @@ export declare interface UpdateExpression extends UnaryExpressionBase {
operator: '--' | '++'; operator: '--' | '++';
} }
export declare type UsingDeclaration = UsingInForOfDeclaration | UsingInNormalContextDeclaration; export declare type UsingDeclaration = UsingInForOfDeclaration | UsingInNormalContextDeclaration;
export declare type UsingDeclarator = UsingInForOfDeclarator | UsingInNomalConextDeclarator; declare interface UsingDeclarationBase extends BaseNode {
export declare interface UsingInForOfDeclaration extends BaseNode {
type: AST_NODE_TYPES.VariableDeclaration; type: AST_NODE_TYPES.VariableDeclaration;
/**
* The variables declared by this declaration.
* Note that there may be 0 declarations (i.e. `const;`).
* @example
* ```ts
* for(using x of y){}
* ```
*/
declarations: UsingInForOfDeclarator[];
/**
* This value will always be `false`
* because 'declare' modifier cannot appear on a 'using' declaration.
*/
declare: false;
/**
* The keyword used to declare the variable(s)
* @example
* ```ts
* for(using x of y){}
* for(await using x of y){}
* ```
*/
kind: 'await using' | 'using';
}
export declare interface UsingInForOfDeclarator extends BaseNode {
type: AST_NODE_TYPES.VariableDeclarator;
id: Identifier;
init: null;
definite: boolean;
}
export declare interface UsingInNomalConextDeclarator extends BaseNode {
type: AST_NODE_TYPES.VariableDeclarator;
id: Identifier;
init: Expression;
definite: boolean;
}
export declare interface UsingInNormalContextDeclaration extends BaseNode {
type: AST_NODE_TYPES.VariableDeclaration;
/**
* The variables declared by this declaration.
* Note that there may be 0 declarations (i.e. `const;`).
* @example
* ```ts
* using x = 1;
* using y =1, z = 2;
* ```
*/
declarations: UsingInNomalConextDeclarator[];
/** /**
* This value will always be `false` * This value will always be `false`
* because 'declare' modifier cannot appear on a 'using' declaration. * because 'declare' modifier cannot appear on a 'using' declaration.
@ -2062,9 +2045,76 @@ export declare interface UsingInNormalContextDeclaration extends BaseNode {
*/ */
kind: 'await using' | 'using'; kind: 'await using' | 'using';
} }
export declare type UsingDeclarator = UsingInForOfDeclarator | UsingInNormalContextDeclarator;
export declare interface UsingInForOfDeclaration extends UsingDeclarationBase {
/**
* The variables declared by this declaration.
* Always has exactly one element.
* @example
* ```ts
* for (using x of y) {}
* ```
*/
declarations: [UsingInForOfDeclarator];
}
export declare interface UsingInForOfDeclarator extends VariableDeclaratorBase {
id: Identifier;
init: null;
definite: false;
}
export declare interface UsingInNormalContextDeclaration extends UsingDeclarationBase {
/**
* The variables declared by this declaration.
* Always non-empty.
* @example
* ```ts
* using x = 1;
* using y = 1, z = 2;
* ```
*/
declarations: UsingInNormalContextDeclarator[];
}
export declare interface UsingInNormalContextDeclarator extends VariableDeclaratorBase {
id: Identifier;
init: Expression;
definite: false;
}
declare type ValueOf<T> = T[keyof T]; declare type ValueOf<T> = T[keyof T];
export declare type VariableDeclaration = LetOrConstOrVarDeclaration | UsingDeclaration; export declare type VariableDeclaration = LetOrConstOrVarDeclaration | UsingDeclaration;
export declare type VariableDeclarator = LetOrConstOrVarDeclarator | UsingDeclarator; export declare type VariableDeclarator = LetOrConstOrVarDeclarator | UsingDeclarator;
declare interface VariableDeclaratorBase extends BaseNode {
type: AST_NODE_TYPES.VariableDeclarator;
/**
* The name(s) of the variable(s).
*/
id: BindingName;
/**
* The initializer expression of the variable. Must be present for `const` unless
* in a `declare const`.
*/
init: Expression | null;
/**
* Whether there's definite assignment assertion (`let x!: number`).
* If `true`, then: `id` must be an identifier with a type annotation,
* `init` must be `null`, and the declarator must be a `var`/`let` declarator.
*/
definite: boolean;
}
export declare interface VariableDeclaratorDefiniteAssignment extends VariableDeclaratorBase {
/**
* The name of the variable. Must have a type annotation.
*/
id: Identifier;
init: null;
definite: true;
}
export declare interface VariableDeclaratorMaybeInit extends VariableDeclaratorBase {
definite: false;
}
export declare interface VariableDeclaratorNoInit extends VariableDeclaratorBase {
init: null;
definite: false;
}
export declare interface WhileStatement extends BaseNode { export declare interface WhileStatement extends BaseNode {
type: AST_NODE_TYPES.WhileStatement; type: AST_NODE_TYPES.WhileStatement;
test: Expression; test: Expression;

File diff suppressed because one or more lines are too long

View file

@ -15,6 +15,21 @@ declare module './generated/ast-spec' {
interface AccessorPropertyNonComputedName { interface AccessorPropertyNonComputedName {
parent: TSESTree.ClassBody; parent: TSESTree.ClassBody;
} }
interface VariableDeclaratorDefiniteAssignment {
parent: TSESTree.VariableDeclaration;
}
interface VariableDeclaratorMaybeInit {
parent: TSESTree.VariableDeclaration;
}
interface VariableDeclaratorNoInit {
parent: TSESTree.VariableDeclaration;
}
interface UsingInForOfDeclarator {
parent: TSESTree.VariableDeclaration;
}
interface UsingInNormalContextDeclarator {
parent: TSESTree.VariableDeclaration;
}
interface TSAbstractAccessorPropertyComputedName { interface TSAbstractAccessorPropertyComputedName {
parent: TSESTree.ClassBody; parent: TSESTree.ClassBody;
} }

View file

@ -1 +1 @@
{"version":3,"file":"ts-estree.d.ts","sourceRoot":"","sources":["../src/ts-estree.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,QAAQ,MAAM,sBAAsB,CAAC;AAGtD,OAAO,QAAQ,sBAAsB,CAAC;IACpC,UAAU,QAAQ;QAChB,MAAM,EAAE,QAAQ,CAAC,IAAI,CAAC;KACvB;IAED,UAAU,OAAO;QACf;;WAEG;QACH,MAAM,CAAC,EAAE,KAAK,CAAC;KAChB;IAED,UAAU,4BAA4B;QACpC,MAAM,EAAE,QAAQ,CAAC,SAAS,CAAC;KAC5B;IACD,UAAU,+BAA+B;QACvC,MAAM,EAAE,QAAQ,CAAC,SAAS,CAAC;KAC5B;IACD,UAAU,sCAAsC;QAC9C,MAAM,EAAE,QAAQ,CAAC,SAAS,CAAC;KAC5B;IACD,UAAU,yCAAyC;QACjD,MAAM,EAAE,QAAQ,CAAC,SAAS,CAAC;KAC5B;IAED,UAAU,WAAW;QACnB,MAAM,EAAE,QAAQ,CAAC,YAAY,CAAC;KAC/B;IAED,UAAU,SAAS;QACjB,MAAM,EAAE,QAAQ,CAAC,eAAe,GAAG,QAAQ,CAAC,gBAAgB,CAAC;KAC9D;IAED,UAAU,eAAe;QACvB,MAAM,EAAE,QAAQ,CAAC,sBAAsB,C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AAmB,CAAC;KACtC;IAED,UAAU,mBAAmB;QAC3B,MAAM,EAAE,QAAQ,CAAC,YAAY,CAAC;KAC/B;IAED,UAAU,+BAA+B;QACvC,MAAM,EAAE,QAAQ,CAAC,eAAe,GAAG,QAAQ,CAAC,aAAa,CAAC;KAC3D;IACD,UAAU,kCAAkC;QAC1C,MAAM,EAAE,QAAQ,CAAC,eAAe,GAAG,QAAQ,CAAC,aAAa,CAAC;KAC3D;IAED,UAAU,eAAe;QACvB,MAAM,EACF,QAAQ,CAAC,WAAW,GACpB,QAAQ,CAAC,0BAA0B,GACnC,QAAQ,CAAC,YAAY,CAAC;KAC3B;CACF;AAED,OAAO,KAAK,QAAQ,MAAM,sBAAsB,CAAC"}

View file

@ -1 +1 @@
{"version":3,"file":"ts-estree.js","sourceRoot":"","sources":["../src/ts-estree.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA2MA,iEAAiD"} {"version":3,"file":"ts-estree.js","sourceRoot":"","sources":["../src/ts-estree.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA+NA,iEAAiD"}

View file

@ -1,6 +1,6 @@
{ {
"name": "@typescript-eslint/types", "name": "@typescript-eslint/types",
"version": "8.0.1", "version": "8.1.0",
"description": "Types for the TypeScript-ESTree AST spec", "description": "Types for the TypeScript-ESTree AST spec",
"files": [ "files": [
"dist", "dist",

View file

@ -1 +1 @@
{"version":3,"file":"convert.d.ts","sourceRoot":"","sources":["../src/convert.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,YAAY,CAAC;AAGjC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AA6B5C,OAAO,KAAK,EACV,aAAa,EACb,2BAA2B,EAC5B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,KAAK,EAAE,QAAQ,EAAoB,MAAM,EAAE,MAAM,a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.convertChild(node.statement), body: this.convertChild(node.statement),
}); });
case SyntaxKind.ForInStatement: case SyntaxKind.ForInStatement:
this.#checkForStatementDeclaration(node.initializer); this.#checkForStatementDeclaration(node.initializer, node.kind);
return this.createNode(node, { return this.createNode(node, {
type: ts_estree_1.AST_NODE_TYPES.ForInStatement, type: ts_estree_1.AST_NODE_TYPES.ForInStatement,
left: this.convertPattern(node.initializer), left: this.convertPattern(node.initializer),
right: this.convertChild(node.expression), right: this.convertChild(node.expression),
body: this.convertChild(node.statement), body: this.convertChild(node.statement),
}); });
case SyntaxKind.ForOfStatement: case SyntaxKind.ForOfStatement: {
this.#checkForStatementDeclaration(node.initializer, node.kind);
return this.createNode(node, { return this.createNode(node, {
type: ts_estree_1.AST_NODE_TYPES.ForOfStatement, type: ts_estree_1.AST_NODE_TYPES.ForOfStatement,
left: this.convertPattern(node.initializer), left: this.convertPattern(node.initializer),
@ -700,6 +701,7 @@ class Converter {
await: Boolean(node.awaitModifier && await: Boolean(node.awaitModifier &&
node.awaitModifier.kind === SyntaxKind.AwaitKeyword), node.awaitModifier.kind === SyntaxKind.AwaitKeyword),
}); });
}
// Declarations // Declarations
case SyntaxKind.FunctionDeclaration: { case SyntaxKind.FunctionDeclaration: {
const isDeclare = (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node); const isDeclare = (0, node_utils_1.hasModifier)(SyntaxKind.DeclareKeyword, node);
@ -738,11 +740,23 @@ class Converter {
return this.fixExports(node, result); return this.fixExports(node, result);
} }
case SyntaxKind.VariableDeclaration: { case SyntaxKind.VariableDeclaration: {
const definite = !!node.exclamationToken;
const init = this.convertChild(node.initializer);
const id = this.convertBindingNameWithTypeAnnotation(node.name, node.type, node);
if (definite) {
if (init) {
this.#throwError(node, 'Declarations with initializers cannot also have definite assignment assertions.');
}
else if (id.type !== ts_estree_1.AST_NODE_TYPES.Identifier ||
!id.typeAnnotation) {
this.#throwError(node, 'Declarations with definite assignment assertions must also have type annotations.');
}
}
return this.createNode(node, { return this.createNode(node, {
type: ts_estree_1.AST_NODE_TYPES.VariableDeclarator, type: ts_estree_1.AST_NODE_TYPES.VariableDeclarator,
definite: !!node.exclamationToken, definite,
id: this.convertBindingNameWithTypeAnnotation(node.name, node.type, node), id,
init: this.convertChild(node.initializer), init,
}); });
} }
case SyntaxKind.VariableStatement: { case SyntaxKind.VariableStatement: {
@ -765,6 +779,31 @@ class Converter {
} }
}); });
} }
// Definite assignment only allowed for non-declare let and var
if (result.declare ||
['using', 'await using', 'const'].includes(result.kind)) {
node.declarationList.declarations.forEach((declaration, i) => {
if (result.declarations[i].definite) {
this.#throwError(declaration, `A definite assignment assertion '!' is not permitted in this context.`);
}
});
}
if (result.declare) {
node.declarationList.declarations.forEach((declaration, i) => {
if (result.declarations[i].init &&
(['let', 'var'].includes(result.kind) ||
result.declarations[i].id.typeAnnotation)) {
this.#throwError(declaration, `Initializers are not permitted in ambient contexts.`);
}
});
// Theoretically, only certain initializers are allowed for declare const,
// (TS1254: A 'const' initializer in an ambient context must be a string
// or numeric literal or literal enum reference.) but we just allow
// all expressions
}
// Note! No-declare does not mean the variable is not ambient, because
// it can be further nested in other declare contexts. Therefore we cannot
// check for const initializers.
/** /**
* Semantically, decorators are not allowed on variable declarations, * Semantically, decorators are not allowed on variable declarations,
* Pre 4.8 TS would include them in the AST, so we did as well. * Pre 4.8 TS would include them in the AST, so we did as well.
@ -2596,12 +2635,29 @@ class Converter {
} }
throw (0, node_utils_1.createError)(message, this.ast, start, end); throw (0, node_utils_1.createError)(message, this.ast, start, end);
} }
#checkForStatementDeclaration(initializer) { #checkForStatementDeclaration(initializer, kind) {
const loop = kind === ts.SyntaxKind.ForInStatement ? 'for...in' : 'for...of';
if (ts.isVariableDeclarationList(initializer)) { if (ts.isVariableDeclarationList(initializer)) {
if ((initializer.flags & ts.NodeFlags.Using) !== 0) { if (initializer.declarations.length !== 1) {
this.#throwError(initializer, `Only a single variable declaration is allowed in a '${loop}' statement.`);
}
const declaration = initializer.declarations[0];
if (declaration.initializer) {
this.#throwError(declaration, `The variable declaration of a '${loop}' statement cannot have an initializer.`);
}
else if (declaration.type) {
this.#throwError(declaration, `The variable declaration of a '${loop}' statement cannot have a type annotation.`);
}
if (kind === ts.SyntaxKind.ForInStatement &&
initializer.flags & ts.NodeFlags.Using) {
this.#throwError(initializer, "The left-hand side of a 'for...in' statement cannot be a 'using' declaration."); this.#throwError(initializer, "The left-hand side of a 'for...in' statement cannot be a 'using' declaration.");
} }
} }
else if (!(0, node_utils_1.isValidAssignmentTarget)(initializer) &&
initializer.kind !== ts.SyntaxKind.ObjectLiteralExpression &&
initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {
this.#throwError(initializer, `The left-hand side of a '${loop}' statement must be a variable or a property access.`);
}
} }
} }
exports.Converter = Converter; exports.Converter = Converter;

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -765,6 +765,7 @@ function isValidAssignmentTarget(node) {
case SyntaxKind.TypeAssertionExpression: case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.AsExpression: case SyntaxKind.AsExpression:
case SyntaxKind.SatisfiesExpression: case SyntaxKind.SatisfiesExpression:
case SyntaxKind.ExpressionWithTypeArguments:
case SyntaxKind.NonNullExpression: case SyntaxKind.NonNullExpression:
return isValidAssignmentTarget(node.expression); return isValidAssignmentTarget(node.expression);
default: default:

File diff suppressed because one or more lines are too long

View file

@ -1,6 +1,6 @@
{ {
"name": "@typescript-eslint/typescript-estree", "name": "@typescript-eslint/typescript-estree",
"version": "8.0.1", "version": "8.1.0",
"description": "A parser that converts TypeScript source code into an ESTree compatible form", "description": "A parser that converts TypeScript source code into an ESTree compatible form",
"files": [ "files": [
"dist", "dist",
@ -54,8 +54,8 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.0.1", "@typescript-eslint/types": "8.1.0",
"@typescript-eslint/visitor-keys": "8.0.1", "@typescript-eslint/visitor-keys": "8.1.0",
"debug": "^4.3.4", "debug": "^4.3.4",
"globby": "^11.1.0", "globby": "^11.1.0",
"is-glob": "^4.0.3", "is-glob": "^4.0.3",

View file

@ -10,8 +10,9 @@ export declare namespace SharedConfig {
type RuleLevelAndOptions = [RuleLevel, ...unknown[]]; type RuleLevelAndOptions = [RuleLevel, ...unknown[]];
type RuleEntry = RuleLevel | RuleLevelAndOptions; type RuleEntry = RuleLevel | RuleLevelAndOptions;
type RulesRecord = Partial<Record<string, RuleEntry>>; type RulesRecord = Partial<Record<string, RuleEntry>>;
type GlobalVariableOptionBase = 'off' | 'readonly' | 'writable'; type GlobalVariableOptionBase = 'off' | 'readonly' | 'writable' | /** @deprecated use `'writable'` */ 'writeable' | /** @deprecated use `'readonly'` */ 'readable';
type GlobalVariableOption = GlobalVariableOptionBase | boolean; type GlobalVariableOptionBoolean = /** @deprecated use `'writable'` */ true | /** @deprecated use `'readonly'` */ false;
type GlobalVariableOption = GlobalVariableOptionBase | GlobalVariableOptionBoolean;
interface GlobalsConfig { interface GlobalsConfig {
[name: string]: GlobalVariableOption; [name: string]: GlobalVariableOption;
} }
@ -181,7 +182,7 @@ export declare namespace FlatConfig {
* Set to `"latest"` for the most recent supported version. * Set to `"latest"` for the most recent supported version.
* @default "latest" * @default "latest"
*/ */
ecmaVersion?: EcmaVersion; ecmaVersion?: EcmaVersion | undefined;
/** /**
* An object specifying additional objects that should be added to the global scope during linting. * An object specifying additional objects that should be added to the global scope during linting.
*/ */
@ -194,7 +195,7 @@ export declare namespace FlatConfig {
* require('espree') * require('espree')
* ``` * ```
*/ */
parser?: Parser; parser?: Parser | undefined;
/** /**
* An object specifying additional options that are passed directly to the parser. * An object specifying additional options that are passed directly to the parser.
* The available options are parser-dependent. * The available options are parser-dependent.
@ -211,7 +212,7 @@ export declare namespace FlatConfig {
* "commonjs" * "commonjs"
* ``` * ```
*/ */
sourceType?: SourceType; sourceType?: SourceType | undefined;
} }
interface Config { interface Config {
/** /**

View file

@ -1 +1 @@
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AAE,MAAM,qBAAqB,CAAC"} {"version":3,"file":"ESLint.d.ts","sourceRoot":"","sources":["../../src/ts-eslint/ESLint.ts"],"names":[],"mappings":"AAAA,OAAO;AAEL;;GAEG;AACH,YAAY,GACb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,UAAU,IAAI,MAAM,EAAE,MAAM,qBAAqB,CAAC"}

View file

@ -1,5 +1,4 @@
"use strict"; "use strict";
/* eslint-disable @typescript-eslint/no-namespace */
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.ESLint = exports.FlatESLint = exports.LegacyESLint = void 0; exports.ESLint = exports.FlatESLint = exports.LegacyESLint = void 0;
var LegacyESLint_1 = require("./eslint/LegacyESLint"); var LegacyESLint_1 = require("./eslint/LegacyESLint");

View file

@ -1 +1 @@
{"version":3,"file":"ESLint.js","sourceRoot":"","sources":["../../src/ts-eslint/ESLint.ts"],"names":[],"mappings":";AAAA,oDAAoD;;;AAEpD,sDAM+B;AAL7B,mDAAmD;AACnD;;GAEG;AACH,4GAAA,YAAY,OAAA;AAEd,kDAAiD;AAAxC,wGAAA,UAAU,OAAA;AACnB,kDAA2D;AAAlD,oGAAA,UAAU,OAAU"} {"version":3,"file":"ESLint.js","sourceRoot":"","sources":["../../src/ts-eslint/ESLint.ts"],"names":[],"mappings":";;;AAAA,sDAM+B;AAL7B,mDAAmD;AACnD;;GAEG;AACH,4GAAA,YAAY,OAAA;AAEd,kDAAiD;AAAxC,wGAAA,UAAU,OAAA;AACnB,kDAA2D;AAAlD,oGAAA,UAAU,OAAU"}

View file

@ -1,6 +1,6 @@
{ {
"name": "@typescript-eslint/utils", "name": "@typescript-eslint/utils",
"version": "8.0.1", "version": "8.1.0",
"description": "Utilities for working with TypeScript + ESLint together", "description": "Utilities for working with TypeScript + ESLint together",
"files": [ "files": [
"dist", "dist",
@ -64,9 +64,9 @@
}, },
"dependencies": { "dependencies": {
"@eslint-community/eslint-utils": "^4.4.0", "@eslint-community/eslint-utils": "^4.4.0",
"@typescript-eslint/scope-manager": "8.0.1", "@typescript-eslint/scope-manager": "8.1.0",
"@typescript-eslint/types": "8.0.1", "@typescript-eslint/types": "8.1.0",
"@typescript-eslint/typescript-estree": "8.0.1" "@typescript-eslint/typescript-estree": "8.1.0"
}, },
"peerDependencies": { "peerDependencies": {
"eslint": "^8.57.0 || ^9.0.0" "eslint": "^8.57.0 || ^9.0.0"

View file

@ -1,6 +1,6 @@
{ {
"name": "@typescript-eslint/visitor-keys", "name": "@typescript-eslint/visitor-keys",
"version": "8.0.1", "version": "8.1.0",
"description": "Visitor keys used to help traverse the TypeScript-ESTree AST", "description": "Visitor keys used to help traverse the TypeScript-ESTree AST",
"files": [ "files": [
"dist", "dist",
@ -47,7 +47,7 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@typescript-eslint/types": "8.0.1", "@typescript-eslint/types": "8.1.0",
"eslint-visitor-keys": "^3.4.3" "eslint-visitor-keys": "^3.4.3"
}, },
"devDependencies": { "devDependencies": {

25
node_modules/adm-zip/README.md generated vendored
View file

@ -1,13 +1,19 @@
# ADM-ZIP for NodeJS with added support for electron original-fs # ADM-ZIP for NodeJS
ADM-ZIP is a pure JavaScript implementation for zip data compression for [NodeJS](https://nodejs.org/). ADM-ZIP is a pure JavaScript implementation for zip data compression for [NodeJS](https://nodejs.org/).
<a href="https://github.com/cthackers/adm-zip/actions/workflows/ci.yml">
<img src="https://github.com/cthackers/adm-zip/actions/workflows/ci.yml/badge.svg" alt="Build Status">
</a>
# Installation # Installation
With [npm](https://www.npmjs.com/) do: With [npm](https://www.npmjs.com/) do:
$ npm install adm-zip $ npm install adm-zip
**Electron** file system support described below.
## What is it good for? ## What is it good for?
The library allows you to: The library allows you to:
@ -63,4 +69,19 @@ zip.writeZip(/*target file name*/ "/home/me/files.zip");
For more detailed information please check out the [wiki](https://github.com/cthackers/adm-zip/wiki). For more detailed information please check out the [wiki](https://github.com/cthackers/adm-zip/wiki).
[![Build Status](https://travis-ci.org/cthackers/adm-zip.svg?branch=master)](https://travis-ci.org/cthackers/adm-zip) ## Electron original-fs
ADM-ZIP has supported electron **original-fs** for years without any user interractions but it causes problem with bundlers like rollup etc. For continuing support **original-fs** or any other custom file system module. There is possible specify your module by **fs** option in ADM-ZIP constructor.
Example:
```javascript
const AdmZip = require("adm-zip");
const OriginalFs = require("original-fs");
// reading archives
const zip = new AdmZip("./my_file.zip", { fs: OriginalFs });
.
.
.
```

490
node_modules/adm-zip/adm-zip.js generated vendored
View file

@ -3,8 +3,9 @@ const pth = require("path");
const ZipEntry = require("./zipEntry"); const ZipEntry = require("./zipEntry");
const ZipFile = require("./zipFile"); const ZipFile = require("./zipFile");
const get_Bool = (val, def) => (typeof val === "boolean" ? val : def); const get_Bool = (...val) => Utils.findLast(val, (c) => typeof c === "boolean");
const get_Str = (val, def) => (typeof val === "string" ? val : def); const get_Str = (...val) => Utils.findLast(val, (c) => typeof c === "string");
const get_Fun = (...val) => Utils.findLast(val, (c) => typeof c === "function");
const defaultOptions = { const defaultOptions = {
// option "noSort" : if true it disables files sorting // option "noSort" : if true it disables files sorting
@ -46,6 +47,10 @@ module.exports = function (/**String*/ input, /** object */ options) {
// instanciate utils filesystem // instanciate utils filesystem
const filetools = new Utils(opts); const filetools = new Utils(opts);
if (typeof opts.decoder !== "object" || typeof opts.decoder.encode !== "function" || typeof opts.decoder.decode !== "function") {
opts.decoder = Utils.decoder;
}
// if input is file name we retrieve its content // if input is file name we retrieve its content
if (input && "string" === typeof input) { if (input && "string" === typeof input) {
// load zip file // load zip file
@ -54,20 +59,20 @@ module.exports = function (/**String*/ input, /** object */ options) {
opts.filename = input; opts.filename = input;
inBuffer = filetools.fs.readFileSync(input); inBuffer = filetools.fs.readFileSync(input);
} else { } else {
throw new Error(Utils.Errors.INVALID_FILENAME); throw Utils.Errors.INVALID_FILENAME();
} }
} }
// create variable // create variable
const _zip = new ZipFile(inBuffer, opts); const _zip = new ZipFile(inBuffer, opts);
const { canonical, sanitize } = Utils; const { canonical, sanitize, zipnamefix } = Utils;
function getEntry(/**Object*/ entry) { function getEntry(/**Object*/ entry) {
if (entry && _zip) { if (entry && _zip) {
var item; var item;
// If entry was given as a file name // If entry was given as a file name
if (typeof entry === "string") item = _zip.getEntry(entry); if (typeof entry === "string") item = _zip.getEntry(pth.posix.normalize(entry));
// if entry was given as a ZipEntry object // if entry was given as a ZipEntry object
if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName); if (typeof entry === "object" && typeof entry.entryName !== "undefined" && typeof entry.header !== "undefined") item = _zip.getEntry(entry.entryName);
@ -84,26 +89,60 @@ module.exports = function (/**String*/ input, /** object */ options) {
return join(".", normalize(sep + zipPath.split("\\").join(sep) + sep)); return join(".", normalize(sep + zipPath.split("\\").join(sep) + sep));
} }
function filenameFilter(filterfn) {
if (filterfn instanceof RegExp) {
// if filter is RegExp wrap it
return (function (rx) {
return function (filename) {
return rx.test(filename);
};
})(filterfn);
} else if ("function" !== typeof filterfn) {
// if filter is not function we will replace it
return () => true;
}
return filterfn;
}
// keep last character on folders
const relativePath = (local, entry) => {
let lastChar = entry.slice(-1);
lastChar = lastChar === filetools.sep ? filetools.sep : "";
return pth.relative(local, entry) + lastChar;
};
return { return {
/** /**
* Extracts the given entry from the archive and returns the content as a Buffer object * Extracts the given entry from the archive and returns the content as a Buffer object
* @param entry ZipEntry object or String with the full path of the entry * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry
* * @param {Buffer|string} [pass] - password
* @return Buffer or Null in case of error * @return Buffer or Null in case of error
*/ */
readFile: function (/**Object*/ entry, /*String, Buffer*/ pass) { readFile: function (entry, pass) {
var item = getEntry(entry); var item = getEntry(entry);
return (item && item.getData(pass)) || null; return (item && item.getData(pass)) || null;
}, },
/**
* Returns how many child elements has on entry (directories) on files it is always 0
* @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry
* @returns {integer}
*/
childCount: function (entry) {
const item = getEntry(entry);
if (item) {
return _zip.getChildCount(item);
}
},
/** /**
* Asynchronous readFile * Asynchronous readFile
* @param entry ZipEntry object or String with the full path of the entry * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry
* @param callback * @param {callback} callback
* *
* @return Buffer or Null in case of error * @return Buffer or Null in case of error
*/ */
readFileAsync: function (/**Object*/ entry, /**Function*/ callback) { readFileAsync: function (entry, callback) {
var item = getEntry(entry); var item = getEntry(entry);
if (item) { if (item) {
item.getDataAsync(callback); item.getDataAsync(callback);
@ -114,12 +153,12 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Extracts the given entry from the archive and returns the content as plain text in the given encoding * Extracts the given entry from the archive and returns the content as plain text in the given encoding
* @param entry ZipEntry object or String with the full path of the entry * @param {ZipEntry|string} entry - ZipEntry object or String with the full path of the entry
* @param encoding Optional. If no encoding is specified utf8 is used * @param {string} encoding - Optional. If no encoding is specified utf8 is used
* *
* @return String * @return String
*/ */
readAsText: function (/**Object*/ entry, /**String=*/ encoding) { readAsText: function (entry, encoding) {
var item = getEntry(entry); var item = getEntry(entry);
if (item) { if (item) {
var data = item.getData(); var data = item.getData();
@ -132,13 +171,13 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Asynchronous readAsText * Asynchronous readAsText
* @param entry ZipEntry object or String with the full path of the entry * @param {ZipEntry|string} entry ZipEntry object or String with the full path of the entry
* @param callback * @param {callback} callback
* @param encoding Optional. If no encoding is specified utf8 is used * @param {string} [encoding] - Optional. If no encoding is specified utf8 is used
* *
* @return String * @return String
*/ */
readAsTextAsync: function (/**Object*/ entry, /**Function*/ callback, /**String=*/ encoding) { readAsTextAsync: function (entry, callback, encoding) {
var item = getEntry(entry); var item = getEntry(entry);
if (item) { if (item) {
item.getDataAsync(function (data, err) { item.getDataAsync(function (data, err) {
@ -161,11 +200,26 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory * Remove the entry from the file or the entry and all it's nested directories and files if the given entry is a directory
* *
* @param entry * @param {ZipEntry|string} entry
* @returns {void}
*/ */
deleteFile: function (/**Object*/ entry) { deleteFile: function (entry, withsubfolders = true) {
// @TODO: test deleteFile // @TODO: test deleteFile
var item = getEntry(entry); var item = getEntry(entry);
if (item) {
_zip.deleteFile(item.entryName, withsubfolders);
}
},
/**
* Remove the entry from the file or directory without affecting any nested entries
*
* @param {ZipEntry|string} entry
* @returns {void}
*/
deleteEntry: function (entry) {
// @TODO: test deleteEntry
var item = getEntry(entry);
if (item) { if (item) {
_zip.deleteEntry(item.entryName); _zip.deleteEntry(item.entryName);
} }
@ -174,9 +228,9 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Adds a comment to the zip. The zip must be rewritten after adding the comment. * Adds a comment to the zip. The zip must be rewritten after adding the comment.
* *
* @param comment * @param {string} comment
*/ */
addZipComment: function (/**String*/ comment) { addZipComment: function (comment) {
// @TODO: test addZipComment // @TODO: test addZipComment
_zip.comment = comment; _zip.comment = comment;
}, },
@ -194,10 +248,10 @@ module.exports = function (/**String*/ input, /** object */ options) {
* Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment * Adds a comment to a specified zipEntry. The zip must be rewritten after adding the comment
* The comment cannot exceed 65535 characters in length * The comment cannot exceed 65535 characters in length
* *
* @param entry * @param {ZipEntry} entry
* @param comment * @param {string} comment
*/ */
addZipEntryComment: function (/**Object*/ entry, /**String*/ comment) { addZipEntryComment: function (entry, comment) {
var item = getEntry(entry); var item = getEntry(entry);
if (item) { if (item) {
item.comment = comment; item.comment = comment;
@ -207,10 +261,10 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Returns the comment of the specified entry * Returns the comment of the specified entry
* *
* @param entry * @param {ZipEntry} entry
* @return String * @return String
*/ */
getZipEntryComment: function (/**Object*/ entry) { getZipEntryComment: function (entry) {
var item = getEntry(entry); var item = getEntry(entry);
if (item) { if (item) {
return item.comment || ""; return item.comment || "";
@ -221,10 +275,10 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content * Updates the content of an existing entry inside the archive. The zip must be rewritten after updating the content
* *
* @param entry * @param {ZipEntry} entry
* @param content * @param {Buffer} content
*/ */
updateFile: function (/**Object*/ entry, /**Buffer*/ content) { updateFile: function (entry, content) {
var item = getEntry(entry); var item = getEntry(entry);
if (item) { if (item) {
item.setData(content); item.setData(content);
@ -234,17 +288,18 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Adds a file from the disk to the archive * Adds a file from the disk to the archive
* *
* @param localPath File to add to zip * @param {string} localPath File to add to zip
* @param zipPath Optional path inside the zip * @param {string} [zipPath] Optional path inside the zip
* @param zipName Optional name for the file * @param {string} [zipName] Optional name for the file
* @param {string} [comment] Optional file comment
*/ */
addLocalFile: function (/**String*/ localPath, /**String=*/ zipPath, /**String=*/ zipName, /**String*/ comment) { addLocalFile: function (localPath, zipPath, zipName, comment) {
if (filetools.fs.existsSync(localPath)) { if (filetools.fs.existsSync(localPath)) {
// fix ZipPath // fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : ""; zipPath = zipPath ? fixPath(zipPath) : "";
// p - local file name // p - local file name
var p = localPath.split("\\").join("/").split("/").pop(); const p = pth.win32.basename(pth.win32.normalize(localPath));
// add file name into zippath // add file name into zippath
zipPath += zipName ? zipName : p; zipPath += zipName ? zipName : p;
@ -252,37 +307,77 @@ module.exports = function (/**String*/ input, /** object */ options) {
// read file attributes // read file attributes
const _attr = filetools.fs.statSync(localPath); const _attr = filetools.fs.statSync(localPath);
// get file content
const data = _attr.isFile() ? filetools.fs.readFileSync(localPath) : Buffer.alloc(0);
// if folder
if (_attr.isDirectory()) zipPath += filetools.sep;
// add file into zip file // add file into zip file
this.addFile(zipPath, filetools.fs.readFileSync(localPath), comment, _attr); this.addFile(zipPath, data, comment, _attr);
} else { } else {
throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); throw Utils.Errors.FILE_NOT_FOUND(localPath);
} }
}, },
/**
* Callback for showing if everything was done.
*
* @callback doneCallback
* @param {Error} err - Error object
* @param {boolean} done - was request fully completed
*/
/**
* Adds a file from the disk to the archive
*
* @param {(object|string)} options - options object, if it is string it us used as localPath.
* @param {string} options.localPath - Local path to the file.
* @param {string} [options.comment] - Optional file comment.
* @param {string} [options.zipPath] - Optional path inside the zip
* @param {string} [options.zipName] - Optional name for the file
* @param {doneCallback} callback - The callback that handles the response.
*/
addLocalFileAsync: function (options, callback) {
options = typeof options === "object" ? options : { localPath: options };
const localPath = pth.resolve(options.localPath);
const { comment } = options;
let { zipPath, zipName } = options;
const self = this;
filetools.fs.stat(localPath, function (err, stats) {
if (err) return callback(err, false);
// fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : "";
// p - local file name
const p = pth.win32.basename(pth.win32.normalize(localPath));
// add file name into zippath
zipPath += zipName ? zipName : p;
if (stats.isFile()) {
filetools.fs.readFile(localPath, function (err, data) {
if (err) return callback(err, false);
self.addFile(zipPath, data, comment, stats);
return setImmediate(callback, undefined, true);
});
} else if (stats.isDirectory()) {
zipPath += filetools.sep;
self.addFile(zipPath, Buffer.alloc(0), comment, stats);
return setImmediate(callback, undefined, true);
}
});
},
/** /**
* Adds a local directory and all its nested files and directories to the archive * Adds a local directory and all its nested files and directories to the archive
* *
* @param localPath * @param {string} localPath - local path to the folder
* @param zipPath optional path inside zip * @param {string} [zipPath] - optional path inside zip
* @param filter optional RegExp or Function if files match will * @param {(RegExp|function)} [filter] - optional RegExp or Function if files match will be included.
* be included.
* @param {number | object} attr - number as unix file permissions, object as filesystem Stats object
*/ */
addLocalFolder: function (/**String*/ localPath, /**String=*/ zipPath, /**=RegExp|Function*/ filter, /**=number|object*/ attr) { addLocalFolder: function (localPath, zipPath, filter) {
// Prepare filter // Prepare filter
if (filter instanceof RegExp) { filter = filenameFilter(filter);
// if filter is RegExp wrap it
filter = (function (rx) {
return function (filename) {
return rx.test(filename);
};
})(filter);
} else if ("function" !== typeof filter) {
// if filter is not function we will replace it
filter = function () {
return true;
};
}
// fix ZipPath // fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : ""; zipPath = zipPath ? fixPath(zipPath) : "";
@ -295,43 +390,29 @@ module.exports = function (/**String*/ input, /** object */ options) {
const self = this; const self = this;
if (items.length) { if (items.length) {
items.forEach(function (filepath) { for (const filepath of items) {
var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix const p = pth.join(zipPath, relativePath(localPath, filepath));
if (filter(p)) { if (filter(p)) {
var stats = filetools.fs.statSync(filepath); self.addLocalFile(filepath, pth.dirname(p));
if (stats.isFile()) {
self.addFile(zipPath + p, filetools.fs.readFileSync(filepath), "", attr ? attr : stats);
} else {
self.addFile(zipPath + p + "/", Buffer.alloc(0), "", attr ? attr : stats);
}
} }
}); }
} }
} else { } else {
throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); throw Utils.Errors.FILE_NOT_FOUND(localPath);
} }
}, },
/** /**
* Asynchronous addLocalFile * Asynchronous addLocalFolder
* @param localPath * @param {string} localPath
* @param callback * @param {callback} callback
* @param zipPath optional path inside zip * @param {string} [zipPath] optional path inside zip
* @param filter optional RegExp or Function if files match will * @param {RegExp|function} [filter] optional RegExp or Function if files match will
* be included. * be included.
*/ */
addLocalFolderAsync: function (/*String*/ localPath, /*Function*/ callback, /*String*/ zipPath, /*RegExp|Function*/ filter) { addLocalFolderAsync: function (localPath, callback, zipPath, filter) {
if (filter instanceof RegExp) { // Prepare filter
filter = (function (rx) { filter = filenameFilter(filter);
return function (filename) {
return rx.test(filename);
};
})(filter);
} else if ("function" !== typeof filter) {
filter = function () {
return true;
};
}
// fix ZipPath // fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : ""; zipPath = zipPath ? fixPath(zipPath) : "";
@ -342,7 +423,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
var self = this; var self = this;
filetools.fs.open(localPath, "r", function (err) { filetools.fs.open(localPath, "r", function (err) {
if (err && err.code === "ENOENT") { if (err && err.code === "ENOENT") {
callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath)); callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));
} else if (err) { } else if (err) {
callback(undefined, err); callback(undefined, err);
} else { } else {
@ -353,7 +434,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
i += 1; i += 1;
if (i < items.length) { if (i < items.length) {
var filepath = items[i]; var filepath = items[i];
var p = pth.relative(localPath, filepath).split("\\").join("/"); //windows fix var p = relativePath(localPath, filepath).split("\\").join("/"); //windows fix
p = p p = p
.normalize("NFD") .normalize("NFD")
.replace(/[\u0300-\u036f]/g, "") .replace(/[\u0300-\u036f]/g, "")
@ -391,24 +472,99 @@ module.exports = function (/**String*/ input, /** object */ options) {
}, },
/** /**
* Adds a local directory and all its nested files and directories to the archive
*
* @param {object | string} options - options object, if it is string it us used as localPath.
* @param {string} options.localPath - Local path to the folder.
* @param {string} [options.zipPath] - optional path inside zip.
* @param {RegExp|function} [options.filter] - optional RegExp or Function if files match will be included.
* @param {function|string} [options.namefix] - optional function to help fix filename
* @param {doneCallback} callback - The callback that handles the response.
*
*/
addLocalFolderAsync2: function (options, callback) {
const self = this;
options = typeof options === "object" ? options : { localPath: options };
localPath = pth.resolve(fixPath(options.localPath));
let { zipPath, filter, namefix } = options;
if (filter instanceof RegExp) {
filter = (function (rx) {
return function (filename) {
return rx.test(filename);
};
})(filter);
} else if ("function" !== typeof filter) {
filter = function () {
return true;
};
}
// fix ZipPath
zipPath = zipPath ? fixPath(zipPath) : "";
// Check Namefix function
if (namefix == "latin1") {
namefix = (str) =>
str
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^\x20-\x7E]/g, ""); // accent fix (latin1 characers only)
}
if (typeof namefix !== "function") namefix = (str) => str;
// internal, create relative path + fix the name
const relPathFix = (entry) => pth.join(zipPath, namefix(relativePath(localPath, entry)));
const fileNameFix = (entry) => pth.win32.basename(pth.win32.normalize(namefix(entry)));
filetools.fs.open(localPath, "r", function (err) {
if (err && err.code === "ENOENT") {
callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));
} else if (err) {
callback(undefined, err);
} else {
filetools.findFilesAsync(localPath, function (err, fileEntries) {
if (err) return callback(err);
fileEntries = fileEntries.filter((dir) => filter(relPathFix(dir)));
if (!fileEntries.length) callback(undefined, false);
setImmediate(
fileEntries.reverse().reduce(function (next, entry) {
return function (err, done) {
if (err || done === false) return setImmediate(next, err, false);
self.addLocalFileAsync(
{
localPath: entry,
zipPath: pth.dirname(relPathFix(entry)),
zipName: fileNameFix(entry)
},
next
);
};
}, callback)
);
});
}
});
},
/**
* Adds a local directory and all its nested files and directories to the archive
* *
* @param {string} localPath - path where files will be extracted * @param {string} localPath - path where files will be extracted
* @param {object} props - optional properties * @param {object} props - optional properties
* @param {string} props.zipPath - optional path inside zip * @param {string} [props.zipPath] - optional path inside zip
* @param {regexp, function} props.filter - RegExp or Function if files match will be included. * @param {RegExp|function} [props.filter] - optional RegExp or Function if files match will be included.
* @param {function|string} [props.namefix] - optional function to help fix filename
*/ */
addLocalFolderPromise: function (/*String*/ localPath, /* object */ props) { addLocalFolderPromise: function (localPath, props) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const { filter, zipPath } = Object.assign({}, props); this.addLocalFolderAsync2(Object.assign({ localPath }, props), (err, done) => {
this.addLocalFolderAsync( if (err) reject(err);
localPath, if (done) resolve(this);
(done, err) => { });
if (err) reject(err);
if (done) resolve(this);
},
zipPath,
filter
);
}); });
}, },
@ -419,17 +575,18 @@ module.exports = function (/**String*/ input, /** object */ options) {
* *
* @param {string} entryName * @param {string} entryName
* @param {Buffer | string} content - file content as buffer or utf8 coded string * @param {Buffer | string} content - file content as buffer or utf8 coded string
* @param {string} comment - file comment * @param {string} [comment] - file comment
* @param {number | object} attr - number as unix file permissions, object as filesystem Stats object * @param {number | object} [attr] - number as unix file permissions, object as filesystem Stats object
*/ */
addFile: function (/**String*/ entryName, /**Buffer*/ content, /**String*/ comment, /**Number*/ attr) { addFile: function (entryName, content, comment, attr) {
entryName = zipnamefix(entryName);
let entry = getEntry(entryName); let entry = getEntry(entryName);
const update = entry != null; const update = entry != null;
// prepare new entry // prepare new entry
if (!update) { if (!update) {
entry = new ZipEntry(); entry = new ZipEntry(opts);
entry.entryName = Utils.canonical(entryName); entry.entryName = entryName;
} }
entry.comment = comment || ""; entry.comment = comment || "";
@ -471,9 +628,10 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Returns an array of ZipEntry objects representing the files and folders inside the archive * Returns an array of ZipEntry objects representing the files and folders inside the archive
* *
* @return Array * @param {string} [password]
* @returns Array
*/ */
getEntries: function (/**String*/ password) { getEntries: function (password) {
_zip.password = password; _zip.password = password;
return _zip ? _zip.entries : []; return _zip ? _zip.entries : [];
}, },
@ -481,7 +639,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Returns a ZipEntry object representing the file or folder specified by ``name``. * Returns a ZipEntry object representing the file or folder specified by ``name``.
* *
* @param name * @param {string} name
* @return ZipEntry * @return ZipEntry
*/ */
getEntry: function (/**String*/ name) { getEntry: function (/**String*/ name) {
@ -500,34 +658,24 @@ module.exports = function (/**String*/ input, /** object */ options) {
* Extracts the given entry to the given targetPath * Extracts the given entry to the given targetPath
* If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted * If the entry is a directory inside the archive, the entire directory and it's subdirectories will be extracted
* *
* @param entry ZipEntry object or String with the full path of the entry * @param {string|ZipEntry} entry - ZipEntry object or String with the full path of the entry
* @param targetPath Target folder where to write the file * @param {string} targetPath - Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is inside a folder, the entry folder * @param {boolean} [maintainEntryPath=true] - If maintainEntryPath is true and the entry is inside a folder, the entry folder will be created in targetPath as well. Default is TRUE
* will be created in targetPath as well. Default is TRUE * @param {boolean} [overwrite=false] - If the file already exists at the target path, the file will be overwriten if this is true.
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. * @param {boolean} [keepOriginalPermission=false] - The file will be set as the permission from the entry if this is true.
* Default is FALSE * @param {string} [outFileName] - String If set will override the filename of the extracted file (Only works if the entry is a file)
* @param keepOriginalPermission The file will be set as the permission from the entry if this is true.
* Default is FALSE
* @param outFileName String If set will override the filename of the extracted file (Only works if the entry is a file)
* *
* @return Boolean * @return Boolean
*/ */
extractEntryTo: function ( extractEntryTo: function (entry, targetPath, maintainEntryPath, overwrite, keepOriginalPermission, outFileName) {
/**Object*/ entry, overwrite = get_Bool(false, overwrite);
/**String*/ targetPath, keepOriginalPermission = get_Bool(false, keepOriginalPermission);
/**Boolean*/ maintainEntryPath, maintainEntryPath = get_Bool(true, maintainEntryPath);
/**Boolean*/ overwrite, outFileName = get_Str(keepOriginalPermission, outFileName);
/**Boolean*/ keepOriginalPermission,
/**String**/ outFileName
) {
overwrite = get_Bool(overwrite, false);
keepOriginalPermission = get_Bool(keepOriginalPermission, false);
maintainEntryPath = get_Bool(maintainEntryPath, true);
outFileName = get_Str(outFileName, get_Str(keepOriginalPermission, undefined));
var item = getEntry(entry); var item = getEntry(entry);
if (!item) { if (!item) {
throw new Error(Utils.Errors.NO_ENTRY); throw Utils.Errors.NO_ENTRY();
} }
var entryName = canonical(item.entryName); var entryName = canonical(item.entryName);
@ -540,7 +688,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
if (child.isDirectory) return; if (child.isDirectory) return;
var content = child.getData(); var content = child.getData();
if (!content) { if (!content) {
throw new Error(Utils.Errors.CANT_EXTRACT_FILE); throw Utils.Errors.CANT_EXTRACT_FILE();
} }
var name = canonical(child.entryName); var name = canonical(child.entryName);
var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name)); var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name));
@ -552,10 +700,10 @@ module.exports = function (/**String*/ input, /** object */ options) {
} }
var content = item.getData(_zip.password); var content = item.getData(_zip.password);
if (!content) throw new Error(Utils.Errors.CANT_EXTRACT_FILE); if (!content) throw Utils.Errors.CANT_EXTRACT_FILE();
if (filetools.fs.existsSync(target) && !overwrite) { if (filetools.fs.existsSync(target) && !overwrite) {
throw new Error(Utils.Errors.CANT_OVERRIDE); throw Utils.Errors.CANT_OVERRIDE();
} }
// The reverse operation for attr depend on method addFile() // The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
@ -566,7 +714,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Test the archive * Test the archive
* * @param {string} [pass]
*/ */
test: function (pass) { test: function (pass) {
if (!_zip) { if (!_zip) {
@ -592,28 +740,28 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Extracts the entire archive to the given location * Extracts the entire archive to the given location
* *
* @param targetPath Target location * @param {string} targetPath Target location
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true.
* Default is FALSE * Default is FALSE
* @param keepOriginalPermission The file will be set as the permission from the entry if this is true. * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true.
* Default is FALSE * Default is FALSE
* @param {string|Buffer} [pass] password
*/ */
extractAllTo: function (/**String*/ targetPath, /**Boolean*/ overwrite, /**Boolean*/ keepOriginalPermission, /*String, Buffer*/ pass) { extractAllTo: function (targetPath, overwrite, keepOriginalPermission, pass) {
overwrite = get_Bool(overwrite, false); keepOriginalPermission = get_Bool(false, keepOriginalPermission);
pass = get_Str(keepOriginalPermission, pass); pass = get_Str(keepOriginalPermission, pass);
keepOriginalPermission = get_Bool(keepOriginalPermission, false); overwrite = get_Bool(false, overwrite);
if (!_zip) { if (!_zip) throw Utils.Errors.NO_ZIP();
throw new Error(Utils.Errors.NO_ZIP);
}
_zip.entries.forEach(function (entry) { _zip.entries.forEach(function (entry) {
var entryName = sanitize(targetPath, canonical(entry.entryName.toString())); var entryName = sanitize(targetPath, canonical(entry.entryName));
if (entry.isDirectory) { if (entry.isDirectory) {
filetools.makeDir(entryName); filetools.makeDir(entryName);
return; return;
} }
var content = entry.getData(pass); var content = entry.getData(pass);
if (!content) { if (!content) {
throw new Error(Utils.Errors.CANT_EXTRACT_FILE); throw Utils.Errors.CANT_EXTRACT_FILE();
} }
// The reverse operation for attr depend on method addFile() // The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
@ -621,7 +769,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
try { try {
filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time); filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time);
} catch (err) { } catch (err) {
throw new Error(Utils.Errors.CANT_EXTRACT_FILE); throw Utils.Errors.CANT_EXTRACT_FILE();
} }
}); });
}, },
@ -629,18 +777,17 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Asynchronous extractAllTo * Asynchronous extractAllTo
* *
* @param targetPath Target location * @param {string} targetPath Target location
* @param overwrite If the file already exists at the target path, the file will be overwriten if this is true. * @param {boolean} [overwrite=false] If the file already exists at the target path, the file will be overwriten if this is true.
* Default is FALSE * Default is FALSE
* @param keepOriginalPermission The file will be set as the permission from the entry if this is true. * @param {boolean} [keepOriginalPermission=false] The file will be set as the permission from the entry if this is true.
* Default is FALSE * Default is FALSE
* @param callback The callback will be executed when all entries are extracted successfully or any error is thrown. * @param {function} callback The callback will be executed when all entries are extracted successfully or any error is thrown.
*/ */
extractAllToAsync: function (/**String*/ targetPath, /**Boolean*/ overwrite, /**Boolean*/ keepOriginalPermission, /**Function*/ callback) { extractAllToAsync: function (targetPath, overwrite, keepOriginalPermission, callback) {
if (typeof overwrite === "function" && !callback) callback = overwrite; callback = get_Fun(overwrite, keepOriginalPermission, callback);
overwrite = get_Bool(overwrite, false); keepOriginalPermission = get_Bool(false, keepOriginalPermission);
if (typeof keepOriginalPermission === "function" && !callback) callback = keepOriginalPermission; overwrite = get_Bool(false, overwrite);
keepOriginalPermission = get_Bool(keepOriginalPermission, false);
if (!callback) { if (!callback) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function (err) { this.extractAllToAsync(targetPath, overwrite, keepOriginalPermission, function (err) {
@ -653,13 +800,13 @@ module.exports = function (/**String*/ input, /** object */ options) {
}); });
} }
if (!_zip) { if (!_zip) {
callback(new Error(Utils.Errors.NO_ZIP)); callback(Utils.Errors.NO_ZIP());
return; return;
} }
targetPath = pth.resolve(targetPath); targetPath = pth.resolve(targetPath);
// convert entryName to // convert entryName to
const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName.toString()))); const getPath = (entry) => sanitize(targetPath, pth.normalize(canonical(entry.entryName)));
const getError = (msg, file) => new Error(msg + ': "' + file + '"'); const getError = (msg, file) => new Error(msg + ': "' + file + '"');
// separate directories from files // separate directories from files
@ -694,13 +841,13 @@ module.exports = function (/**String*/ input, /** object */ options) {
if (err) { if (err) {
next(err); next(err);
} else { } else {
const entryName = pth.normalize(canonical(entry.entryName.toString())); const entryName = pth.normalize(canonical(entry.entryName));
const filePath = sanitize(targetPath, entryName); const filePath = sanitize(targetPath, entryName);
entry.getDataAsync(function (content, err_1) { entry.getDataAsync(function (content, err_1) {
if (err_1) { if (err_1) {
next(new Error(err_1)); next(err_1);
} else if (!content) { } else if (!content) {
next(new Error(Utils.Errors.CANT_EXTRACT_FILE)); next(Utils.Errors.CANT_EXTRACT_FILE());
} else { } else {
// The reverse operation for attr depend on method addFile() // The reverse operation for attr depend on method addFile()
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined; const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
@ -726,10 +873,10 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip * Writes the newly created zip file to disk at the specified location or if a zip was opened and no ``targetFileName`` is provided, it will overwrite the opened zip
* *
* @param targetFileName * @param {string} targetFileName
* @param callback * @param {function} callback
*/ */
writeZip: function (/**String*/ targetFileName, /**Function*/ callback) { writeZip: function (targetFileName, callback) {
if (arguments.length === 1) { if (arguments.length === 1) {
if (typeof targetFileName === "function") { if (typeof targetFileName === "function") {
callback = targetFileName; callback = targetFileName;
@ -749,6 +896,15 @@ module.exports = function (/**String*/ input, /** object */ options) {
} }
}, },
/**
*
* @param {string} targetFileName
* @param {object} [props]
* @param {boolean} [props.overwrite=true] If the file already exists at the target path, the file will be overwriten if this is true.
* @param {boolean} [props.perm] The file will be set as the permission from the entry if this is true.
* @returns {Promise<void>}
*/
writeZipPromise: function (/**String*/ targetFileName, /* object */ props) { writeZipPromise: function (/**String*/ targetFileName, /* object */ props) {
const { overwrite, perm } = Object.assign({ overwrite: true }, props); const { overwrite, perm } = Object.assign({ overwrite: true }, props);
@ -764,6 +920,9 @@ module.exports = function (/**String*/ input, /** object */ options) {
}); });
}, },
/**
* @returns {Promise<Buffer>} A promise to the Buffer.
*/
toBufferPromise: function () { toBufferPromise: function () {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
_zip.toAsyncBuffer(resolve, reject); _zip.toAsyncBuffer(resolve, reject);
@ -773,10 +932,13 @@ module.exports = function (/**String*/ input, /** object */ options) {
/** /**
* Returns the content of the entire zip file as a Buffer object * Returns the content of the entire zip file as a Buffer object
* *
* @return Buffer * @prop {function} [onSuccess]
* @prop {function} [onFail]
* @prop {function} [onItemStart]
* @prop {function} [onItemEnd]
* @returns {Buffer}
*/ */
toBuffer: function (/**Function=*/ onSuccess, /**Function=*/ onFail, /**Function=*/ onItemStart, /**Function=*/ onItemEnd) { toBuffer: function (onSuccess, onFail, onItemStart, onItemEnd) {
this.valueOf = 2;
if (typeof onSuccess === "function") { if (typeof onSuccess === "function") {
_zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd); _zip.toAsyncBuffer(onSuccess, onFail, onItemStart, onItemEnd);
return null; return null;

View file

@ -25,21 +25,16 @@ module.exports = function () {
// Without it file names may be corrupted for other apps when file names use unicode chars // Without it file names may be corrupted for other apps when file names use unicode chars
_flags |= Constants.FLG_EFS; _flags |= Constants.FLG_EFS;
var _localHeader = {}; const _localHeader = {
extraLen: 0
};
function setTime(val) { // casting
val = new Date(val); const uint32 = (val) => Math.max(0, val) >>> 0;
_time = const uint16 = (val) => Math.max(0, val) & 0xffff;
(((val.getFullYear() - 1980) & 0x7f) << 25) | // b09-16 years from 1980 const uint8 = (val) => Math.max(0, val) & 0xff;
((val.getMonth() + 1) << 21) | // b05-08 month
(val.getDate() << 16) | // b00-04 hour
// 2 bytes time
(val.getHours() << 11) | // b11-15 hour
(val.getMinutes() << 5) | // b05-10 minute
(val.getSeconds() >> 1); // b00-04 seconds divided by 2
}
setTime(+new Date()); _time = Utils.fromDate2DOS(new Date());
return { return {
get made() { get made() {
@ -63,6 +58,28 @@ module.exports = function () {
_flags = val; _flags = val;
}, },
get flags_efs() {
return (_flags & Constants.FLG_EFS) > 0;
},
set flags_efs(val) {
if (val) {
_flags |= Constants.FLG_EFS;
} else {
_flags &= ~Constants.FLG_EFS;
}
},
get flags_desc() {
return (_flags & Constants.FLG_DESC) > 0;
},
set flags_desc(val) {
if (val) {
_flags |= Constants.FLG_DESC;
} else {
_flags &= ~Constants.FLG_DESC;
}
},
get method() { get method() {
return _method; return _method;
}, },
@ -78,33 +95,41 @@ module.exports = function () {
}, },
get time() { get time() {
return new Date(((_time >> 25) & 0x7f) + 1980, ((_time >> 21) & 0x0f) - 1, (_time >> 16) & 0x1f, (_time >> 11) & 0x1f, (_time >> 5) & 0x3f, (_time & 0x1f) << 1); return Utils.fromDOS2Date(this.timeval);
}, },
set time(val) { set time(val) {
setTime(val); this.timeval = Utils.fromDate2DOS(val);
}, },
get timeval() {
return _time;
},
set timeval(val) {
_time = uint32(val);
},
get timeHighByte() { get timeHighByte() {
return (_time >>> 8) & 0xff; return uint8(_time >>> 8);
}, },
get crc() { get crc() {
return _crc; return _crc;
}, },
set crc(val) { set crc(val) {
_crc = Math.max(0, val) >>> 0; _crc = uint32(val);
}, },
get compressedSize() { get compressedSize() {
return _compressedSize; return _compressedSize;
}, },
set compressedSize(val) { set compressedSize(val) {
_compressedSize = Math.max(0, val) >>> 0; _compressedSize = uint32(val);
}, },
get size() { get size() {
return _size; return _size;
}, },
set size(val) { set size(val) {
_size = Math.max(0, val) >>> 0; _size = uint32(val);
}, },
get fileNameLength() { get fileNameLength() {
@ -121,6 +146,13 @@ module.exports = function () {
_extraLen = val; _extraLen = val;
}, },
get extraLocalLength() {
return _localHeader.extraLen;
},
set extraLocalLength(val) {
_localHeader.extraLen = val;
},
get commentLength() { get commentLength() {
return _comLen; return _comLen;
}, },
@ -132,37 +164,37 @@ module.exports = function () {
return _diskStart; return _diskStart;
}, },
set diskNumStart(val) { set diskNumStart(val) {
_diskStart = Math.max(0, val) >>> 0; _diskStart = uint32(val);
}, },
get inAttr() { get inAttr() {
return _inattr; return _inattr;
}, },
set inAttr(val) { set inAttr(val) {
_inattr = Math.max(0, val) >>> 0; _inattr = uint32(val);
}, },
get attr() { get attr() {
return _attr; return _attr;
}, },
set attr(val) { set attr(val) {
_attr = Math.max(0, val) >>> 0; _attr = uint32(val);
}, },
// get Unix file permissions // get Unix file permissions
get fileAttr() { get fileAttr() {
return _attr ? (((_attr >>> 0) | 0) >> 16) & 0xfff : 0; return uint16(_attr >> 16) & 0xfff;
}, },
get offset() { get offset() {
return _offset; return _offset;
}, },
set offset(val) { set offset(val) {
_offset = Math.max(0, val) >>> 0; _offset = uint32(val);
}, },
get encrypted() { get encrypted() {
return (_flags & 1) === 1; return (_flags & Constants.FLG_ENC) === Constants.FLG_ENC;
}, },
get centralHeaderSize() { get centralHeaderSize() {
@ -181,34 +213,38 @@ module.exports = function () {
var data = input.slice(_offset, _offset + Constants.LOCHDR); var data = input.slice(_offset, _offset + Constants.LOCHDR);
// 30 bytes and should start with "PK\003\004" // 30 bytes and should start with "PK\003\004"
if (data.readUInt32LE(0) !== Constants.LOCSIG) { if (data.readUInt32LE(0) !== Constants.LOCSIG) {
throw new Error(Utils.Errors.INVALID_LOC); throw Utils.Errors.INVALID_LOC();
} }
_localHeader = {
// version needed to extract // version needed to extract
version: data.readUInt16LE(Constants.LOCVER), _localHeader.version = data.readUInt16LE(Constants.LOCVER);
// general purpose bit flag // general purpose bit flag
flags: data.readUInt16LE(Constants.LOCFLG), _localHeader.flags = data.readUInt16LE(Constants.LOCFLG);
// compression method // compression method
method: data.readUInt16LE(Constants.LOCHOW), _localHeader.method = data.readUInt16LE(Constants.LOCHOW);
// modification time (2 bytes time, 2 bytes date) // modification time (2 bytes time, 2 bytes date)
time: data.readUInt32LE(Constants.LOCTIM), _localHeader.time = data.readUInt32LE(Constants.LOCTIM);
// uncompressed file crc-32 value // uncompressed file crc-32 valu
crc: data.readUInt32LE(Constants.LOCCRC), _localHeader.crc = data.readUInt32LE(Constants.LOCCRC);
// compressed size // compressed size
compressedSize: data.readUInt32LE(Constants.LOCSIZ), _localHeader.compressedSize = data.readUInt32LE(Constants.LOCSIZ);
// uncompressed size // uncompressed size
size: data.readUInt32LE(Constants.LOCLEN), _localHeader.size = data.readUInt32LE(Constants.LOCLEN);
// filename length // filename length
fnameLen: data.readUInt16LE(Constants.LOCNAM), _localHeader.fnameLen = data.readUInt16LE(Constants.LOCNAM);
// extra field length // extra field length
extraLen: data.readUInt16LE(Constants.LOCEXT) _localHeader.extraLen = data.readUInt16LE(Constants.LOCEXT);
};
// read extra data
const extraStart = _offset + Constants.LOCHDR + _localHeader.fnameLen;
const extraEnd = extraStart + _localHeader.extraLen;
return input.slice(extraStart, extraEnd);
}, },
loadFromBinary: function (/*Buffer*/ data) { loadFromBinary: function (/*Buffer*/ data) {
// data should be 46 bytes and start with "PK 01 02" // data should be 46 bytes and start with "PK 01 02"
if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) { if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {
throw new Error(Utils.Errors.INVALID_CEN); throw Utils.Errors.INVALID_CEN();
} }
// version made by // version made by
_verMade = data.readUInt16LE(Constants.CENVEM); _verMade = data.readUInt16LE(Constants.CENVEM);
@ -264,7 +300,7 @@ module.exports = function () {
// filename length // filename length
data.writeUInt16LE(_fnameLen, Constants.LOCNAM); data.writeUInt16LE(_fnameLen, Constants.LOCNAM);
// extra field length // extra field length
data.writeUInt16LE(_extraLen, Constants.LOCEXT); data.writeUInt16LE(_localHeader.extraLen, Constants.LOCEXT);
return data; return data;
}, },
@ -303,8 +339,6 @@ module.exports = function () {
data.writeUInt32LE(_attr, Constants.CENATX); data.writeUInt32LE(_attr, Constants.CENATX);
// LOC header offset // LOC header offset
data.writeUInt32LE(_offset, Constants.CENOFF); data.writeUInt32LE(_offset, Constants.CENOFF);
// fill all with
data.fill(0x00, Constants.CENHDR);
return data; return data;
}, },

View file

@ -56,7 +56,7 @@ module.exports = function () {
(data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) && (data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) &&
(data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG) (data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)
) { ) {
throw new Error(Utils.Errors.INVALID_END); throw Utils.Errors.INVALID_END();
} }
if (data.readUInt32LE(0) === Constants.ENDSIG) { if (data.readUInt32LE(0) === Constants.ENDSIG) {

View file

@ -3,6 +3,7 @@
// node crypt, we use it for generate salt // node crypt, we use it for generate salt
// eslint-disable-next-line node/no-unsupported-features/node-builtins // eslint-disable-next-line node/no-unsupported-features/node-builtins
const { randomFillSync } = require("crypto"); const { randomFillSync } = require("crypto");
const Errors = require("../util/errors");
// generate CRC32 lookup table // generate CRC32 lookup table
const crctable = new Uint32Array(256).map((t, crc) => { const crctable = new Uint32Array(256).map((t, crc) => {
@ -124,7 +125,7 @@ function decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) {
//3. does password meet expectations //3. does password meet expectations
if (salt[11] !== verifyByte) { if (salt[11] !== verifyByte) {
throw "ADM-ZIP: Wrong Password"; throw Errors.WRONG_PASSWORD();
} }
// 4. decode content // 4. decode content

5
node_modules/adm-zip/package.json generated vendored
View file

@ -1,6 +1,6 @@
{ {
"name": "adm-zip", "name": "adm-zip",
"version": "0.5.14", "version": "0.5.15",
"description": "Javascript implementation of zip for nodejs with support for electron original-fs. Allows user to create or extract zip files both in memory or to/from disk", "description": "Javascript implementation of zip for nodejs with support for electron original-fs. Allows user to create or extract zip files both in memory or to/from disk",
"scripts": { "scripts": {
"test": "mocha -R spec", "test": "mocha -R spec",
@ -41,8 +41,9 @@
}, },
"devDependencies": { "devDependencies": {
"chai": "^4.3.4", "chai": "^4.3.4",
"iconv-lite": "^0.6.3",
"mocha": "^10.2.0", "mocha": "^10.2.0",
"prettier": "^2.2.1", "prettier": "^3.3.2",
"rimraf": "^3.0.2" "rimraf": "^3.0.2"
} }
} }

5
node_modules/adm-zip/util/decoder.js generated vendored Normal file
View file

@ -0,0 +1,5 @@
module.exports = {
efs: true,
encode: (data) => Buffer.from(data, "utf8"),
decode: (data) => data.toString("utf8")
};

37
node_modules/adm-zip/util/errors.js generated vendored
View file

@ -1,13 +1,18 @@
module.exports = { const errors = {
/* Header error messages */ /* Header error messages */
INVALID_LOC: "Invalid LOC header (bad signature)", INVALID_LOC: "Invalid LOC header (bad signature)",
INVALID_CEN: "Invalid CEN header (bad signature)", INVALID_CEN: "Invalid CEN header (bad signature)",
INVALID_END: "Invalid END header (bad signature)", INVALID_END: "Invalid END header (bad signature)",
/* Descriptor */
DESCRIPTOR_NOT_EXIST: "No descriptor present",
DESCRIPTOR_UNKNOWN: "Unknown descriptor format",
DESCRIPTOR_FAULTY: "Descriptor data is malformed",
/* ZipEntry error messages*/ /* ZipEntry error messages*/
NO_DATA: "Nothing to decompress", NO_DATA: "Nothing to decompress",
BAD_CRC: "CRC32 checksum failed", BAD_CRC: "CRC32 checksum failed {0}",
FILE_IN_THE_WAY: "There is a file in the way: %s", FILE_IN_THE_WAY: "There is a file in the way: {0}",
UNKNOWN_METHOD: "Invalid/unsupported compression method", UNKNOWN_METHOD: "Invalid/unsupported compression method",
/* Inflater error messages */ /* Inflater error messages */
@ -29,8 +34,30 @@ module.exports = {
NO_ZIP: "No zip file was loaded", NO_ZIP: "No zip file was loaded",
NO_ENTRY: "Entry doesn't exist", NO_ENTRY: "Entry doesn't exist",
DIRECTORY_CONTENT_ERROR: "A directory cannot have content", DIRECTORY_CONTENT_ERROR: "A directory cannot have content",
FILE_NOT_FOUND: "File not found: %s", FILE_NOT_FOUND: 'File not found: "{0}"',
NOT_IMPLEMENTED: "Not implemented", NOT_IMPLEMENTED: "Not implemented",
INVALID_FILENAME: "Invalid filename", INVALID_FILENAME: "Invalid filename",
INVALID_FORMAT: "Invalid or unsupported zip format. No END header found" INVALID_FORMAT: "Invalid or unsupported zip format. No END header found",
INVALID_PASS_PARAM: "Incompatible password parameter",
WRONG_PASSWORD: "Wrong Password",
/* ADM-ZIP */
COMMENT_TOO_LONG: "Comment is too long", // Comment can be max 65535 bytes long (NOTE: some non-US characters may take more space)
EXTRA_FIELD_PARSE_ERROR: "Extra field parsing error"
}; };
// template
function E(message) {
return function (...args) {
if (args.length) { // Allow {0} .. {9} arguments in error message, based on argument number
message = message.replace(/\{(\d)\}/g, (_, n) => args[n] || '');
}
return new Error('ADM-ZIP: ' + message);
};
}
// Init errors with template
for (const msg of Object.keys(errors)) {
exports[msg] = E(errors[msg]);
}

5
node_modules/adm-zip/util/fattr.js generated vendored
View file

@ -1,9 +1,6 @@
const fs = require("./fileSystem").require();
const pth = require("path"); const pth = require("path");
fs.existsSync = fs.existsSync || pth.existsSync; module.exports = function (/*String*/ path, /*Utils object*/ { fs }) {
module.exports = function (/*String*/ path) {
var _path = path || "", var _path = path || "",
_obj = newAttr(), _obj = newAttr(),
_stat = null; _stat = null;

View file

@ -1,11 +0,0 @@
exports.require = function () {
if (typeof process === "object" && process.versions && process.versions["electron"]) {
try {
const originalFs = require("original-fs");
if (Object.keys(originalFs).length > 0) {
return originalFs;
}
} catch (e) {}
}
return require("fs");
};

1
node_modules/adm-zip/util/index.js generated vendored
View file

@ -2,3 +2,4 @@ module.exports = require("./utils");
module.exports.Constants = require("./constants"); module.exports.Constants = require("./constants");
module.exports.Errors = require("./errors"); module.exports.Errors = require("./errors");
module.exports.FileAttr = require("./fattr"); module.exports.FileAttr = require("./fattr");
module.exports.decoder = require("./decoder");

137
node_modules/adm-zip/util/utils.js generated vendored
View file

@ -1,10 +1,10 @@
const fsystem = require("./fileSystem").require(); const fsystem = require("fs");
const pth = require("path"); const pth = require("path");
const Constants = require("./constants"); const Constants = require("./constants");
const Errors = require("./errors"); const Errors = require("./errors");
const isWin = typeof process === "object" && "win32" === process.platform; const isWin = typeof process === "object" && "win32" === process.platform;
const is_Obj = (obj) => obj && typeof obj === "object"; const is_Obj = (obj) => typeof obj === "object" && obj !== null;
// generate CRC32 lookup table // generate CRC32 lookup table
const crcTable = new Uint32Array(256).map((t, c) => { const crcTable = new Uint32Array(256).map((t, c) => {
@ -34,7 +34,7 @@ function Utils(opts) {
module.exports = Utils; module.exports = Utils;
// INSTANCED functions // INSTANTIABLE functions
Utils.prototype.makeDir = function (/*String*/ folder) { Utils.prototype.makeDir = function (/*String*/ folder) {
const self = this; const self = this;
@ -51,7 +51,7 @@ Utils.prototype.makeDir = function (/*String*/ folder) {
} catch (e) { } catch (e) {
self.fs.mkdirSync(resolvedPath); self.fs.mkdirSync(resolvedPath);
} }
if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath); if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`);
}); });
} }
@ -75,10 +75,10 @@ Utils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*B
var fd; var fd;
try { try {
fd = self.fs.openSync(path, "w", 438); // 0666 fd = self.fs.openSync(path, "w", 0o666); // 0666
} catch (e) { } catch (e) {
self.fs.chmodSync(path, 438); self.fs.chmodSync(path, 0o666);
fd = self.fs.openSync(path, "w", 438); fd = self.fs.openSync(path, "w", 0o666);
} }
if (fd) { if (fd) {
try { try {
@ -87,7 +87,7 @@ Utils.prototype.writeFileTo = function (/*String*/ path, /*Buffer*/ content, /*B
self.fs.closeSync(fd); self.fs.closeSync(fd);
} }
} }
self.fs.chmodSync(path, attr || 438); self.fs.chmodSync(path, attr || 0o666);
return true; return true;
}; };
@ -111,13 +111,13 @@ Utils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content
self.fs.exists(folder, function (exists) { self.fs.exists(folder, function (exists) {
if (!exists) self.makeDir(folder); if (!exists) self.makeDir(folder);
self.fs.open(path, "w", 438, function (err, fd) { self.fs.open(path, "w", 0o666, function (err, fd) {
if (err) { if (err) {
self.fs.chmod(path, 438, function () { self.fs.chmod(path, 0o666, function () {
self.fs.open(path, "w", 438, function (err, fd) { self.fs.open(path, "w", 0o666, function (err, fd) {
self.fs.write(fd, content, 0, content.length, 0, function () { self.fs.write(fd, content, 0, content.length, 0, function () {
self.fs.close(fd, function () { self.fs.close(fd, function () {
self.fs.chmod(path, attr || 438, function () { self.fs.chmod(path, attr || 0o666, function () {
callback(true); callback(true);
}); });
}); });
@ -127,13 +127,13 @@ Utils.prototype.writeFileToAsync = function (/*String*/ path, /*Buffer*/ content
} else if (fd) { } else if (fd) {
self.fs.write(fd, content, 0, content.length, 0, function () { self.fs.write(fd, content, 0, content.length, 0, function () {
self.fs.close(fd, function () { self.fs.close(fd, function () {
self.fs.chmod(path, attr || 438, function () { self.fs.chmod(path, attr || 0o666, function () {
callback(true); callback(true);
}); });
}); });
}); });
} else { } else {
self.fs.chmod(path, attr || 438, function () { self.fs.chmod(path, attr || 0o666, function () {
callback(true); callback(true);
}); });
} }
@ -153,13 +153,14 @@ Utils.prototype.findFiles = function (/*String*/ path) {
} }
let files = []; let files = [];
self.fs.readdirSync(dir).forEach(function (file) { self.fs.readdirSync(dir).forEach(function (file) {
var path = pth.join(dir, file); const path = pth.join(dir, file);
const stat = self.fs.statSync(path);
if (self.fs.statSync(path).isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive));
if (!pattern || pattern.test(path)) { if (!pattern || pattern.test(path)) {
files.push(pth.normalize(path) + (self.fs.statSync(path).isDirectory() ? self.sep : "")); files.push(pth.normalize(path) + (stat.isDirectory() ? self.sep : ""));
} }
if (stat.isDirectory() && recursive) files = files.concat(findSync(path, pattern, recursive));
}); });
return files; return files;
} }
@ -167,6 +168,47 @@ Utils.prototype.findFiles = function (/*String*/ path) {
return findSync(path, undefined, true); return findSync(path, undefined, true);
}; };
/**
* Callback for showing if everything was done.
*
* @callback filelistCallback
* @param {Error} err - Error object
* @param {string[]} list - was request fully completed
*/
/**
*
* @param {string} dir
* @param {filelistCallback} cb
*/
Utils.prototype.findFilesAsync = function (dir, cb) {
const self = this;
let results = [];
self.fs.readdir(dir, function (err, list) {
if (err) return cb(err);
let list_length = list.length;
if (!list_length) return cb(null, results);
list.forEach(function (file) {
file = pth.join(dir, file);
self.fs.stat(file, function (err, stat) {
if (err) return cb(err);
if (stat) {
results.push(pth.normalize(file) + (stat.isDirectory() ? self.sep : ""));
if (stat.isDirectory()) {
self.findFilesAsync(file, function (err, res) {
if (err) return cb(err);
results = results.concat(res);
if (!--list_length) cb(null, results);
});
} else {
if (!--list_length) cb(null, results);
}
}
});
});
});
};
Utils.prototype.getAttributes = function () {}; Utils.prototype.getAttributes = function () {};
Utils.prototype.setAttributes = function () {}; Utils.prototype.setAttributes = function () {};
@ -182,8 +224,6 @@ Utils.crc32 = function (buf) {
if (typeof buf === "string") { if (typeof buf === "string") {
buf = Buffer.from(buf, "utf8"); buf = Buffer.from(buf, "utf8");
} }
// Generate crcTable
if (!crcTable.length) genCRCTable();
let len = buf.length; let len = buf.length;
let crc = ~0; let crc = ~0;
@ -203,14 +243,49 @@ Utils.methodToString = function (/*Number*/ method) {
} }
}; };
// removes ".." style path elements /**
* removes ".." style path elements
* @param {string} path - fixable path
* @returns string - fixed filepath
*/
Utils.canonical = function (/*string*/ path) { Utils.canonical = function (/*string*/ path) {
if (!path) return ""; if (!path) return "";
// trick normalize think path is absolute // trick normalize think path is absolute
var safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/")); const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/"));
return pth.join(".", safeSuffix); return pth.join(".", safeSuffix);
}; };
/**
* fix file names in achive
* @param {string} path - fixable path
* @returns string - fixed filepath
*/
Utils.zipnamefix = function (path) {
if (!path) return "";
// trick normalize think path is absolute
const safeSuffix = pth.posix.normalize("/" + path.split("\\").join("/"));
return pth.posix.join(".", safeSuffix);
};
/**
*
* @param {Array} arr
* @param {function} callback
* @returns
*/
Utils.findLast = function (arr, callback) {
if (!Array.isArray(arr)) throw new TypeError("arr is not array");
const len = arr.length >>> 0;
for (let i = len - 1; i >= 0; i--) {
if (callback(arr[i], i, arr)) {
return arr[i];
}
}
return void 0;
};
// make abolute paths taking prefix as root folder // make abolute paths taking prefix as root folder
Utils.sanitize = function (/*string*/ prefix, /*string*/ name) { Utils.sanitize = function (/*string*/ prefix, /*string*/ name) {
prefix = pth.resolve(pth.normalize(prefix)); prefix = pth.resolve(pth.normalize(prefix));
@ -225,14 +300,14 @@ Utils.sanitize = function (/*string*/ prefix, /*string*/ name) {
}; };
// converts buffer, Uint8Array, string types to buffer // converts buffer, Uint8Array, string types to buffer
Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input) { Utils.toBuffer = function toBuffer(/*buffer, Uint8Array, string*/ input, /* function */ encoder) {
if (Buffer.isBuffer(input)) { if (Buffer.isBuffer(input)) {
return input; return input;
} else if (input instanceof Uint8Array) { } else if (input instanceof Uint8Array) {
return Buffer.from(input); return Buffer.from(input);
} else { } else {
// expect string all other values are invalid and return empty buffer // expect string all other values are invalid and return empty buffer
return typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.alloc(0); return typeof input === "string" ? encoder(input) : Buffer.alloc(0);
} }
}; };
@ -243,5 +318,19 @@ Utils.readBigUInt64LE = function (/*Buffer*/ buffer, /*int*/ index) {
return parseInt(`0x${slice.toString("hex")}`); return parseInt(`0x${slice.toString("hex")}`);
}; };
Utils.fromDOS2Date = function (val) {
return new Date(((val >> 25) & 0x7f) + 1980, Math.max(((val >> 21) & 0x0f) - 1, 0), Math.max((val >> 16) & 0x1f, 1), (val >> 11) & 0x1f, (val >> 5) & 0x3f, (val & 0x1f) << 1);
};
Utils.fromDate2DOS = function (val) {
let date = 0;
let time = 0;
if (val.getFullYear() > 1979) {
date = (((val.getFullYear() - 1980) & 0x7f) << 9) | ((val.getMonth() + 1) << 5) | val.getDate();
time = (val.getHours() << 11) | (val.getMinutes() << 5) | (val.getSeconds() >> 1);
}
return (date << 16) | time;
};
Utils.isWin = isWin; // Do we have windows system Utils.isWin = isWin; // Do we have windows system
Utils.crcTable = crcTable; Utils.crcTable = crcTable;

139
node_modules/adm-zip/zipEntry.js generated vendored
View file

@ -3,33 +3,72 @@ var Utils = require("./util"),
Constants = Utils.Constants, Constants = Utils.Constants,
Methods = require("./methods"); Methods = require("./methods");
module.exports = function (/*Buffer*/ input) { module.exports = function (/** object */ options, /*Buffer*/ input) {
var _centralHeader = new Headers.EntryHeader(), var _centralHeader = new Headers.EntryHeader(),
_entryName = Buffer.alloc(0), _entryName = Buffer.alloc(0),
_comment = Buffer.alloc(0), _comment = Buffer.alloc(0),
_isDirectory = false, _isDirectory = false,
uncompressedData = null, uncompressedData = null,
_extra = Buffer.alloc(0); _extra = Buffer.alloc(0),
_extralocal = Buffer.alloc(0),
_efs = true;
// assign options
const opts = options;
const decoder = typeof opts.decoder === "object" ? opts.decoder : Utils.decoder;
_efs = decoder.hasOwnProperty("efs") ? decoder.efs : false;
function getCompressedDataFromZip() { function getCompressedDataFromZip() {
//if (!input || !Buffer.isBuffer(input)) { //if (!input || !Buffer.isBuffer(input)) {
if (!input || !(input instanceof Uint8Array)) { if (!input || !(input instanceof Uint8Array)) {
return Buffer.alloc(0); return Buffer.alloc(0);
} }
_centralHeader.loadLocalHeaderFromBinary(input); _extralocal = _centralHeader.loadLocalHeaderFromBinary(input);
return input.slice(_centralHeader.realDataOffset, _centralHeader.realDataOffset + _centralHeader.compressedSize); return input.slice(_centralHeader.realDataOffset, _centralHeader.realDataOffset + _centralHeader.compressedSize);
} }
function crc32OK(data) { function crc32OK(data) {
// if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the header is written // if bit 3 (0x08) of the general-purpose flags field is set, then the CRC-32 and file sizes are not known when the local header is written
if ((_centralHeader.flags & 0x8) !== 0x8) { if (!_centralHeader.flags_desc) {
if (Utils.crc32(data) !== _centralHeader.localHeader.crc) { if (Utils.crc32(data) !== _centralHeader.localHeader.crc) {
return false; return false;
} }
} else { } else {
// @TODO: load and check data descriptor header const descriptor = {};
// The fields in the local header are filled with zero, and the CRC-32 and size are appended in a 12-byte structure const dataEndOffset = _centralHeader.realDataOffset + _centralHeader.compressedSize;
// (optionally preceded by a 4-byte signature) immediately after the compressed data: // no descriptor after compressed data, instead new local header
if (input.readUInt32LE(dataEndOffset) == Constants.LOCSIG || input.readUInt32LE(dataEndOffset) == Constants.CENSIG) {
throw Utils.Errors.DESCRIPTOR_NOT_EXIST();
}
// get decriptor data
if (input.readUInt32LE(dataEndOffset) == Constants.EXTSIG) {
// descriptor with signature
descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC);
descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ);
descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN);
} else if (input.readUInt16LE(dataEndOffset + 12) === 0x4b50) {
// descriptor without signature (we check is new header starting where we expect)
descriptor.crc = input.readUInt32LE(dataEndOffset + Constants.EXTCRC - 4);
descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ - 4);
descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN - 4);
} else {
throw Utils.Errors.DESCRIPTOR_UNKNOWN();
}
// check data integrity
if (descriptor.compressedSize !== _centralHeader.compressedSize || descriptor.size !== _centralHeader.size || descriptor.crc !== _centralHeader.crc) {
throw Utils.Errors.DESCRIPTOR_FAULTY();
}
if (Utils.crc32(data) !== descriptor.crc) {
return false;
}
// @TODO: zip64 bit descriptor fields
// if bit 3 is set and any value in local header "zip64 Extended information" extra field are set 0 (place holder)
// then 64-bit descriptor format is used instead of 32-bit
// central header - "zip64 Extended information" extra field should store real values and not place holders
} }
return true; return true;
} }
@ -41,7 +80,7 @@ module.exports = function (/*Buffer*/ input) {
} }
if (_isDirectory) { if (_isDirectory) {
if (async && callback) { if (async && callback) {
callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR); //si added error. callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR()); //si added error.
} }
return Buffer.alloc(0); return Buffer.alloc(0);
} }
@ -56,7 +95,7 @@ module.exports = function (/*Buffer*/ input) {
if (_centralHeader.encrypted) { if (_centralHeader.encrypted) {
if ("string" !== typeof pass && !Buffer.isBuffer(pass)) { if ("string" !== typeof pass && !Buffer.isBuffer(pass)) {
throw new Error("ADM-ZIP: Incompatible password parameter"); throw Utils.Errors.INVALID_PASS_PARAM();
} }
compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass); compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass);
} }
@ -67,8 +106,8 @@ module.exports = function (/*Buffer*/ input) {
case Utils.Constants.STORED: case Utils.Constants.STORED:
compressedData.copy(data); compressedData.copy(data);
if (!crc32OK(data)) { if (!crc32OK(data)) {
if (async && callback) callback(data, Utils.Errors.BAD_CRC); //si added error if (async && callback) callback(data, Utils.Errors.BAD_CRC()); //si added error
throw new Error(Utils.Errors.BAD_CRC); throw Utils.Errors.BAD_CRC();
} else { } else {
//si added otherwise did not seem to return data. //si added otherwise did not seem to return data.
if (async && callback) callback(data); if (async && callback) callback(data);
@ -80,7 +119,7 @@ module.exports = function (/*Buffer*/ input) {
const result = inflater.inflate(data); const result = inflater.inflate(data);
result.copy(data, 0); result.copy(data, 0);
if (!crc32OK(data)) { if (!crc32OK(data)) {
throw new Error(Utils.Errors.BAD_CRC + " " + _entryName.toString()); throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`);
} }
return data; return data;
} else { } else {
@ -88,7 +127,7 @@ module.exports = function (/*Buffer*/ input) {
result.copy(result, 0); result.copy(result, 0);
if (callback) { if (callback) {
if (!crc32OK(result)) { if (!crc32OK(result)) {
callback(result, Utils.Errors.BAD_CRC); //si added error callback(result, Utils.Errors.BAD_CRC()); //si added error
} else { } else {
callback(result); callback(result);
} }
@ -97,8 +136,8 @@ module.exports = function (/*Buffer*/ input) {
} }
break; break;
default: default:
if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD); if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD());
throw new Error(Utils.Errors.UNKNOWN_METHOD); throw Utils.Errors.UNKNOWN_METHOD();
} }
} }
@ -151,18 +190,22 @@ module.exports = function (/*Buffer*/ input) {
} }
function parseExtra(data) { function parseExtra(data) {
var offset = 0; try {
var signature, size, part; var offset = 0;
while (offset < data.length) { var signature, size, part;
signature = data.readUInt16LE(offset); while (offset + 4 < data.length) {
offset += 2; signature = data.readUInt16LE(offset);
size = data.readUInt16LE(offset); offset += 2;
offset += 2; size = data.readUInt16LE(offset);
part = data.slice(offset, offset + size); offset += 2;
offset += size; part = data.slice(offset, offset + size);
if (Constants.ID_ZIP64 === signature) { offset += size;
parseZip64ExtendedInformation(part); if (Constants.ID_ZIP64 === signature) {
parseZip64ExtendedInformation(part);
}
} }
} catch (error) {
throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR();
} }
} }
@ -198,18 +241,26 @@ module.exports = function (/*Buffer*/ input) {
return { return {
get entryName() { get entryName() {
return _entryName.toString(); return decoder.decode(_entryName);
}, },
get rawEntryName() { get rawEntryName() {
return _entryName; return _entryName;
}, },
set entryName(val) { set entryName(val) {
_entryName = Utils.toBuffer(val); _entryName = Utils.toBuffer(val, decoder.encode);
var lastChar = _entryName[_entryName.length - 1]; var lastChar = _entryName[_entryName.length - 1];
_isDirectory = lastChar === 47 || lastChar === 92; _isDirectory = lastChar === 47 || lastChar === 92;
_centralHeader.fileNameLength = _entryName.length; _centralHeader.fileNameLength = _entryName.length;
}, },
get efs() {
if (typeof _efs === "function") {
return _efs(this.entryName);
} else {
return _efs;
}
},
get extra() { get extra() {
return _extra; return _extra;
}, },
@ -220,15 +271,16 @@ module.exports = function (/*Buffer*/ input) {
}, },
get comment() { get comment() {
return _comment.toString(); return decoder.decode(_comment);
}, },
set comment(val) { set comment(val) {
_comment = Utils.toBuffer(val); _comment = Utils.toBuffer(val, decoder.encode);
_centralHeader.commentLength = _comment.length; _centralHeader.commentLength = _comment.length;
if (_comment.length > 0xffff) throw Utils.Errors.COMMENT_TOO_LONG();
}, },
get name() { get name() {
var n = _entryName.toString(); var n = decoder.decode(_entryName);
return _isDirectory return _isDirectory
? n ? n
.substr(n.length - 1) .substr(n.length - 1)
@ -249,7 +301,7 @@ module.exports = function (/*Buffer*/ input) {
}, },
setData: function (value) { setData: function (value) {
uncompressedData = Utils.toBuffer(value); uncompressedData = Utils.toBuffer(value, Utils.decoder.encode);
if (!_isDirectory && uncompressedData.length) { if (!_isDirectory && uncompressedData.length) {
_centralHeader.size = uncompressedData.length; _centralHeader.size = uncompressedData.length;
_centralHeader.method = Utils.Constants.DEFLATED; _centralHeader.method = Utils.Constants.DEFLATED;
@ -293,6 +345,8 @@ module.exports = function (/*Buffer*/ input) {
}, },
packCentralHeader: function () { packCentralHeader: function () {
_centralHeader.flags_efs = this.efs;
_centralHeader.extraLength = _extra.length;
// 1. create header (buffer) // 1. create header (buffer)
var header = _centralHeader.centralHeaderToBinary(); var header = _centralHeader.centralHeaderToBinary();
var addpos = Utils.Constants.CENHDR; var addpos = Utils.Constants.CENHDR;
@ -300,24 +354,21 @@ module.exports = function (/*Buffer*/ input) {
_entryName.copy(header, addpos); _entryName.copy(header, addpos);
addpos += _entryName.length; addpos += _entryName.length;
// 3. add extra data // 3. add extra data
if (_centralHeader.extraLength) { _extra.copy(header, addpos);
_extra.copy(header, addpos); addpos += _centralHeader.extraLength;
addpos += _centralHeader.extraLength;
}
// 4. add file comment // 4. add file comment
if (_centralHeader.commentLength) { _comment.copy(header, addpos);
_comment.copy(header, addpos);
}
return header; return header;
}, },
packLocalHeader: function () { packLocalHeader: function () {
let addpos = 0; let addpos = 0;
_centralHeader.flags_efs = this.efs;
_centralHeader.extraLocalLength = _extralocal.length;
// 1. construct local header Buffer // 1. construct local header Buffer
const localHeaderBuf = _centralHeader.localHeaderToBinary(); const localHeaderBuf = _centralHeader.localHeaderToBinary();
// 2. localHeader - crate header buffer // 2. localHeader - crate header buffer
const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _extra.length); const localHeader = Buffer.alloc(localHeaderBuf.length + _entryName.length + _centralHeader.extraLocalLength);
// 2.1 add localheader // 2.1 add localheader
localHeaderBuf.copy(localHeader, addpos); localHeaderBuf.copy(localHeader, addpos);
addpos += localHeaderBuf.length; addpos += localHeaderBuf.length;
@ -325,8 +376,8 @@ module.exports = function (/*Buffer*/ input) {
_entryName.copy(localHeader, addpos); _entryName.copy(localHeader, addpos);
addpos += _entryName.length; addpos += _entryName.length;
// 2.3 add extra field // 2.3 add extra field
_extra.copy(localHeader, addpos); _extralocal.copy(localHeader, addpos);
addpos += _extra.length; addpos += _extralocal.length;
return localHeader; return localHeader;
}, },

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