This commit is contained in:
Lilith 2024-06-13 00:09:21 +02:00
parent eddf7cecb8
commit aea798d119
Signed by: lilith
GPG key ID: 8712A0F317C37175
16631 changed files with 1480363 additions and 257 deletions

1
home/ags/node_modules/.bin/acorn generated vendored Symbolic link
View file

@ -0,0 +1 @@
../acorn/bin/acorn

1
home/ags/node_modules/.bin/eslint generated vendored Symbolic link
View file

@ -0,0 +1 @@
../eslint/bin/eslint.js

1
home/ags/node_modules/.bin/js-yaml generated vendored Symbolic link
View file

@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js

1
home/ags/node_modules/.bin/json5 generated vendored Symbolic link
View file

@ -0,0 +1 @@
../json5/lib/cli.js

1
home/ags/node_modules/.bin/node-which generated vendored Symbolic link
View file

@ -0,0 +1 @@
../which/bin/node-which

1
home/ags/node_modules/.bin/resolve generated vendored Symbolic link
View file

@ -0,0 +1 @@
../resolve/bin/resolve

1
home/ags/node_modules/.bin/rimraf generated vendored Symbolic link
View file

@ -0,0 +1 @@
../rimraf/bin.js

1
home/ags/node_modules/.bin/semver generated vendored Symbolic link
View file

@ -0,0 +1 @@
../semver/bin/semver.js

1
home/ags/node_modules/.bin/tsc generated vendored Symbolic link
View file

@ -0,0 +1 @@
../typescript/bin/tsc

1
home/ags/node_modules/.bin/tsserver generated vendored Symbolic link
View file

@ -0,0 +1 @@
../typescript/bin/tsserver

3246
home/ags/node_modules/.package-lock.json generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

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

View file

@ -0,0 +1,37 @@
# @eslint-community/eslint-utils
[![npm version](https://img.shields.io/npm/v/@eslint-community/eslint-utils.svg)](https://www.npmjs.com/package/@eslint-community/eslint-utils)
[![Downloads/month](https://img.shields.io/npm/dm/@eslint-community/eslint-utils.svg)](http://www.npmtrends.com/@eslint-community/eslint-utils)
[![Build Status](https://github.com/eslint-community/eslint-utils/workflows/CI/badge.svg)](https://github.com/eslint-community/eslint-utils/actions)
[![Coverage Status](https://codecov.io/gh/eslint-community/eslint-utils/branch/main/graph/badge.svg)](https://codecov.io/gh/eslint-community/eslint-utils)
## 🏁 Goal
This package provides utility functions and classes for make ESLint custom rules.
For examples:
- [`getStaticValue`](https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstaticvalue) evaluates static value on AST.
- [`ReferenceTracker`](https://eslint-community.github.io/eslint-utils/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring.
## 📖 Usage
See [documentation](https://eslint-community.github.io/eslint-utils).
## 📰 Changelog
See [releases](https://github.com/eslint-community/eslint-utils/releases).
## ❤️ Contributing
Welcome contributing!
Please use GitHub's Issues/PRs.
### Development Tools
- `npm test` runs tests and measures coverage.
- `npm run clean` removes the coverage result of `npm test` command.
- `npm run coverage` shows the coverage result of the last `npm test` command.
- `npm run lint` runs ESLint.
- `npm run watch` runs tests on each file change.

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,73 @@
{
"name": "@eslint-community/eslint-utils",
"version": "4.4.0",
"description": "Utilities for ESLint plugins.",
"keywords": [
"eslint"
],
"homepage": "https://github.com/eslint-community/eslint-utils#readme",
"bugs": {
"url": "https://github.com/eslint-community/eslint-utils/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/eslint-community/eslint-utils"
},
"license": "MIT",
"author": "Toru Nagashima",
"sideEffects": false,
"exports": {
".": {
"import": "./index.mjs",
"require": "./index.js"
},
"./package.json": "./package.json"
},
"main": "index",
"module": "index.mjs",
"files": [
"index.*"
],
"scripts": {
"prebuild": "npm run -s clean",
"build": "rollup -c",
"clean": "rimraf .nyc_output coverage index.*",
"coverage": "opener ./coverage/lcov-report/index.html",
"docs:build": "vitepress build docs",
"docs:watch": "vitepress dev docs",
"format": "npm run -s format:prettier -- --write",
"format:prettier": "prettier .",
"format:check": "npm run -s format:prettier -- --check",
"lint": "eslint .",
"test": "c8 mocha --reporter dot \"test/*.mjs\"",
"preversion": "npm test && npm run -s build",
"postversion": "git push && git push --tags",
"prewatch": "npm run -s clean",
"watch": "warun \"{src,test}/**/*.mjs\" -- npm run -s test:mocha"
},
"dependencies": {
"eslint-visitor-keys": "^3.3.0"
},
"devDependencies": {
"@eslint-community/eslint-plugin-mysticatea": "^15.2.0",
"c8": "^7.12.0",
"dot-prop": "^6.0.1",
"eslint": "^8.28.0",
"mocha": "^9.2.2",
"npm-run-all": "^4.1.5",
"opener": "^1.5.2",
"prettier": "2.8.4",
"rimraf": "^3.0.2",
"rollup": "^2.79.1",
"rollup-plugin-sourcemaps": "^0.6.3",
"semver": "^7.3.8",
"vitepress": "^1.0.0-alpha.40",
"warun": "^1.0.0"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
}

View file

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

View file

@ -0,0 +1,177 @@
# @eslint-community/regexpp
[![npm version](https://img.shields.io/npm/v/@eslint-community/regexpp.svg)](https://www.npmjs.com/package/@eslint-community/regexpp)
[![Downloads/month](https://img.shields.io/npm/dm/@eslint-community/regexpp.svg)](http://www.npmtrends.com/@eslint-community/regexpp)
[![Build Status](https://github.com/eslint-community/regexpp/workflows/CI/badge.svg)](https://github.com/eslint-community/regexpp/actions)
[![codecov](https://codecov.io/gh/eslint-community/regexpp/branch/main/graph/badge.svg)](https://codecov.io/gh/eslint-community/regexpp)
A regular expression parser for ECMAScript.
## 💿 Installation
```bash
$ npm install @eslint-community/regexpp
```
- require Node@^12.0.0 || ^14.0.0 || >=16.0.0.
## 📖 Usage
```ts
import {
AST,
RegExpParser,
RegExpValidator,
RegExpVisitor,
parseRegExpLiteral,
validateRegExpLiteral,
visitRegExpAST
} from "@eslint-community/regexpp"
```
### parseRegExpLiteral(source, options?)
Parse a given regular expression literal then make AST object.
This is equivalent to `new RegExpParser(options).parseLiteral(source)`.
- **Parameters:**
- `source` (`string | RegExp`) The source code to parse.
- `options?` ([`RegExpParser.Options`]) The options to parse.
- **Return:**
- The AST of the regular expression.
### validateRegExpLiteral(source, options?)
Validate a given regular expression literal.
This is equivalent to `new RegExpValidator(options).validateLiteral(source)`.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `options?` ([`RegExpValidator.Options`]) The options to validate.
### visitRegExpAST(ast, handlers)
Visit each node of a given AST.
This is equivalent to `new RegExpVisitor(handlers).visit(ast)`.
- **Parameters:**
- `ast` ([`AST.Node`]) The AST to visit.
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
### RegExpParser
#### new RegExpParser(options?)
- **Parameters:**
- `options?` ([`RegExpParser.Options`]) The options to parse.
#### parser.parseLiteral(source, start?, end?)
Parse a regular expression literal.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"/abc/g"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- **Return:**
- The AST of the regular expression.
#### parser.parsePattern(source, start?, end?, flags?)
Parse a regular expression pattern.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"abc"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
- **Return:**
- The AST of the regular expression pattern.
#### parser.parseFlags(source, start?, end?)
Parse a regular expression flags.
- **Parameters:**
- `source` (`string`) The source code to parse. E.g. `"gim"`.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- **Return:**
- The AST of the regular expression flags.
### RegExpValidator
#### new RegExpValidator(options)
- **Parameters:**
- `options` ([`RegExpValidator.Options`]) The options to validate.
#### validator.validateLiteral(source, start, end)
Validate a regular expression literal.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
#### validator.validatePattern(source, start, end, flags)
Validate a regular expression pattern.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
#### validator.validateFlags(source, start, end)
Validate a regular expression flags.
- **Parameters:**
- `source` (`string`) The source code to validate.
- `start?` (`number`) The start index in the source code. Default is `0`.
- `end?` (`number`) The end index in the source code. Default is `source.length`.
### RegExpVisitor
#### new RegExpVisitor(handlers)
- **Parameters:**
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
#### visitor.visit(ast)
Validate a regular expression literal.
- **Parameters:**
- `ast` ([`AST.Node`]) The AST to visit.
## 📰 Changelog
- [GitHub Releases](https://github.com/eslint-community/regexpp/releases)
## 🍻 Contributing
Welcome contributing!
Please use GitHub's Issues/PRs.
### Development Tools
- `npm test` runs tests and measures coverage.
- `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`.
- `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`.
- `npm run lint` runs ESLint.
- `npm run update:test` updates test fixtures.
- `npm run update:ids` updates `src/unicode/ids.ts`.
- `npm run watch` runs tests with `--watch` option.
[`AST.Node`]: src/ast.ts#L4
[`RegExpParser.Options`]: src/parser.ts#L743
[`RegExpValidator.Options`]: src/validator.ts#L220
[`RegExpVisitor.Handlers`]: src/visitor.ts#L291

File diff suppressed because it is too large Load diff

2754
home/ags/node_modules/@eslint-community/regexpp/index.js generated vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

2744
home/ags/node_modules/@eslint-community/regexpp/index.mjs generated vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,91 @@
{
"name": "@eslint-community/regexpp",
"version": "4.10.1",
"description": "Regular expression parser for ECMAScript.",
"keywords": [
"regexp",
"regular",
"expression",
"parser",
"validator",
"ast",
"abstract",
"syntax",
"tree",
"ecmascript",
"es2015",
"es2016",
"es2017",
"es2018",
"es2019",
"es2020",
"es2021",
"annexB"
],
"homepage": "https://github.com/eslint-community/regexpp#readme",
"bugs": {
"url": "https://github.com/eslint-community/regexpp/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/eslint-community/regexpp"
},
"license": "MIT",
"author": "Toru Nagashima",
"exports": {
".": {
"types": "./index.d.ts",
"import": "./index.mjs",
"default": "./index.js"
},
"./package.json": "./package.json"
},
"main": "index",
"files": [
"index.*"
],
"scripts": {
"prebuild": "npm run -s clean",
"build": "run-s build:*",
"build:tsc": "tsc --module es2015",
"build:rollup": "rollup -c",
"build:dts": "npm run -s build:tsc -- --removeComments false && dts-bundle --name @eslint-community/regexpp --main .temp/index.d.ts --out ../index.d.ts && prettier --write index.d.ts",
"clean": "rimraf .temp index.*",
"lint": "eslint . --ext .ts",
"test": "nyc _mocha \"test/*.ts\" --reporter dot --timeout 10000",
"debug": "mocha --require ts-node/register/transpile-only \"test/*.ts\" --reporter dot --timeout 10000",
"update:test": "ts-node scripts/update-fixtures.ts",
"update:unicode": "run-s update:unicode:*",
"update:unicode:ids": "ts-node scripts/update-unicode-ids.ts",
"update:unicode:props": "ts-node scripts/update-unicode-properties.ts",
"update:test262:extract": "ts-node -T scripts/extract-test262.ts",
"preversion": "npm test && npm run -s build",
"postversion": "git push && git push --tags",
"prewatch": "npm run -s clean",
"watch": "_mocha \"test/*.ts\" --require ts-node/register --reporter dot --timeout 10000 --watch-extensions ts --watch --growl"
},
"dependencies": {},
"devDependencies": {
"@eslint-community/eslint-plugin-mysticatea": "^15.5.1",
"@rollup/plugin-node-resolve": "^14.1.0",
"@types/eslint": "^8.44.3",
"@types/jsdom": "^16.2.15",
"@types/mocha": "^9.1.1",
"@types/node": "^12.20.55",
"dts-bundle": "^0.7.3",
"eslint": "^8.50.0",
"js-tokens": "^8.0.2",
"jsdom": "^19.0.0",
"mocha": "^9.2.2",
"npm-run-all": "^4.1.5",
"nyc": "^14.1.1",
"rimraf": "^3.0.2",
"rollup": "^2.79.1",
"rollup-plugin-sourcemaps": "^0.6.3",
"ts-node": "^10.9.1",
"typescript": "~5.0.2"
},
"engines": {
"node": "^12.0.0 || ^14.0.0 || >=16.0.0"
}
}

19
home/ags/node_modules/@eslint/eslintrc/LICENSE generated vendored Normal file
View file

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

115
home/ags/node_modules/@eslint/eslintrc/README.md generated vendored Normal file
View file

@ -0,0 +1,115 @@
# ESLintRC Library
This repository contains the legacy ESLintRC configuration file format for ESLint. This package is not intended for use outside of the ESLint ecosystem. It is ESLint-specific and not intended for use in other programs.
**Note:** This package is frozen except for critical bug fixes as ESLint moves to a new config system.
## Installation
You can install the package as follows:
```
npm install @eslint/eslintrc --save-dev
# or
yarn add @eslint/eslintrc -D
```
## Usage (ESM)
The primary class in this package is `FlatCompat`, which is a utility to translate ESLintRC-style configs into flat configs. Here's how you use it inside of your `eslint.config.js` file:
```js
import { FlatCompat } from "@eslint/eslintrc";
import js from "@eslint/js";
import path from "path";
import { fileURLToPath } from "url";
// mimic CommonJS variables -- not needed if using CommonJS
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const compat = new FlatCompat({
baseDirectory: __dirname, // optional; default: process.cwd()
resolvePluginsRelativeTo: __dirname, // optional
recommendedConfig: js.configs.recommended, // optional
allConfig: js.configs.all, // optional
});
export default [
// mimic ESLintRC-style extends
...compat.extends("standard", "example"),
// mimic environments
...compat.env({
es2020: true,
node: true
}),
// mimic plugins
...compat.plugins("airbnb", "react"),
// translate an entire config
...compat.config({
plugins: ["airbnb", "react"],
extends: "standard",
env: {
es2020: true,
node: true
},
rules: {
semi: "error"
}
})
];
```
## Usage (CommonJS)
Using `FlatCompat` in CommonJS files is similar to ESM, but you'll use `require()` and `module.exports` instead of `import` and `export`. Here's how you use it inside of your `eslint.config.js` CommonJS file:
```js
const { FlatCompat } = require("@eslint/eslintrc");
const js = require("@eslint/js");
const compat = new FlatCompat({
baseDirectory: __dirname, // optional; default: process.cwd()
resolvePluginsRelativeTo: __dirname, // optional
recommendedConfig: js.configs.recommended, // optional
allConfig: js.configs.all, // optional
});
module.exports = [
// mimic ESLintRC-style extends
...compat.extends("standard", "example"),
// mimic environments
...compat.env({
es2020: true,
node: true
}),
// mimic plugins
...compat.plugins("airbnb", "react"),
// translate an entire config
...compat.config({
plugins: ["airbnb", "react"],
extends: "standard",
env: {
es2020: true,
node: true
},
rules: {
semi: "error"
}
})
];
```
## License
MIT License

View file

@ -0,0 +1,79 @@
/**
* @fileoverview Defines a schema for configs.
* @author Sylvan Mably
*/
const baseConfigProperties = {
$schema: { type: "string" },
env: { type: "object" },
extends: { $ref: "#/definitions/stringOrStrings" },
globals: { type: "object" },
overrides: {
type: "array",
items: { $ref: "#/definitions/overrideConfig" },
additionalItems: false
},
parser: { type: ["string", "null"] },
parserOptions: { type: "object" },
plugins: { type: "array" },
processor: { type: "string" },
rules: { type: "object" },
settings: { type: "object" },
noInlineConfig: { type: "boolean" },
reportUnusedDisableDirectives: { type: "boolean" },
ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
};
const configSchema = {
definitions: {
stringOrStrings: {
oneOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
additionalItems: false
}
]
},
stringOrStringsRequired: {
oneOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
additionalItems: false,
minItems: 1
}
]
},
// Config at top-level.
objectConfig: {
type: "object",
properties: {
root: { type: "boolean" },
ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
...baseConfigProperties
},
additionalProperties: false
},
// Config in `overrides`.
overrideConfig: {
type: "object",
properties: {
excludedFiles: { $ref: "#/definitions/stringOrStrings" },
files: { $ref: "#/definitions/stringOrStringsRequired" },
...baseConfigProperties
},
required: ["files"],
additionalProperties: false
}
},
$ref: "#/definitions/objectConfig"
};
export default configSchema;

View file

@ -0,0 +1,215 @@
/**
* @fileoverview Defines environment settings and globals.
* @author Elan Shanker
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import globals from "globals";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Get the object that has difference.
* @param {Record<string,boolean>} current The newer object.
* @param {Record<string,boolean>} prev The older object.
* @returns {Record<string,boolean>} The difference object.
*/
function getDiff(current, prev) {
const retv = {};
for (const [key, value] of Object.entries(current)) {
if (!Object.hasOwnProperty.call(prev, key)) {
retv[key] = value;
}
}
return retv;
}
const newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...
const newGlobals2017 = {
Atomics: false,
SharedArrayBuffer: false
};
const newGlobals2020 = {
BigInt: false,
BigInt64Array: false,
BigUint64Array: false,
globalThis: false
};
const newGlobals2021 = {
AggregateError: false,
FinalizationRegistry: false,
WeakRef: false
};
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/** @type {Map<string, import("../lib/shared/types").Environment>} */
export default new Map(Object.entries({
// Language
builtin: {
globals: globals.es5
},
es6: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 6
}
},
es2015: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 6
}
},
es2016: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 7
}
},
es2017: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 8
}
},
es2018: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 9
}
},
es2019: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 10
}
},
es2020: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
parserOptions: {
ecmaVersion: 11
}
},
es2021: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 12
}
},
es2022: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 13
}
},
es2023: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 14
}
},
es2024: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 15
}
},
// Platforms
browser: {
globals: globals.browser
},
node: {
globals: globals.node,
parserOptions: {
ecmaFeatures: {
globalReturn: true
}
}
},
"shared-node-browser": {
globals: globals["shared-node-browser"]
},
worker: {
globals: globals.worker
},
serviceworker: {
globals: globals.serviceworker
},
// Frameworks
commonjs: {
globals: globals.commonjs,
parserOptions: {
ecmaFeatures: {
globalReturn: true
}
}
},
amd: {
globals: globals.amd
},
mocha: {
globals: globals.mocha
},
jasmine: {
globals: globals.jasmine
},
jest: {
globals: globals.jest
},
phantomjs: {
globals: globals.phantomjs
},
jquery: {
globals: globals.jquery
},
qunit: {
globals: globals.qunit
},
prototypejs: {
globals: globals.prototypejs
},
shelljs: {
globals: globals.shelljs
},
meteor: {
globals: globals.meteor
},
mongo: {
globals: globals.mongo
},
protractor: {
globals: globals.protractor
},
applescript: {
globals: globals.applescript
},
nashorn: {
globals: globals.nashorn
},
atomtest: {
globals: globals.atomtest
},
embertest: {
globals: globals.embertest
},
webextensions: {
globals: globals.webextensions
},
greasemonkey: {
globals: globals.greasemonkey
}
}));

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

4344
home/ags/node_modules/@eslint/eslintrc/dist/eslintrc.cjs generated vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,532 @@
/**
* @fileoverview `CascadingConfigArrayFactory` class.
*
* `CascadingConfigArrayFactory` class has a responsibility:
*
* 1. Handles cascading of config files.
*
* It provides two methods:
*
* - `getConfigArrayForFile(filePath)`
* Get the corresponded configuration of a given file. This method doesn't
* throw even if the given file didn't exist.
* - `clearCache()`
* Clear the internal cache. You have to call this method when
* `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends
* on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import debugOrig from "debug";
import os from "os";
import path from "path";
import { ConfigArrayFactory } from "./config-array-factory.js";
import {
ConfigArray,
ConfigDependency,
IgnorePattern
} from "./config-array/index.js";
import ConfigValidator from "./shared/config-validator.js";
import { emitDeprecationWarning } from "./shared/deprecation-warnings.js";
const debug = debugOrig("eslintrc:cascading-config-array-factory");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// Define types for VSCode IntelliSense.
/** @typedef {import("./shared/types").ConfigData} ConfigData */
/** @typedef {import("./shared/types").Parser} Parser */
/** @typedef {import("./shared/types").Plugin} Plugin */
/** @typedef {import("./shared/types").Rule} Rule */
/** @typedef {ReturnType<ConfigArrayFactory["create"]>} ConfigArray */
/**
* @typedef {Object} CascadingConfigArrayFactoryOptions
* @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
* @property {ConfigData} [baseConfig] The config by `baseConfig` option.
* @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.
* @property {string} [cwd] The base directory to start lookup.
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
* @property {string[]} [rulePaths] The value of `--rulesdir` option.
* @property {string} [specificConfigPath] The value of `--config` option.
* @property {boolean} [useEslintrc] if `false` then it doesn't load config files.
* @property {Function} loadRules The function to use to load rules.
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
* @property {Object} [resolver=ModuleResolver] The module resolver object.
* @property {string} eslintAllPath The path to the definitions for eslint:all.
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
*/
/**
* @typedef {Object} CascadingConfigArrayFactoryInternalSlots
* @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.
* @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.
* @property {ConfigArray} cliConfigArray The config array of CLI options.
* @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.
* @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.
* @property {Map<string, ConfigArray>} configCache The cache from directory paths to config arrays.
* @property {string} cwd The base directory to start lookup.
* @property {WeakMap<ConfigArray, ConfigArray>} finalizeCache The cache from config arrays to finalized config arrays.
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
* @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.
* @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.
* @property {boolean} useEslintrc if `false` then it doesn't load config files.
* @property {Function} loadRules The function to use to load rules.
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
* @property {Object} [resolver=ModuleResolver] The module resolver object.
* @property {string} eslintAllPath The path to the definitions for eslint:all.
* @property {Function} getEslintAllConfig Returns the config data for eslint:all.
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
* @property {Function} getEslintRecommendedConfig Returns the config data for eslint:recommended.
*/
/** @type {WeakMap<CascadingConfigArrayFactory, CascadingConfigArrayFactoryInternalSlots>} */
const internalSlotsMap = new WeakMap();
/**
* Create the config array from `baseConfig` and `rulePaths`.
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
* @returns {ConfigArray} The config array of the base configs.
*/
function createBaseConfigArray({
configArrayFactory,
baseConfigData,
rulePaths,
cwd,
loadRules
}) {
const baseConfigArray = configArrayFactory.create(
baseConfigData,
{ name: "BaseConfig" }
);
/*
* Create the config array element for the default ignore patterns.
* This element has `ignorePattern` property that ignores the default
* patterns in the current working directory.
*/
baseConfigArray.unshift(configArrayFactory.create(
{ ignorePatterns: IgnorePattern.DefaultPatterns },
{ name: "DefaultIgnorePattern" }
)[0]);
/*
* Load rules `--rulesdir` option as a pseudo plugin.
* Use a pseudo plugin to define rules of `--rulesdir`, so we can validate
* the rule's options with only information in the config array.
*/
if (rulePaths && rulePaths.length > 0) {
baseConfigArray.push({
type: "config",
name: "--rulesdir",
filePath: "",
plugins: {
"": new ConfigDependency({
definition: {
rules: rulePaths.reduce(
(map, rulesPath) => Object.assign(
map,
loadRules(rulesPath, cwd)
),
{}
)
},
filePath: "",
id: "",
importerName: "--rulesdir",
importerPath: ""
})
}
});
}
return baseConfigArray;
}
/**
* Create the config array from CLI options.
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
* @returns {ConfigArray} The config array of the base configs.
*/
function createCLIConfigArray({
cliConfigData,
configArrayFactory,
cwd,
ignorePath,
specificConfigPath
}) {
const cliConfigArray = configArrayFactory.create(
cliConfigData,
{ name: "CLIOptions" }
);
cliConfigArray.unshift(
...(ignorePath
? configArrayFactory.loadESLintIgnore(ignorePath)
: configArrayFactory.loadDefaultESLintIgnore())
);
if (specificConfigPath) {
cliConfigArray.unshift(
...configArrayFactory.loadFile(
specificConfigPath,
{ name: "--config", basePath: cwd }
)
);
}
return cliConfigArray;
}
/**
* The error type when there are files matched by a glob, but all of them have been ignored.
*/
class ConfigurationNotFoundError extends Error {
// eslint-disable-next-line jsdoc/require-description
/**
* @param {string} directoryPath The directory path.
*/
constructor(directoryPath) {
super(`No ESLint configuration found in ${directoryPath}.`);
this.messageTemplate = "no-config-found";
this.messageData = { directoryPath };
}
}
/**
* This class provides the functionality that enumerates every file which is
* matched by given glob patterns and that configuration.
*/
class CascadingConfigArrayFactory {
/**
* Initialize this enumerator.
* @param {CascadingConfigArrayFactoryOptions} options The options.
*/
constructor({
additionalPluginPool = new Map(),
baseConfig: baseConfigData = null,
cliConfig: cliConfigData = null,
cwd = process.cwd(),
ignorePath,
resolvePluginsRelativeTo,
rulePaths = [],
specificConfigPath = null,
useEslintrc = true,
builtInRules = new Map(),
loadRules,
resolver,
eslintRecommendedPath,
getEslintRecommendedConfig,
eslintAllPath,
getEslintAllConfig
} = {}) {
const configArrayFactory = new ConfigArrayFactory({
additionalPluginPool,
cwd,
resolvePluginsRelativeTo,
builtInRules,
resolver,
eslintRecommendedPath,
getEslintRecommendedConfig,
eslintAllPath,
getEslintAllConfig
});
internalSlotsMap.set(this, {
baseConfigArray: createBaseConfigArray({
baseConfigData,
configArrayFactory,
cwd,
rulePaths,
loadRules
}),
baseConfigData,
cliConfigArray: createCLIConfigArray({
cliConfigData,
configArrayFactory,
cwd,
ignorePath,
specificConfigPath
}),
cliConfigData,
configArrayFactory,
configCache: new Map(),
cwd,
finalizeCache: new WeakMap(),
ignorePath,
rulePaths,
specificConfigPath,
useEslintrc,
builtInRules,
loadRules
});
}
/**
* The path to the current working directory.
* This is used by tests.
* @type {string}
*/
get cwd() {
const { cwd } = internalSlotsMap.get(this);
return cwd;
}
/**
* Get the config array of a given file.
* If `filePath` was not given, it returns the config which contains only
* `baseConfigData` and `cliConfigData`.
* @param {string} [filePath] The file path to a file.
* @param {Object} [options] The options.
* @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.
* @returns {ConfigArray} The config array of the file.
*/
getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {
const {
baseConfigArray,
cliConfigArray,
cwd
} = internalSlotsMap.get(this);
if (!filePath) {
return new ConfigArray(...baseConfigArray, ...cliConfigArray);
}
const directoryPath = path.dirname(path.resolve(cwd, filePath));
debug(`Load config files for ${directoryPath}.`);
return this._finalizeConfigArray(
this._loadConfigInAncestors(directoryPath),
directoryPath,
ignoreNotFoundError
);
}
/**
* Set the config data to override all configs.
* Require to call `clearCache()` method after this method is called.
* @param {ConfigData} configData The config data to override all configs.
* @returns {void}
*/
setOverrideConfig(configData) {
const slots = internalSlotsMap.get(this);
slots.cliConfigData = configData;
}
/**
* Clear config cache.
* @returns {void}
*/
clearCache() {
const slots = internalSlotsMap.get(this);
slots.baseConfigArray = createBaseConfigArray(slots);
slots.cliConfigArray = createCLIConfigArray(slots);
slots.configCache.clear();
}
/**
* Load and normalize config files from the ancestor directories.
* @param {string} directoryPath The path to a leaf directory.
* @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
* @returns {ConfigArray} The loaded config.
* @private
*/
_loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
const {
baseConfigArray,
configArrayFactory,
configCache,
cwd,
useEslintrc
} = internalSlotsMap.get(this);
if (!useEslintrc) {
return baseConfigArray;
}
let configArray = configCache.get(directoryPath);
// Hit cache.
if (configArray) {
debug(`Cache hit: ${directoryPath}.`);
return configArray;
}
debug(`No cache found: ${directoryPath}.`);
const homePath = os.homedir();
// Consider this is root.
if (directoryPath === homePath && cwd !== homePath) {
debug("Stop traversing because of considered root.");
if (configsExistInSubdirs) {
const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
if (filePath) {
emitDeprecationWarning(
filePath,
"ESLINT_PERSONAL_CONFIG_SUPPRESS"
);
}
}
return this._cacheConfig(directoryPath, baseConfigArray);
}
// Load the config on this directory.
try {
configArray = configArrayFactory.loadInDirectory(directoryPath);
} catch (error) {
/* istanbul ignore next */
if (error.code === "EACCES") {
debug("Stop traversing because of 'EACCES' error.");
return this._cacheConfig(directoryPath, baseConfigArray);
}
throw error;
}
if (configArray.length > 0 && configArray.isRoot()) {
debug("Stop traversing because of 'root:true'.");
configArray.unshift(...baseConfigArray);
return this._cacheConfig(directoryPath, configArray);
}
// Load from the ancestors and merge it.
const parentPath = path.dirname(directoryPath);
const parentConfigArray = parentPath && parentPath !== directoryPath
? this._loadConfigInAncestors(
parentPath,
configsExistInSubdirs || configArray.length > 0
)
: baseConfigArray;
if (configArray.length > 0) {
configArray.unshift(...parentConfigArray);
} else {
configArray = parentConfigArray;
}
// Cache and return.
return this._cacheConfig(directoryPath, configArray);
}
/**
* Freeze and cache a given config.
* @param {string} directoryPath The path to a directory as a cache key.
* @param {ConfigArray} configArray The config array as a cache value.
* @returns {ConfigArray} The `configArray` (frozen).
*/
_cacheConfig(directoryPath, configArray) {
const { configCache } = internalSlotsMap.get(this);
Object.freeze(configArray);
configCache.set(directoryPath, configArray);
return configArray;
}
/**
* Finalize a given config array.
* Concatenate `--config` and other CLI options.
* @param {ConfigArray} configArray The parent config array.
* @param {string} directoryPath The path to the leaf directory to find config files.
* @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.
* @returns {ConfigArray} The loaded config.
* @private
*/
_finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {
const {
cliConfigArray,
configArrayFactory,
finalizeCache,
useEslintrc,
builtInRules
} = internalSlotsMap.get(this);
let finalConfigArray = finalizeCache.get(configArray);
if (!finalConfigArray) {
finalConfigArray = configArray;
// Load the personal config if there are no regular config files.
if (
useEslintrc &&
configArray.every(c => !c.filePath) &&
cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
) {
const homePath = os.homedir();
debug("Loading the config file of the home directory:", homePath);
const personalConfigArray = configArrayFactory.loadInDirectory(
homePath,
{ name: "PersonalConfig" }
);
if (
personalConfigArray.length > 0 &&
!directoryPath.startsWith(homePath)
) {
const lastElement =
personalConfigArray[personalConfigArray.length - 1];
emitDeprecationWarning(
lastElement.filePath,
"ESLINT_PERSONAL_CONFIG_LOAD"
);
}
finalConfigArray = finalConfigArray.concat(personalConfigArray);
}
// Apply CLI options.
if (cliConfigArray.length > 0) {
finalConfigArray = finalConfigArray.concat(cliConfigArray);
}
// Validate rule settings and environments.
const validator = new ConfigValidator({
builtInRules
});
validator.validateConfigArray(finalConfigArray);
// Cache it.
Object.freeze(finalConfigArray);
finalizeCache.set(configArray, finalConfigArray);
debug(
"Configuration was determined: %o on %s",
finalConfigArray,
directoryPath
);
}
// At least one element (the default ignore patterns) exists.
if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {
throw new ConfigurationNotFoundError(directoryPath);
}
return finalConfigArray;
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export { CascadingConfigArrayFactory };

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,523 @@
/**
* @fileoverview `ConfigArray` class.
*
* `ConfigArray` class expresses the full of a configuration. It has the entry
* config file, base config files that were extended, loaded parsers, and loaded
* plugins.
*
* `ConfigArray` class provides three properties and two methods.
*
* - `pluginEnvironments`
* - `pluginProcessors`
* - `pluginRules`
* The `Map` objects that contain the members of all plugins that this
* config array contains. Those map objects don't have mutation methods.
* Those keys are the member ID such as `pluginId/memberName`.
* - `isRoot()`
* If `true` then this configuration has `root:true` property.
* - `extractConfig(filePath)`
* Extract the final configuration for a given file. This means merging
* every config array element which that `criteria` property matched. The
* `filePath` argument must be an absolute path.
*
* `ConfigArrayFactory` provides the loading logic of config files.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import { ExtractedConfig } from "./extracted-config.js";
import { IgnorePattern } from "./ignore-pattern.js";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// Define types for VSCode IntelliSense.
/** @typedef {import("../../shared/types").Environment} Environment */
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
/** @typedef {import("../../shared/types").RuleConf} RuleConf */
/** @typedef {import("../../shared/types").Rule} Rule */
/** @typedef {import("../../shared/types").Plugin} Plugin */
/** @typedef {import("../../shared/types").Processor} Processor */
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
/**
* @typedef {Object} ConfigArrayElement
* @property {string} name The name of this config element.
* @property {string} filePath The path to the source file of this config element.
* @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
* @property {Record<string, boolean>|undefined} env The environment settings.
* @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
* @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
* @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
* @property {DependentParser|undefined} parser The parser loader.
* @property {Object|undefined} parserOptions The parser options.
* @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
* @property {string|undefined} processor The processor name to refer plugin's processor.
* @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
* @property {boolean|undefined} root The flag to express root.
* @property {Record<string, RuleConf>|undefined} rules The rule settings
* @property {Object|undefined} settings The shared settings.
* @property {"config" | "ignore" | "implicit-processor"} type The element type.
*/
/**
* @typedef {Object} ConfigArrayInternalSlots
* @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
* @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
* @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
* @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
*/
/** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
const internalSlotsMap = new class extends WeakMap {
get(key) {
let value = super.get(key);
if (!value) {
value = {
cache: new Map(),
envMap: null,
processorMap: null,
ruleMap: null
};
super.set(key, value);
}
return value;
}
}();
/**
* Get the indices which are matched to a given file.
* @param {ConfigArrayElement[]} elements The elements.
* @param {string} filePath The path to a target file.
* @returns {number[]} The indices.
*/
function getMatchedIndices(elements, filePath) {
const indices = [];
for (let i = elements.length - 1; i >= 0; --i) {
const element = elements[i];
if (!element.criteria || (filePath && element.criteria.test(filePath))) {
indices.push(i);
}
}
return indices;
}
/**
* Check if a value is a non-null object.
* @param {any} x The value to check.
* @returns {boolean} `true` if the value is a non-null object.
*/
function isNonNullObject(x) {
return typeof x === "object" && x !== null;
}
/**
* Merge two objects.
*
* Assign every property values of `y` to `x` if `x` doesn't have the property.
* If `x`'s property value is an object, it does recursive.
* @param {Object} target The destination to merge
* @param {Object|undefined} source The source to merge.
* @returns {void}
*/
function mergeWithoutOverwrite(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
if (isNonNullObject(target[key])) {
mergeWithoutOverwrite(target[key], source[key]);
} else if (target[key] === void 0) {
if (isNonNullObject(source[key])) {
target[key] = Array.isArray(source[key]) ? [] : {};
mergeWithoutOverwrite(target[key], source[key]);
} else if (source[key] !== void 0) {
target[key] = source[key];
}
}
}
}
/**
* The error for plugin conflicts.
*/
class PluginConflictError extends Error {
/**
* Initialize this error object.
* @param {string} pluginId The plugin ID.
* @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
*/
constructor(pluginId, plugins) {
super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`);
this.messageTemplate = "plugin-conflict";
this.messageData = { pluginId, plugins };
}
}
/**
* Merge plugins.
* `target`'s definition is prior to `source`'s.
* @param {Record<string, DependentPlugin>} target The destination to merge
* @param {Record<string, DependentPlugin>|undefined} source The source to merge.
* @returns {void}
*/
function mergePlugins(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
const targetValue = target[key];
const sourceValue = source[key];
// Adopt the plugin which was found at first.
if (targetValue === void 0) {
if (sourceValue.error) {
throw sourceValue.error;
}
target[key] = sourceValue;
} else if (sourceValue.filePath !== targetValue.filePath) {
throw new PluginConflictError(key, [
{
filePath: targetValue.filePath,
importerName: targetValue.importerName
},
{
filePath: sourceValue.filePath,
importerName: sourceValue.importerName
}
]);
}
}
}
/**
* Merge rule configs.
* `target`'s definition is prior to `source`'s.
* @param {Record<string, Array>} target The destination to merge
* @param {Record<string, RuleConf>|undefined} source The source to merge.
* @returns {void}
*/
function mergeRuleConfigs(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
const targetDef = target[key];
const sourceDef = source[key];
// Adopt the rule config which was found at first.
if (targetDef === void 0) {
if (Array.isArray(sourceDef)) {
target[key] = [...sourceDef];
} else {
target[key] = [sourceDef];
}
/*
* If the first found rule config is severity only and the current rule
* config has options, merge the severity and the options.
*/
} else if (
targetDef.length === 1 &&
Array.isArray(sourceDef) &&
sourceDef.length >= 2
) {
targetDef.push(...sourceDef.slice(1));
}
}
}
/**
* Create the extracted config.
* @param {ConfigArray} instance The config elements.
* @param {number[]} indices The indices to use.
* @returns {ExtractedConfig} The extracted config.
*/
function createConfig(instance, indices) {
const config = new ExtractedConfig();
const ignorePatterns = [];
// Merge elements.
for (const index of indices) {
const element = instance[index];
// Adopt the parser which was found at first.
if (!config.parser && element.parser) {
if (element.parser.error) {
throw element.parser.error;
}
config.parser = element.parser;
}
// Adopt the processor which was found at first.
if (!config.processor && element.processor) {
config.processor = element.processor;
}
// Adopt the noInlineConfig which was found at first.
if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
config.noInlineConfig = element.noInlineConfig;
config.configNameOfNoInlineConfig = element.name;
}
// Adopt the reportUnusedDisableDirectives which was found at first.
if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
}
// Collect ignorePatterns
if (element.ignorePattern) {
ignorePatterns.push(element.ignorePattern);
}
// Merge others.
mergeWithoutOverwrite(config.env, element.env);
mergeWithoutOverwrite(config.globals, element.globals);
mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
mergeWithoutOverwrite(config.settings, element.settings);
mergePlugins(config.plugins, element.plugins);
mergeRuleConfigs(config.rules, element.rules);
}
// Create the predicate function for ignore patterns.
if (ignorePatterns.length > 0) {
config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
}
return config;
}
/**
* Collect definitions.
* @template T, U
* @param {string} pluginId The plugin ID for prefix.
* @param {Record<string,T>} defs The definitions to collect.
* @param {Map<string, U>} map The map to output.
* @param {function(T): U} [normalize] The normalize function for each value.
* @returns {void}
*/
function collect(pluginId, defs, map, normalize) {
if (defs) {
const prefix = pluginId && `${pluginId}/`;
for (const [key, value] of Object.entries(defs)) {
map.set(
`${prefix}${key}`,
normalize ? normalize(value) : value
);
}
}
}
/**
* Normalize a rule definition.
* @param {Function|Rule} rule The rule definition to normalize.
* @returns {Rule} The normalized rule definition.
*/
function normalizePluginRule(rule) {
return typeof rule === "function" ? { create: rule } : rule;
}
/**
* Delete the mutation methods from a given map.
* @param {Map<any, any>} map The map object to delete.
* @returns {void}
*/
function deleteMutationMethods(map) {
Object.defineProperties(map, {
clear: { configurable: true, value: void 0 },
delete: { configurable: true, value: void 0 },
set: { configurable: true, value: void 0 }
});
}
/**
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
* @param {ConfigArrayElement[]} elements The config elements.
* @param {ConfigArrayInternalSlots} slots The internal slots.
* @returns {void}
*/
function initPluginMemberMaps(elements, slots) {
const processed = new Set();
slots.envMap = new Map();
slots.processorMap = new Map();
slots.ruleMap = new Map();
for (const element of elements) {
if (!element.plugins) {
continue;
}
for (const [pluginId, value] of Object.entries(element.plugins)) {
const plugin = value.definition;
if (!plugin || processed.has(pluginId)) {
continue;
}
processed.add(pluginId);
collect(pluginId, plugin.environments, slots.envMap);
collect(pluginId, plugin.processors, slots.processorMap);
collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule);
}
}
deleteMutationMethods(slots.envMap);
deleteMutationMethods(slots.processorMap);
deleteMutationMethods(slots.ruleMap);
}
/**
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
* @param {ConfigArray} instance The config elements.
* @returns {ConfigArrayInternalSlots} The extracted config.
*/
function ensurePluginMemberMaps(instance) {
const slots = internalSlotsMap.get(instance);
if (!slots.ruleMap) {
initPluginMemberMaps(instance, slots);
}
return slots;
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* The Config Array.
*
* `ConfigArray` instance contains all settings, parsers, and plugins.
* You need to call `ConfigArray#extractConfig(filePath)` method in order to
* extract, merge and get only the config data which is related to an arbitrary
* file.
* @extends {Array<ConfigArrayElement>}
*/
class ConfigArray extends Array {
/**
* Get the plugin environments.
* The returned map cannot be mutated.
* @type {ReadonlyMap<string, Environment>} The plugin environments.
*/
get pluginEnvironments() {
return ensurePluginMemberMaps(this).envMap;
}
/**
* Get the plugin processors.
* The returned map cannot be mutated.
* @type {ReadonlyMap<string, Processor>} The plugin processors.
*/
get pluginProcessors() {
return ensurePluginMemberMaps(this).processorMap;
}
/**
* Get the plugin rules.
* The returned map cannot be mutated.
* @returns {ReadonlyMap<string, Rule>} The plugin rules.
*/
get pluginRules() {
return ensurePluginMemberMaps(this).ruleMap;
}
/**
* Check if this config has `root` flag.
* @returns {boolean} `true` if this config array is root.
*/
isRoot() {
for (let i = this.length - 1; i >= 0; --i) {
const root = this[i].root;
if (typeof root === "boolean") {
return root;
}
}
return false;
}
/**
* Extract the config data which is related to a given file.
* @param {string} filePath The absolute path to the target file.
* @returns {ExtractedConfig} The extracted config data.
*/
extractConfig(filePath) {
const { cache } = internalSlotsMap.get(this);
const indices = getMatchedIndices(this, filePath);
const cacheKey = indices.join(",");
if (!cache.has(cacheKey)) {
cache.set(cacheKey, createConfig(this, indices));
}
return cache.get(cacheKey);
}
/**
* Check if a given path is an additional lint target.
* @param {string} filePath The absolute path to the target file.
* @returns {boolean} `true` if the file is an additional lint target.
*/
isAdditionalTargetPath(filePath) {
for (const { criteria, type } of this) {
if (
type === "config" &&
criteria &&
!criteria.endsWithWildcard &&
criteria.test(filePath)
) {
return true;
}
}
return false;
}
}
/**
* Get the used extracted configs.
* CLIEngine will use this method to collect used deprecated rules.
* @param {ConfigArray} instance The config array object to get.
* @returns {ExtractedConfig[]} The used extracted configs.
* @private
*/
function getUsedExtractedConfigs(instance) {
const { cache } = internalSlotsMap.get(instance);
return Array.from(cache.values());
}
export {
ConfigArray,
getUsedExtractedConfigs
};

View file

@ -0,0 +1,124 @@
/**
* @fileoverview `ConfigDependency` class.
*
* `ConfigDependency` class expresses a loaded parser or plugin.
*
* If the parser or plugin was loaded successfully, it has `definition` property
* and `filePath` property. Otherwise, it has `error` property.
*
* When `JSON.stringify()` converted a `ConfigDependency` object to a JSON, it
* omits `definition` property.
*
* `ConfigArrayFactory` creates `ConfigDependency` objects when it loads parsers
* or plugins.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import util from "util";
/**
* The class is to store parsers or plugins.
* This class hides the loaded object from `JSON.stringify()` and `console.log`.
* @template T
*/
class ConfigDependency {
/**
* Initialize this instance.
* @param {Object} data The dependency data.
* @param {T} [data.definition] The dependency if the loading succeeded.
* @param {T} [data.original] The original, non-normalized dependency if the loading succeeded.
* @param {Error} [data.error] The error object if the loading failed.
* @param {string} [data.filePath] The actual path to the dependency if the loading succeeded.
* @param {string} data.id The ID of this dependency.
* @param {string} data.importerName The name of the config file which loads this dependency.
* @param {string} data.importerPath The path to the config file which loads this dependency.
*/
constructor({
definition = null,
original = null,
error = null,
filePath = null,
id,
importerName,
importerPath
}) {
/**
* The loaded dependency if the loading succeeded.
* @type {T|null}
*/
this.definition = definition;
/**
* The original dependency as loaded directly from disk if the loading succeeded.
* @type {T|null}
*/
this.original = original;
/**
* The error object if the loading failed.
* @type {Error|null}
*/
this.error = error;
/**
* The loaded dependency if the loading succeeded.
* @type {string|null}
*/
this.filePath = filePath;
/**
* The ID of this dependency.
* @type {string}
*/
this.id = id;
/**
* The name of the config file which loads this dependency.
* @type {string}
*/
this.importerName = importerName;
/**
* The path to the config file which loads this dependency.
* @type {string}
*/
this.importerPath = importerPath;
}
// eslint-disable-next-line jsdoc/require-description
/**
* @returns {Object} a JSON compatible object.
*/
toJSON() {
const obj = this[util.inspect.custom]();
// Display `error.message` (`Error#message` is unenumerable).
if (obj.error instanceof Error) {
obj.error = { ...obj.error, message: obj.error.message };
}
return obj;
}
// eslint-disable-next-line jsdoc/require-description
/**
* @returns {Object} an object to display by `console.log()`.
*/
[util.inspect.custom]() {
const {
definition: _ignore1, // eslint-disable-line no-unused-vars
original: _ignore2, // eslint-disable-line no-unused-vars
...obj
} = this;
return obj;
}
}
/** @typedef {ConfigDependency<import("../../shared/types").Parser>} DependentParser */
/** @typedef {ConfigDependency<import("../../shared/types").Plugin>} DependentPlugin */
export { ConfigDependency };

View file

@ -0,0 +1,145 @@
/**
* @fileoverview `ExtractedConfig` class.
*
* `ExtractedConfig` class expresses a final configuration for a specific file.
*
* It provides one method.
*
* - `toCompatibleObjectAsConfigFileContent()`
* Convert this configuration to the compatible object as the content of
* config files. It converts the loaded parser and plugins to strings.
* `CLIEngine#getConfigForFile(filePath)` method uses this method.
*
* `ConfigArray#extractConfig(filePath)` creates a `ExtractedConfig` instance.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import { IgnorePattern } from "./ignore-pattern.js";
// For VSCode intellisense
/** @typedef {import("../../shared/types").ConfigData} ConfigData */
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
/** @typedef {import("../../shared/types").SeverityConf} SeverityConf */
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
/**
* Check if `xs` starts with `ys`.
* @template T
* @param {T[]} xs The array to check.
* @param {T[]} ys The array that may be the first part of `xs`.
* @returns {boolean} `true` if `xs` starts with `ys`.
*/
function startsWith(xs, ys) {
return xs.length >= ys.length && ys.every((y, i) => y === xs[i]);
}
/**
* The class for extracted config data.
*/
class ExtractedConfig {
constructor() {
/**
* The config name what `noInlineConfig` setting came from.
* @type {string}
*/
this.configNameOfNoInlineConfig = "";
/**
* Environments.
* @type {Record<string, boolean>}
*/
this.env = {};
/**
* Global variables.
* @type {Record<string, GlobalConf>}
*/
this.globals = {};
/**
* The glob patterns that ignore to lint.
* @type {(((filePath:string, dot?:boolean) => boolean) & { basePath:string; patterns:string[] }) | undefined}
*/
this.ignores = void 0;
/**
* The flag that disables directive comments.
* @type {boolean|undefined}
*/
this.noInlineConfig = void 0;
/**
* Parser definition.
* @type {DependentParser|null}
*/
this.parser = null;
/**
* Options for the parser.
* @type {Object}
*/
this.parserOptions = {};
/**
* Plugin definitions.
* @type {Record<string, DependentPlugin>}
*/
this.plugins = {};
/**
* Processor ID.
* @type {string|null}
*/
this.processor = null;
/**
* The flag that reports unused `eslint-disable` directive comments.
* @type {boolean|undefined}
*/
this.reportUnusedDisableDirectives = void 0;
/**
* Rule settings.
* @type {Record<string, [SeverityConf, ...any[]]>}
*/
this.rules = {};
/**
* Shared settings.
* @type {Object}
*/
this.settings = {};
}
/**
* Convert this config to the compatible object as a config file content.
* @returns {ConfigData} The converted object.
*/
toCompatibleObjectAsConfigFileContent() {
const {
/* eslint-disable no-unused-vars */
configNameOfNoInlineConfig: _ignore1,
processor: _ignore2,
/* eslint-enable no-unused-vars */
ignores,
...config
} = this;
config.parser = config.parser && config.parser.filePath;
config.plugins = Object.keys(config.plugins).filter(Boolean).reverse();
config.ignorePatterns = ignores ? ignores.patterns : [];
// Strip the default patterns from `ignorePatterns`.
if (startsWith(config.ignorePatterns, IgnorePattern.DefaultPatterns)) {
config.ignorePatterns =
config.ignorePatterns.slice(IgnorePattern.DefaultPatterns.length);
}
return config;
}
}
export { ExtractedConfig };

View file

@ -0,0 +1,238 @@
/**
* @fileoverview `IgnorePattern` class.
*
* `IgnorePattern` class has the set of glob patterns and the base path.
*
* It provides two static methods.
*
* - `IgnorePattern.createDefaultIgnore(cwd)`
* Create the default predicate function.
* - `IgnorePattern.createIgnore(ignorePatterns)`
* Create the predicate function from multiple `IgnorePattern` objects.
*
* It provides two properties and a method.
*
* - `patterns`
* The glob patterns that ignore to lint.
* - `basePath`
* The base path of the glob patterns. If absolute paths existed in the
* glob patterns, those are handled as relative paths to the base path.
* - `getPatternsRelativeTo(basePath)`
* Get `patterns` as modified for a given base path. It modifies the
* absolute paths in the patterns as prepending the difference of two base
* paths.
*
* `ConfigArrayFactory` creates `IgnorePattern` objects when it processes
* `ignorePatterns` properties.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import assert from "assert";
import path from "path";
import ignore from "ignore";
import debugOrig from "debug";
const debug = debugOrig("eslintrc:ignore-pattern");
/** @typedef {ReturnType<import("ignore").default>} Ignore */
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Get the path to the common ancestor directory of given paths.
* @param {string[]} sourcePaths The paths to calculate the common ancestor.
* @returns {string} The path to the common ancestor directory.
*/
function getCommonAncestorPath(sourcePaths) {
let result = sourcePaths[0];
for (let i = 1; i < sourcePaths.length; ++i) {
const a = result;
const b = sourcePaths[i];
// Set the shorter one (it's the common ancestor if one includes the other).
result = a.length < b.length ? a : b;
// Set the common ancestor.
for (let j = 0, lastSepPos = 0; j < a.length && j < b.length; ++j) {
if (a[j] !== b[j]) {
result = a.slice(0, lastSepPos);
break;
}
if (a[j] === path.sep) {
lastSepPos = j;
}
}
}
let resolvedResult = result || path.sep;
// if Windows common ancestor is root of drive must have trailing slash to be absolute.
if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") {
resolvedResult += path.sep;
}
return resolvedResult;
}
/**
* Make relative path.
* @param {string} from The source path to get relative path.
* @param {string} to The destination path to get relative path.
* @returns {string} The relative path.
*/
function relative(from, to) {
const relPath = path.relative(from, to);
if (path.sep === "/") {
return relPath;
}
return relPath.split(path.sep).join("/");
}
/**
* Get the trailing slash if existed.
* @param {string} filePath The path to check.
* @returns {string} The trailing slash if existed.
*/
function dirSuffix(filePath) {
const isDir = (
filePath.endsWith(path.sep) ||
(process.platform === "win32" && filePath.endsWith("/"))
);
return isDir ? "/" : "";
}
const DefaultPatterns = Object.freeze(["/**/node_modules/*"]);
const DotPatterns = Object.freeze([".*", "!.eslintrc.*", "!../"]);
//------------------------------------------------------------------------------
// Public
//------------------------------------------------------------------------------
class IgnorePattern {
/**
* The default patterns.
* @type {string[]}
*/
static get DefaultPatterns() {
return DefaultPatterns;
}
/**
* Create the default predicate function.
* @param {string} cwd The current working directory.
* @returns {((filePath:string, dot:boolean) => boolean) & {basePath:string; patterns:string[]}}
* The preficate function.
* The first argument is an absolute path that is checked.
* The second argument is the flag to not ignore dotfiles.
* If the predicate function returned `true`, it means the path should be ignored.
*/
static createDefaultIgnore(cwd) {
return this.createIgnore([new IgnorePattern(DefaultPatterns, cwd)]);
}
/**
* Create the predicate function from multiple `IgnorePattern` objects.
* @param {IgnorePattern[]} ignorePatterns The list of ignore patterns.
* @returns {((filePath:string, dot?:boolean) => boolean) & {basePath:string; patterns:string[]}}
* The preficate function.
* The first argument is an absolute path that is checked.
* The second argument is the flag to not ignore dotfiles.
* If the predicate function returned `true`, it means the path should be ignored.
*/
static createIgnore(ignorePatterns) {
debug("Create with: %o", ignorePatterns);
const basePath = getCommonAncestorPath(ignorePatterns.map(p => p.basePath));
const patterns = [].concat(
...ignorePatterns.map(p => p.getPatternsRelativeTo(basePath))
);
const ig = ignore({ allowRelativePaths: true }).add([...DotPatterns, ...patterns]);
const dotIg = ignore({ allowRelativePaths: true }).add(patterns);
debug(" processed: %o", { basePath, patterns });
return Object.assign(
(filePath, dot = false) => {
assert(path.isAbsolute(filePath), "'filePath' should be an absolute path.");
const relPathRaw = relative(basePath, filePath);
const relPath = relPathRaw && (relPathRaw + dirSuffix(filePath));
const adoptedIg = dot ? dotIg : ig;
const result = relPath !== "" && adoptedIg.ignores(relPath);
debug("Check", { filePath, dot, relativePath: relPath, result });
return result;
},
{ basePath, patterns }
);
}
/**
* Initialize a new `IgnorePattern` instance.
* @param {string[]} patterns The glob patterns that ignore to lint.
* @param {string} basePath The base path of `patterns`.
*/
constructor(patterns, basePath) {
assert(path.isAbsolute(basePath), "'basePath' should be an absolute path.");
/**
* The glob patterns that ignore to lint.
* @type {string[]}
*/
this.patterns = patterns;
/**
* The base path of `patterns`.
* @type {string}
*/
this.basePath = basePath;
/**
* If `true` then patterns which don't start with `/` will match the paths to the outside of `basePath`. Defaults to `false`.
*
* It's set `true` for `.eslintignore`, `package.json`, and `--ignore-path` for backward compatibility.
* It's `false` as-is for `ignorePatterns` property in config files.
* @type {boolean}
*/
this.loose = false;
}
/**
* Get `patterns` as modified for a given base path. It modifies the
* absolute paths in the patterns as prepending the difference of two base
* paths.
* @param {string} newBasePath The base path.
* @returns {string[]} Modifired patterns.
*/
getPatternsRelativeTo(newBasePath) {
assert(path.isAbsolute(newBasePath), "'newBasePath' should be an absolute path.");
const { basePath, loose, patterns } = this;
if (newBasePath === basePath) {
return patterns;
}
const prefix = `/${relative(newBasePath, basePath)}`;
return patterns.map(pattern => {
const negative = pattern.startsWith("!");
const head = negative ? "!" : "";
const body = negative ? pattern.slice(1) : pattern;
if (body.startsWith("/") || body.startsWith("../")) {
return `${head}${prefix}${body}`;
}
return loose ? pattern : `${head}${prefix}/**/${body}`;
});
}
}
export { IgnorePattern };

View file

@ -0,0 +1,19 @@
/**
* @fileoverview `ConfigArray` class.
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import { ConfigArray, getUsedExtractedConfigs } from "./config-array.js";
import { ConfigDependency } from "./config-dependency.js";
import { ExtractedConfig } from "./extracted-config.js";
import { IgnorePattern } from "./ignore-pattern.js";
import { OverrideTester } from "./override-tester.js";
export {
ConfigArray,
ConfigDependency,
ExtractedConfig,
IgnorePattern,
OverrideTester,
getUsedExtractedConfigs
};

View file

@ -0,0 +1,225 @@
/**
* @fileoverview `OverrideTester` class.
*
* `OverrideTester` class handles `files` property and `excludedFiles` property
* of `overrides` config.
*
* It provides one method.
*
* - `test(filePath)`
* Test if a file path matches the pair of `files` property and
* `excludedFiles` property. The `filePath` argument must be an absolute
* path.
*
* `ConfigArrayFactory` creates `OverrideTester` objects when it processes
* `overrides` properties.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
import assert from "assert";
import path from "path";
import util from "util";
import minimatch from "minimatch";
const { Minimatch } = minimatch;
const minimatchOpts = { dot: true, matchBase: true };
/**
* @typedef {Object} Pattern
* @property {InstanceType<Minimatch>[] | null} includes The positive matchers.
* @property {InstanceType<Minimatch>[] | null} excludes The negative matchers.
*/
/**
* Normalize a given pattern to an array.
* @param {string|string[]|undefined} patterns A glob pattern or an array of glob patterns.
* @returns {string[]|null} Normalized patterns.
* @private
*/
function normalizePatterns(patterns) {
if (Array.isArray(patterns)) {
return patterns.filter(Boolean);
}
if (typeof patterns === "string" && patterns) {
return [patterns];
}
return [];
}
/**
* Create the matchers of given patterns.
* @param {string[]} patterns The patterns.
* @returns {InstanceType<Minimatch>[] | null} The matchers.
*/
function toMatcher(patterns) {
if (patterns.length === 0) {
return null;
}
return patterns.map(pattern => {
if (/^\.[/\\]/u.test(pattern)) {
return new Minimatch(
pattern.slice(2),
// `./*.js` should not match with `subdir/foo.js`
{ ...minimatchOpts, matchBase: false }
);
}
return new Minimatch(pattern, minimatchOpts);
});
}
/**
* Convert a given matcher to string.
* @param {Pattern} matchers The matchers.
* @returns {string} The string expression of the matcher.
*/
function patternToJson({ includes, excludes }) {
return {
includes: includes && includes.map(m => m.pattern),
excludes: excludes && excludes.map(m => m.pattern)
};
}
/**
* The class to test given paths are matched by the patterns.
*/
class OverrideTester {
/**
* Create a tester with given criteria.
* If there are no criteria, returns `null`.
* @param {string|string[]} files The glob patterns for included files.
* @param {string|string[]} excludedFiles The glob patterns for excluded files.
* @param {string} basePath The path to the base directory to test paths.
* @returns {OverrideTester|null} The created instance or `null`.
*/
static create(files, excludedFiles, basePath) {
const includePatterns = normalizePatterns(files);
const excludePatterns = normalizePatterns(excludedFiles);
let endsWithWildcard = false;
if (includePatterns.length === 0) {
return null;
}
// Rejects absolute paths or relative paths to parents.
for (const pattern of includePatterns) {
if (path.isAbsolute(pattern) || pattern.includes("..")) {
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
}
if (pattern.endsWith("*")) {
endsWithWildcard = true;
}
}
for (const pattern of excludePatterns) {
if (path.isAbsolute(pattern) || pattern.includes("..")) {
throw new Error(`Invalid override pattern (expected relative path not containing '..'): ${pattern}`);
}
}
const includes = toMatcher(includePatterns);
const excludes = toMatcher(excludePatterns);
return new OverrideTester(
[{ includes, excludes }],
basePath,
endsWithWildcard
);
}
/**
* Combine two testers by logical and.
* If either of the testers was `null`, returns the other tester.
* The `basePath` property of the two must be the same value.
* @param {OverrideTester|null} a A tester.
* @param {OverrideTester|null} b Another tester.
* @returns {OverrideTester|null} Combined tester.
*/
static and(a, b) {
if (!b) {
return a && new OverrideTester(
a.patterns,
a.basePath,
a.endsWithWildcard
);
}
if (!a) {
return new OverrideTester(
b.patterns,
b.basePath,
b.endsWithWildcard
);
}
assert.strictEqual(a.basePath, b.basePath);
return new OverrideTester(
a.patterns.concat(b.patterns),
a.basePath,
a.endsWithWildcard || b.endsWithWildcard
);
}
/**
* Initialize this instance.
* @param {Pattern[]} patterns The matchers.
* @param {string} basePath The base path.
* @param {boolean} endsWithWildcard If `true` then a pattern ends with `*`.
*/
constructor(patterns, basePath, endsWithWildcard = false) {
/** @type {Pattern[]} */
this.patterns = patterns;
/** @type {string} */
this.basePath = basePath;
/** @type {boolean} */
this.endsWithWildcard = endsWithWildcard;
}
/**
* Test if a given path is matched or not.
* @param {string} filePath The absolute path to the target file.
* @returns {boolean} `true` if the path was matched.
*/
test(filePath) {
if (typeof filePath !== "string" || !path.isAbsolute(filePath)) {
throw new Error(`'filePath' should be an absolute path, but got ${filePath}.`);
}
const relativePath = path.relative(this.basePath, filePath);
return this.patterns.every(({ includes, excludes }) => (
(!includes || includes.some(m => m.match(relativePath))) &&
(!excludes || !excludes.some(m => m.match(relativePath)))
));
}
// eslint-disable-next-line jsdoc/require-description
/**
* @returns {Object} a JSON compatible object.
*/
toJSON() {
if (this.patterns.length === 1) {
return {
...patternToJson(this.patterns[0]),
basePath: this.basePath
};
}
return {
AND: this.patterns.map(patternToJson),
basePath: this.basePath
};
}
// eslint-disable-next-line jsdoc/require-description
/**
* @returns {Object} an object to display by `console.log()`.
*/
[util.inspect.custom]() {
return this.toJSON();
}
}
export { OverrideTester };

View file

@ -0,0 +1,318 @@
/**
* @fileoverview Compatibility class for flat config.
* @author Nicholas C. Zakas
*/
//-----------------------------------------------------------------------------
// Requirements
//-----------------------------------------------------------------------------
import createDebug from "debug";
import path from "path";
import environments from "../conf/environments.js";
import { ConfigArrayFactory } from "./config-array-factory.js";
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
/** @typedef {import("../../shared/types").Environment} Environment */
/** @typedef {import("../../shared/types").Processor} Processor */
const debug = createDebug("eslintrc:flat-compat");
const cafactory = Symbol("cafactory");
/**
* Translates an ESLintRC-style config object into a flag-config-style config
* object.
* @param {Object} eslintrcConfig An ESLintRC-style config object.
* @param {Object} options Options to help translate the config.
* @param {string} options.resolveConfigRelativeTo To the directory to resolve
* configs from.
* @param {string} options.resolvePluginsRelativeTo The directory to resolve
* plugins from.
* @param {ReadOnlyMap<string,Environment>} options.pluginEnvironments A map of plugin environment
* names to objects.
* @param {ReadOnlyMap<string,Processor>} options.pluginProcessors A map of plugin processor
* names to objects.
* @returns {Object} A flag-config-style config object.
*/
function translateESLintRC(eslintrcConfig, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo,
pluginEnvironments,
pluginProcessors
}) {
const flatConfig = {};
const configs = [];
const languageOptions = {};
const linterOptions = {};
const keysToCopy = ["settings", "rules", "processor"];
const languageOptionsKeysToCopy = ["globals", "parser", "parserOptions"];
const linterOptionsKeysToCopy = ["noInlineConfig", "reportUnusedDisableDirectives"];
// copy over simple translations
for (const key of keysToCopy) {
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
flatConfig[key] = eslintrcConfig[key];
}
}
// copy over languageOptions
for (const key of languageOptionsKeysToCopy) {
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
// create the languageOptions key in the flat config
flatConfig.languageOptions = languageOptions;
if (key === "parser") {
debug(`Resolving parser '${languageOptions[key]}' relative to ${resolveConfigRelativeTo}`);
if (eslintrcConfig[key].error) {
throw eslintrcConfig[key].error;
}
languageOptions[key] = eslintrcConfig[key].definition;
continue;
}
// clone any object values that are in the eslintrc config
if (eslintrcConfig[key] && typeof eslintrcConfig[key] === "object") {
languageOptions[key] = {
...eslintrcConfig[key]
};
} else {
languageOptions[key] = eslintrcConfig[key];
}
}
}
// copy over linterOptions
for (const key of linterOptionsKeysToCopy) {
if (key in eslintrcConfig && typeof eslintrcConfig[key] !== "undefined") {
flatConfig.linterOptions = linterOptions;
linterOptions[key] = eslintrcConfig[key];
}
}
// move ecmaVersion a level up
if (languageOptions.parserOptions) {
if ("ecmaVersion" in languageOptions.parserOptions) {
languageOptions.ecmaVersion = languageOptions.parserOptions.ecmaVersion;
delete languageOptions.parserOptions.ecmaVersion;
}
if ("sourceType" in languageOptions.parserOptions) {
languageOptions.sourceType = languageOptions.parserOptions.sourceType;
delete languageOptions.parserOptions.sourceType;
}
// check to see if we even need parserOptions anymore and remove it if not
if (Object.keys(languageOptions.parserOptions).length === 0) {
delete languageOptions.parserOptions;
}
}
// overrides
if (eslintrcConfig.criteria) {
flatConfig.files = [absoluteFilePath => eslintrcConfig.criteria.test(absoluteFilePath)];
}
// translate plugins
if (eslintrcConfig.plugins && typeof eslintrcConfig.plugins === "object") {
debug(`Translating plugins: ${eslintrcConfig.plugins}`);
flatConfig.plugins = {};
for (const pluginName of Object.keys(eslintrcConfig.plugins)) {
debug(`Translating plugin: ${pluginName}`);
debug(`Resolving plugin '${pluginName} relative to ${resolvePluginsRelativeTo}`);
const { original: plugin, error } = eslintrcConfig.plugins[pluginName];
if (error) {
throw error;
}
flatConfig.plugins[pluginName] = plugin;
// create a config for any processors
if (plugin.processors) {
for (const processorName of Object.keys(plugin.processors)) {
if (processorName.startsWith(".")) {
debug(`Assigning processor: ${pluginName}/${processorName}`);
configs.unshift({
files: [`**/*${processorName}`],
processor: pluginProcessors.get(`${pluginName}/${processorName}`)
});
}
}
}
}
}
// translate env - must come after plugins
if (eslintrcConfig.env && typeof eslintrcConfig.env === "object") {
for (const envName of Object.keys(eslintrcConfig.env)) {
// only add environments that are true
if (eslintrcConfig.env[envName]) {
debug(`Translating environment: ${envName}`);
if (environments.has(envName)) {
// built-in environments should be defined first
configs.unshift(...translateESLintRC({
criteria: eslintrcConfig.criteria,
...environments.get(envName)
}, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo
}));
} else if (pluginEnvironments.has(envName)) {
// if the environment comes from a plugin, it should come after the plugin config
configs.push(...translateESLintRC({
criteria: eslintrcConfig.criteria,
...pluginEnvironments.get(envName)
}, {
resolveConfigRelativeTo,
resolvePluginsRelativeTo
}));
}
}
}
}
// only add if there are actually keys in the config
if (Object.keys(flatConfig).length > 0) {
configs.push(flatConfig);
}
return configs;
}
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
/**
* A compatibility class for working with configs.
*/
class FlatCompat {
constructor({
baseDirectory = process.cwd(),
resolvePluginsRelativeTo = baseDirectory,
recommendedConfig,
allConfig
} = {}) {
this.baseDirectory = baseDirectory;
this.resolvePluginsRelativeTo = resolvePluginsRelativeTo;
this[cafactory] = new ConfigArrayFactory({
cwd: baseDirectory,
resolvePluginsRelativeTo,
getEslintAllConfig: () => {
if (!allConfig) {
throw new TypeError("Missing parameter 'allConfig' in FlatCompat constructor.");
}
return allConfig;
},
getEslintRecommendedConfig: () => {
if (!recommendedConfig) {
throw new TypeError("Missing parameter 'recommendedConfig' in FlatCompat constructor.");
}
return recommendedConfig;
}
});
}
/**
* Translates an ESLintRC-style config into a flag-config-style config.
* @param {Object} eslintrcConfig The ESLintRC-style config object.
* @returns {Object} A flag-config-style config object.
*/
config(eslintrcConfig) {
const eslintrcArray = this[cafactory].create(eslintrcConfig, {
basePath: this.baseDirectory
});
const flatArray = [];
let hasIgnorePatterns = false;
eslintrcArray.forEach(configData => {
if (configData.type === "config") {
hasIgnorePatterns = hasIgnorePatterns || configData.ignorePattern;
flatArray.push(...translateESLintRC(configData, {
resolveConfigRelativeTo: path.join(this.baseDirectory, "__placeholder.js"),
resolvePluginsRelativeTo: path.join(this.resolvePluginsRelativeTo, "__placeholder.js"),
pluginEnvironments: eslintrcArray.pluginEnvironments,
pluginProcessors: eslintrcArray.pluginProcessors
}));
}
});
// combine ignorePatterns to emulate ESLintRC behavior better
if (hasIgnorePatterns) {
flatArray.unshift({
ignores: [filePath => {
// Compute the final config for this file.
// This filters config array elements by `files`/`excludedFiles` then merges the elements.
const finalConfig = eslintrcArray.extractConfig(filePath);
// Test the `ignorePattern` properties of the final config.
return Boolean(finalConfig.ignores) && finalConfig.ignores(filePath);
}]
});
}
return flatArray;
}
/**
* Translates the `env` section of an ESLintRC-style config.
* @param {Object} envConfig The `env` section of an ESLintRC config.
* @returns {Object[]} An array of flag-config objects representing the environments.
*/
env(envConfig) {
return this.config({
env: envConfig
});
}
/**
* Translates the `extends` section of an ESLintRC-style config.
* @param {...string} configsToExtend The names of the configs to load.
* @returns {Object[]} An array of flag-config objects representing the config.
*/
extends(...configsToExtend) {
return this.config({
extends: configsToExtend
});
}
/**
* Translates the `plugins` section of an ESLintRC-style config.
* @param {...string} plugins The names of the plugins to load.
* @returns {Object[]} An array of flag-config objects representing the plugins.
*/
plugins(...plugins) {
return this.config({
plugins
});
}
}
export { FlatCompat };

View file

@ -0,0 +1,29 @@
/**
* @fileoverview Package exports for @eslint/eslintrc
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import * as ConfigOps from "./shared/config-ops.js";
import ConfigValidator from "./shared/config-validator.js";
import * as naming from "./shared/naming.js";
import environments from "../conf/environments.js";
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
const Legacy = {
environments,
// shared
ConfigOps,
ConfigValidator,
naming
};
export {
Legacy
};

56
home/ags/node_modules/@eslint/eslintrc/lib/index.js generated vendored Normal file
View file

@ -0,0 +1,56 @@
/**
* @fileoverview Package exports for @eslint/eslintrc
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import {
ConfigArrayFactory,
createContext as createConfigArrayFactoryContext
} from "./config-array-factory.js";
import { CascadingConfigArrayFactory } from "./cascading-config-array-factory.js";
import * as ModuleResolver from "./shared/relative-module-resolver.js";
import { ConfigArray, getUsedExtractedConfigs } from "./config-array/index.js";
import { ConfigDependency } from "./config-array/config-dependency.js";
import { ExtractedConfig } from "./config-array/extracted-config.js";
import { IgnorePattern } from "./config-array/ignore-pattern.js";
import { OverrideTester } from "./config-array/override-tester.js";
import * as ConfigOps from "./shared/config-ops.js";
import ConfigValidator from "./shared/config-validator.js";
import * as naming from "./shared/naming.js";
import { FlatCompat } from "./flat-compat.js";
import environments from "../conf/environments.js";
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
const Legacy = {
ConfigArray,
createConfigArrayFactoryContext,
CascadingConfigArrayFactory,
ConfigArrayFactory,
ConfigDependency,
ExtractedConfig,
IgnorePattern,
OverrideTester,
getUsedExtractedConfigs,
environments,
// shared
ConfigOps,
ConfigValidator,
ModuleResolver,
naming
};
export {
Legacy,
FlatCompat
};

View file

@ -0,0 +1,191 @@
/**
* @fileoverview The instance of Ajv validator.
* @author Evgeny Poberezkin
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import Ajv from "ajv";
//-----------------------------------------------------------------------------
// Helpers
//-----------------------------------------------------------------------------
/*
* Copied from ajv/lib/refs/json-schema-draft-04.json
* The MIT License (MIT)
* Copyright (c) 2015-2017 Evgeny Poberezkin
*/
const metaSchema = {
id: "http://json-schema.org/draft-04/schema#",
$schema: "http://json-schema.org/draft-04/schema#",
description: "Core schema meta-schema",
definitions: {
schemaArray: {
type: "array",
minItems: 1,
items: { $ref: "#" }
},
positiveInteger: {
type: "integer",
minimum: 0
},
positiveIntegerDefault0: {
allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
},
simpleTypes: {
enum: ["array", "boolean", "integer", "null", "number", "object", "string"]
},
stringArray: {
type: "array",
items: { type: "string" },
minItems: 1,
uniqueItems: true
}
},
type: "object",
properties: {
id: {
type: "string"
},
$schema: {
type: "string"
},
title: {
type: "string"
},
description: {
type: "string"
},
default: { },
multipleOf: {
type: "number",
minimum: 0,
exclusiveMinimum: true
},
maximum: {
type: "number"
},
exclusiveMaximum: {
type: "boolean",
default: false
},
minimum: {
type: "number"
},
exclusiveMinimum: {
type: "boolean",
default: false
},
maxLength: { $ref: "#/definitions/positiveInteger" },
minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
pattern: {
type: "string",
format: "regex"
},
additionalItems: {
anyOf: [
{ type: "boolean" },
{ $ref: "#" }
],
default: { }
},
items: {
anyOf: [
{ $ref: "#" },
{ $ref: "#/definitions/schemaArray" }
],
default: { }
},
maxItems: { $ref: "#/definitions/positiveInteger" },
minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
uniqueItems: {
type: "boolean",
default: false
},
maxProperties: { $ref: "#/definitions/positiveInteger" },
minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
required: { $ref: "#/definitions/stringArray" },
additionalProperties: {
anyOf: [
{ type: "boolean" },
{ $ref: "#" }
],
default: { }
},
definitions: {
type: "object",
additionalProperties: { $ref: "#" },
default: { }
},
properties: {
type: "object",
additionalProperties: { $ref: "#" },
default: { }
},
patternProperties: {
type: "object",
additionalProperties: { $ref: "#" },
default: { }
},
dependencies: {
type: "object",
additionalProperties: {
anyOf: [
{ $ref: "#" },
{ $ref: "#/definitions/stringArray" }
]
}
},
enum: {
type: "array",
minItems: 1,
uniqueItems: true
},
type: {
anyOf: [
{ $ref: "#/definitions/simpleTypes" },
{
type: "array",
items: { $ref: "#/definitions/simpleTypes" },
minItems: 1,
uniqueItems: true
}
]
},
format: { type: "string" },
allOf: { $ref: "#/definitions/schemaArray" },
anyOf: { $ref: "#/definitions/schemaArray" },
oneOf: { $ref: "#/definitions/schemaArray" },
not: { $ref: "#" }
},
dependencies: {
exclusiveMaximum: ["maximum"],
exclusiveMinimum: ["minimum"]
},
default: { }
};
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export default (additionalOptions = {}) => {
const ajv = new Ajv({
meta: false,
useDefaults: true,
validateSchema: false,
missingRefs: "ignore",
verbose: true,
schemaId: "auto",
...additionalOptions
});
ajv.addMetaSchema(metaSchema);
// eslint-disable-next-line no-underscore-dangle
ajv._opts.defaultMeta = metaSchema.id;
return ajv;
};

View file

@ -0,0 +1,135 @@
/**
* @fileoverview Config file operations. This file must be usable in the browser,
* so no Node-specific code can be here.
* @author Nicholas C. Zakas
*/
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
const RULE_SEVERITY_STRINGS = ["off", "warn", "error"],
RULE_SEVERITY = RULE_SEVERITY_STRINGS.reduce((map, value, index) => {
map[value] = index;
return map;
}, {}),
VALID_SEVERITIES = [0, 1, 2, "off", "warn", "error"];
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* Normalizes the severity value of a rule's configuration to a number
* @param {(number|string|[number, ...*]|[string, ...*])} ruleConfig A rule's configuration value, generally
* received from the user. A valid config value is either 0, 1, 2, the string "off" (treated the same as 0),
* the string "warn" (treated the same as 1), the string "error" (treated the same as 2), or an array
* whose first element is one of the above values. Strings are matched case-insensitively.
* @returns {(0|1|2)} The numeric severity value if the config value was valid, otherwise 0.
*/
function getRuleSeverity(ruleConfig) {
const severityValue = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
if (severityValue === 0 || severityValue === 1 || severityValue === 2) {
return severityValue;
}
if (typeof severityValue === "string") {
return RULE_SEVERITY[severityValue.toLowerCase()] || 0;
}
return 0;
}
/**
* Converts old-style severity settings (0, 1, 2) into new-style
* severity settings (off, warn, error) for all rules. Assumption is that severity
* values have already been validated as correct.
* @param {Object} config The config object to normalize.
* @returns {void}
*/
function normalizeToStrings(config) {
if (config.rules) {
Object.keys(config.rules).forEach(ruleId => {
const ruleConfig = config.rules[ruleId];
if (typeof ruleConfig === "number") {
config.rules[ruleId] = RULE_SEVERITY_STRINGS[ruleConfig] || RULE_SEVERITY_STRINGS[0];
} else if (Array.isArray(ruleConfig) && typeof ruleConfig[0] === "number") {
ruleConfig[0] = RULE_SEVERITY_STRINGS[ruleConfig[0]] || RULE_SEVERITY_STRINGS[0];
}
});
}
}
/**
* Determines if the severity for the given rule configuration represents an error.
* @param {int|string|Array} ruleConfig The configuration for an individual rule.
* @returns {boolean} True if the rule represents an error, false if not.
*/
function isErrorSeverity(ruleConfig) {
return getRuleSeverity(ruleConfig) === 2;
}
/**
* Checks whether a given config has valid severity or not.
* @param {number|string|Array} ruleConfig The configuration for an individual rule.
* @returns {boolean} `true` if the configuration has valid severity.
*/
function isValidSeverity(ruleConfig) {
let severity = Array.isArray(ruleConfig) ? ruleConfig[0] : ruleConfig;
if (typeof severity === "string") {
severity = severity.toLowerCase();
}
return VALID_SEVERITIES.indexOf(severity) !== -1;
}
/**
* Checks whether every rule of a given config has valid severity or not.
* @param {Object} config The configuration for rules.
* @returns {boolean} `true` if the configuration has valid severity.
*/
function isEverySeverityValid(config) {
return Object.keys(config).every(ruleId => isValidSeverity(config[ruleId]));
}
/**
* Normalizes a value for a global in a config
* @param {(boolean|string|null)} configuredValue The value given for a global in configuration or in
* a global directive comment
* @returns {("readable"|"writeable"|"off")} The value normalized as a string
* @throws Error if global value is invalid
*/
function normalizeConfigGlobal(configuredValue) {
switch (configuredValue) {
case "off":
return "off";
case true:
case "true":
case "writeable":
case "writable":
return "writable";
case null:
case false:
case "false":
case "readable":
case "readonly":
return "readonly";
default:
throw new Error(`'${configuredValue}' is not a valid configuration for a global (use 'readonly', 'writable', or 'off')`);
}
}
export {
getRuleSeverity,
normalizeToStrings,
isErrorSeverity,
isValidSeverity,
isEverySeverityValid,
normalizeConfigGlobal
};

View file

@ -0,0 +1,325 @@
/**
* @fileoverview Validates configs.
* @author Brandon Mills
*/
/* eslint class-methods-use-this: "off" */
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import util from "util";
import * as ConfigOps from "./config-ops.js";
import { emitDeprecationWarning } from "./deprecation-warnings.js";
import ajvOrig from "./ajv.js";
import configSchema from "../../conf/config-schema.js";
import BuiltInEnvironments from "../../conf/environments.js";
const ajv = ajvOrig();
const ruleValidators = new WeakMap();
const noop = Function.prototype;
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
let validateSchema;
const severityMap = {
error: 2,
warn: 1,
off: 0
};
const validated = new WeakSet();
//-----------------------------------------------------------------------------
// Exports
//-----------------------------------------------------------------------------
export default class ConfigValidator {
constructor({ builtInRules = new Map() } = {}) {
this.builtInRules = builtInRules;
}
/**
* Gets a complete options schema for a rule.
* @param {{create: Function, schema: (Array|null)}} rule A new-style rule object
* @returns {Object} JSON Schema for the rule's options.
*/
getRuleOptionsSchema(rule) {
if (!rule) {
return null;
}
const schema = rule.schema || rule.meta && rule.meta.schema;
// Given a tuple of schemas, insert warning level at the beginning
if (Array.isArray(schema)) {
if (schema.length) {
return {
type: "array",
items: schema,
minItems: 0,
maxItems: schema.length
};
}
return {
type: "array",
minItems: 0,
maxItems: 0
};
}
// Given a full schema, leave it alone
return schema || null;
}
/**
* Validates a rule's severity and returns the severity value. Throws an error if the severity is invalid.
* @param {options} options The given options for the rule.
* @returns {number|string} The rule's severity value
*/
validateRuleSeverity(options) {
const severity = Array.isArray(options) ? options[0] : options;
const normSeverity = typeof severity === "string" ? severityMap[severity.toLowerCase()] : severity;
if (normSeverity === 0 || normSeverity === 1 || normSeverity === 2) {
return normSeverity;
}
throw new Error(`\tSeverity should be one of the following: 0 = off, 1 = warn, 2 = error (you passed '${util.inspect(severity).replace(/'/gu, "\"").replace(/\n/gu, "")}').\n`);
}
/**
* Validates the non-severity options passed to a rule, based on its schema.
* @param {{create: Function}} rule The rule to validate
* @param {Array} localOptions The options for the rule, excluding severity
* @returns {void}
*/
validateRuleSchema(rule, localOptions) {
if (!ruleValidators.has(rule)) {
const schema = this.getRuleOptionsSchema(rule);
if (schema) {
ruleValidators.set(rule, ajv.compile(schema));
}
}
const validateRule = ruleValidators.get(rule);
if (validateRule) {
validateRule(localOptions);
if (validateRule.errors) {
throw new Error(validateRule.errors.map(
error => `\tValue ${JSON.stringify(error.data)} ${error.message}.\n`
).join(""));
}
}
}
/**
* Validates a rule's options against its schema.
* @param {{create: Function}|null} rule The rule that the config is being validated for
* @param {string} ruleId The rule's unique name.
* @param {Array|number} options The given options for the rule.
* @param {string|null} source The name of the configuration source to report in any errors. If null or undefined,
* no source is prepended to the message.
* @returns {void}
*/
validateRuleOptions(rule, ruleId, options, source = null) {
try {
const severity = this.validateRuleSeverity(options);
if (severity !== 0) {
this.validateRuleSchema(rule, Array.isArray(options) ? options.slice(1) : []);
}
} catch (err) {
const enhancedMessage = `Configuration for rule "${ruleId}" is invalid:\n${err.message}`;
if (typeof source === "string") {
throw new Error(`${source}:\n\t${enhancedMessage}`);
} else {
throw new Error(enhancedMessage);
}
}
}
/**
* Validates an environment object
* @param {Object} environment The environment config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded environments.
* @returns {void}
*/
validateEnvironment(
environment,
source,
getAdditionalEnv = noop
) {
// not having an environment is ok
if (!environment) {
return;
}
Object.keys(environment).forEach(id => {
const env = getAdditionalEnv(id) || BuiltInEnvironments.get(id) || null;
if (!env) {
const message = `${source}:\n\tEnvironment key "${id}" is unknown\n`;
throw new Error(message);
}
});
}
/**
* Validates a rules config object
* @param {Object} rulesConfig The rules config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {function(ruleId:string): Object} getAdditionalRule A map from strings to loaded rules
* @returns {void}
*/
validateRules(
rulesConfig,
source,
getAdditionalRule = noop
) {
if (!rulesConfig) {
return;
}
Object.keys(rulesConfig).forEach(id => {
const rule = getAdditionalRule(id) || this.builtInRules.get(id) || null;
this.validateRuleOptions(rule, id, rulesConfig[id], source);
});
}
/**
* Validates a `globals` section of a config file
* @param {Object} globalsConfig The `globals` section
* @param {string|null} source The name of the configuration source to report in the event of an error.
* @returns {void}
*/
validateGlobals(globalsConfig, source = null) {
if (!globalsConfig) {
return;
}
Object.entries(globalsConfig)
.forEach(([configuredGlobal, configuredValue]) => {
try {
ConfigOps.normalizeConfigGlobal(configuredValue);
} catch (err) {
throw new Error(`ESLint configuration of global '${configuredGlobal}' in ${source} is invalid:\n${err.message}`);
}
});
}
/**
* Validate `processor` configuration.
* @param {string|undefined} processorName The processor name.
* @param {string} source The name of config file.
* @param {function(id:string): Processor} getProcessor The getter of defined processors.
* @returns {void}
*/
validateProcessor(processorName, source, getProcessor) {
if (processorName && !getProcessor(processorName)) {
throw new Error(`ESLint configuration of processor in '${source}' is invalid: '${processorName}' was not found.`);
}
}
/**
* Formats an array of schema validation errors.
* @param {Array} errors An array of error messages to format.
* @returns {string} Formatted error message
*/
formatErrors(errors) {
return errors.map(error => {
if (error.keyword === "additionalProperties") {
const formattedPropertyPath = error.dataPath.length ? `${error.dataPath.slice(1)}.${error.params.additionalProperty}` : error.params.additionalProperty;
return `Unexpected top-level property "${formattedPropertyPath}"`;
}
if (error.keyword === "type") {
const formattedField = error.dataPath.slice(1);
const formattedExpectedType = Array.isArray(error.schema) ? error.schema.join("/") : error.schema;
const formattedValue = JSON.stringify(error.data);
return `Property "${formattedField}" is the wrong type (expected ${formattedExpectedType} but got \`${formattedValue}\`)`;
}
const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
return `"${field}" ${error.message}. Value: ${JSON.stringify(error.data)}`;
}).map(message => `\t- ${message}.\n`).join("");
}
/**
* Validates the top level properties of the config object.
* @param {Object} config The config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @returns {void}
*/
validateConfigSchema(config, source = null) {
validateSchema = validateSchema || ajv.compile(configSchema);
if (!validateSchema(config)) {
throw new Error(`ESLint configuration in ${source} is invalid:\n${this.formatErrors(validateSchema.errors)}`);
}
if (Object.hasOwnProperty.call(config, "ecmaFeatures")) {
emitDeprecationWarning(source, "ESLINT_LEGACY_ECMAFEATURES");
}
}
/**
* Validates an entire config object.
* @param {Object} config The config object to validate.
* @param {string} source The name of the configuration source to report in any errors.
* @param {function(ruleId:string): Object} [getAdditionalRule] A map from strings to loaded rules.
* @param {function(envId:string): Object} [getAdditionalEnv] A map from strings to loaded envs.
* @returns {void}
*/
validate(config, source, getAdditionalRule, getAdditionalEnv) {
this.validateConfigSchema(config, source);
this.validateRules(config.rules, source, getAdditionalRule);
this.validateEnvironment(config.env, source, getAdditionalEnv);
this.validateGlobals(config.globals, source);
for (const override of config.overrides || []) {
this.validateRules(override.rules, source, getAdditionalRule);
this.validateEnvironment(override.env, source, getAdditionalEnv);
this.validateGlobals(config.globals, source);
}
}
/**
* Validate config array object.
* @param {ConfigArray} configArray The config array to validate.
* @returns {void}
*/
validateConfigArray(configArray) {
const getPluginEnv = Map.prototype.get.bind(configArray.pluginEnvironments);
const getPluginProcessor = Map.prototype.get.bind(configArray.pluginProcessors);
const getPluginRule = Map.prototype.get.bind(configArray.pluginRules);
// Validate.
for (const element of configArray) {
if (validated.has(element)) {
continue;
}
validated.add(element);
this.validateEnvironment(element.env, element.name, getPluginEnv);
this.validateGlobals(element.globals, element.name);
this.validateProcessor(element.processor, element.name, getPluginProcessor);
this.validateRules(element.rules, element.name, getPluginRule);
}
}
}

View file

@ -0,0 +1,63 @@
/**
* @fileoverview Provide the function that emits deprecation warnings.
* @author Toru Nagashima <http://github.com/mysticatea>
*/
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
import path from "path";
//------------------------------------------------------------------------------
// Private
//------------------------------------------------------------------------------
// Defitions for deprecation warnings.
const deprecationWarningMessages = {
ESLINT_LEGACY_ECMAFEATURES:
"The 'ecmaFeatures' config file property is deprecated and has no effect.",
ESLINT_PERSONAL_CONFIG_LOAD:
"'~/.eslintrc.*' config files have been deprecated. " +
"Please use a config file per project or the '--config' option.",
ESLINT_PERSONAL_CONFIG_SUPPRESS:
"'~/.eslintrc.*' config files have been deprecated. " +
"Please remove it or add 'root:true' to the config files in your " +
"projects in order to avoid loading '~/.eslintrc.*' accidentally."
};
const sourceFileErrorCache = new Set();
/**
* Emits a deprecation warning containing a given filepath. A new deprecation warning is emitted
* for each unique file path, but repeated invocations with the same file path have no effect.
* No warnings are emitted if the `--no-deprecation` or `--no-warnings` Node runtime flags are active.
* @param {string} source The name of the configuration source to report the warning for.
* @param {string} errorCode The warning message to show.
* @returns {void}
*/
function emitDeprecationWarning(source, errorCode) {
const cacheKey = JSON.stringify({ source, errorCode });
if (sourceFileErrorCache.has(cacheKey)) {
return;
}
sourceFileErrorCache.add(cacheKey);
const rel = path.relative(process.cwd(), source);
const message = deprecationWarningMessages[errorCode];
process.emitWarning(
`${message} (found in "${rel}")`,
"DeprecationWarning",
errorCode
);
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export {
emitDeprecationWarning
};

View file

@ -0,0 +1,96 @@
/**
* @fileoverview Common helpers for naming of plugins, formatters and configs
*/
const NAMESPACE_REGEX = /^@.*\//iu;
/**
* Brings package name to correct format based on prefix
* @param {string} name The name of the package.
* @param {string} prefix Can be either "eslint-plugin", "eslint-config" or "eslint-formatter"
* @returns {string} Normalized name of the package
* @private
*/
function normalizePackageName(name, prefix) {
let normalizedName = name;
/**
* On Windows, name can come in with Windows slashes instead of Unix slashes.
* Normalize to Unix first to avoid errors later on.
* https://github.com/eslint/eslint/issues/5644
*/
if (normalizedName.includes("\\")) {
normalizedName = normalizedName.replace(/\\/gu, "/");
}
if (normalizedName.charAt(0) === "@") {
/**
* it's a scoped package
* package name is the prefix, or just a username
*/
const scopedPackageShortcutRegex = new RegExp(`^(@[^/]+)(?:/(?:${prefix})?)?$`, "u"),
scopedPackageNameRegex = new RegExp(`^${prefix}(-|$)`, "u");
if (scopedPackageShortcutRegex.test(normalizedName)) {
normalizedName = normalizedName.replace(scopedPackageShortcutRegex, `$1/${prefix}`);
} else if (!scopedPackageNameRegex.test(normalizedName.split("/")[1])) {
/**
* for scoped packages, insert the prefix after the first / unless
* the path is already @scope/eslint or @scope/eslint-xxx-yyy
*/
normalizedName = normalizedName.replace(/^@([^/]+)\/(.*)$/u, `@$1/${prefix}-$2`);
}
} else if (!normalizedName.startsWith(`${prefix}-`)) {
normalizedName = `${prefix}-${normalizedName}`;
}
return normalizedName;
}
/**
* Removes the prefix from a fullname.
* @param {string} fullname The term which may have the prefix.
* @param {string} prefix The prefix to remove.
* @returns {string} The term without prefix.
*/
function getShorthandName(fullname, prefix) {
if (fullname[0] === "@") {
let matchResult = new RegExp(`^(@[^/]+)/${prefix}$`, "u").exec(fullname);
if (matchResult) {
return matchResult[1];
}
matchResult = new RegExp(`^(@[^/]+)/${prefix}-(.+)$`, "u").exec(fullname);
if (matchResult) {
return `${matchResult[1]}/${matchResult[2]}`;
}
} else if (fullname.startsWith(`${prefix}-`)) {
return fullname.slice(prefix.length + 1);
}
return fullname;
}
/**
* Gets the scope (namespace) of a term.
* @param {string} term The term which may have the namespace.
* @returns {string} The namespace of the term if it has one.
*/
function getNamespaceFromTerm(term) {
const match = term.match(NAMESPACE_REGEX);
return match ? match[0] : "";
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
export {
normalizePackageName,
getShorthandName,
getNamespaceFromTerm
};

View file

@ -0,0 +1,42 @@
/**
* Utility for resolving a module relative to another module
* @author Teddy Katz
*/
import Module from "module";
/*
* `Module.createRequire` is added in v12.2.0. It supports URL as well.
* We only support the case where the argument is a filepath, not a URL.
*/
const createRequire = Module.createRequire;
/**
* Resolves a Node module relative to another module
* @param {string} moduleName The name of a Node module, or a path to a Node module.
* @param {string} relativeToPath An absolute path indicating the module that `moduleName` should be resolved relative to. This must be
* a file rather than a directory, but the file need not actually exist.
* @returns {string} The absolute path that would result from calling `require.resolve(moduleName)` in a file located at `relativeToPath`
*/
function resolve(moduleName, relativeToPath) {
try {
return createRequire(relativeToPath).resolve(moduleName);
} catch (error) {
// This `if` block is for older Node.js than 12.0.0. We can remove this block in the future.
if (
typeof error === "object" &&
error !== null &&
error.code === "MODULE_NOT_FOUND" &&
!error.requireStack &&
error.message.includes(moduleName)
) {
error.message += `\nRequire stack:\n- ${relativeToPath}`;
}
throw error;
}
}
export {
resolve
};

View file

@ -0,0 +1,149 @@
/**
* @fileoverview Define common types for input completion.
* @author Toru Nagashima <https://github.com/mysticatea>
*/
/** @type {any} */
export default {};
/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */
/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */
/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */
/**
* @typedef {Object} EcmaFeatures
* @property {boolean} [globalReturn] Enabling `return` statements at the top-level.
* @property {boolean} [jsx] Enabling JSX syntax.
* @property {boolean} [impliedStrict] Enabling strict mode always.
*/
/**
* @typedef {Object} ParserOptions
* @property {EcmaFeatures} [ecmaFeatures] The optional features.
* @property {3|5|6|7|8|9|10|11|12|2015|2016|2017|2018|2019|2020|2021} [ecmaVersion] The ECMAScript version (or revision number).
* @property {"script"|"module"} [sourceType] The source code type.
*/
/**
* @typedef {Object} ConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {string | string[]} [ignorePatterns] The glob patterns that ignore to lint.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {boolean} [root] The root flag.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} OverrideConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [excludedFiles] The glob pattarns for excluded files.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {string | string[]} files The glob patterns for target files.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} ParseResult
* @property {Object} ast The AST.
* @property {ScopeManager} [scopeManager] The scope manager of the AST.
* @property {Record<string, any>} [services] The services that the parser provides.
* @property {Record<string, string[]>} [visitorKeys] The visitor keys of the AST.
*/
/**
* @typedef {Object} Parser
* @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables.
* @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} Environment
* @property {Record<string, GlobalConf>} [globals] The definition of global variables.
* @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} LintMessage
* @property {number} column The 1-based column number.
* @property {number} [endColumn] The 1-based column number of the end location.
* @property {number} [endLine] The 1-based line number of the end location.
* @property {boolean} fatal If `true` then this is a fatal error.
* @property {{range:[number,number], text:string}} [fix] Information for autofix.
* @property {number} line The 1-based line number.
* @property {string} message The error message.
* @property {string|null} ruleId The ID of the rule which makes this message.
* @property {0|1|2} severity The severity of this message.
* @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions.
*/
/**
* @typedef {Object} SuggestionResult
* @property {string} desc A short description.
* @property {string} [messageId] Id referencing a message for the description.
* @property {{ text: string, range: number[] }} fix fix result info
*/
/**
* @typedef {Object} Processor
* @property {(text:string, filename:string) => Array<string | { text:string, filename:string }>} [preprocess] The function to extract code blocks.
* @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages.
* @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix.
*/
/**
* @typedef {Object} RuleMetaDocs
* @property {string} category The category of the rule.
* @property {string} description The description of the rule.
* @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset.
* @property {string} url The URL of the rule documentation.
*/
/**
* @typedef {Object} RuleMeta
* @property {boolean} [deprecated] If `true` then the rule has been deprecated.
* @property {RuleMetaDocs} docs The document information of the rule.
* @property {"code"|"whitespace"} [fixable] The autofix type.
* @property {Record<string,string>} [messages] The messages the rule reports.
* @property {string[]} [replacedBy] The IDs of the alternative rules.
* @property {Array|Object} schema The option schema of the rule.
* @property {"problem"|"suggestion"|"layout"} type The rule type.
*/
/**
* @typedef {Object} Rule
* @property {Function} create The factory of the rule.
* @property {RuleMeta} meta The meta data of the rule.
*/
/**
* @typedef {Object} Plugin
* @property {Record<string, ConfigData>} [configs] The definition of plugin configs.
* @property {Record<string, Environment>} [environments] The definition of plugin environments.
* @property {Record<string, Processor>} [processors] The definition of plugin processors.
* @property {Record<string, Function | Rule>} [rules] The definition of plugin rules.
*/
/**
* Information of deprecated rules.
* @typedef {Object} DeprecatedRuleInfo
* @property {string} ruleId The rule ID.
* @property {string[]} replacedBy The rule IDs that replace this deprecated rule.
*/

View file

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

View file

@ -0,0 +1,129 @@
# brace-expansion
[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
as known from sh/bash, in JavaScript.
[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)
[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
## Example
```js
var expand = require('brace-expansion');
expand('file-{a,b,c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('-v{,,}')
// => ['-v', '-v', '-v']
expand('file{0..2}.jpg')
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
expand('file-{a..c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('file{2..0}.jpg')
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
expand('file{0..4..2}.jpg')
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
expand('file-{a..e..2}.jpg')
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
expand('file{00..10..5}.jpg')
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
expand('{{A..C},{a..c}}')
// => ['A', 'B', 'C', 'a', 'b', 'c']
expand('ppp{,config,oe{,conf}}')
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
```
## API
```js
var expand = require('brace-expansion');
```
### var expanded = expand(str)
Return an array of all possible and valid expansions of `str`. If none are
found, `[str]` is returned.
Valid expansions are:
```js
/^(.*,)+(.+)?$/
// {a,b,...}
```
A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
A numeric sequence from `x` to `y` inclusive, with optional increment.
If `x` or `y` start with a leading `0`, all the numbers will be padded
to have equal length. Negative numbers and backwards iteration work too.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
An alphabetic sequence from `x` to `y` inclusive, with optional increment.
`x` and `y` must be exactly one character, and if given, `incr` must be a
number.
For compatibility reasons, the string `${` is not eligible for brace expansion.
## Installation
With [npm](https://npmjs.org) do:
```bash
npm install brace-expansion
```
## Contributors
- [Julian Gruber](https://github.com/juliangruber)
- [Isaac Z. Schlueter](https://github.com/isaacs)
## Sponsors
This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!
Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,201 @@
var concatMap = require('concat-map');
var balanced = require('balanced-match');
module.exports = expandTop;
var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';
function numeric(str) {
return parseInt(str, 10) == str
? parseInt(str, 10)
: str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split('\\\\').join(escSlash)
.split('\\{').join(escOpen)
.split('\\}').join(escClose)
.split('\\,').join(escComma)
.split('\\.').join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join('\\')
.split(escOpen).join('{')
.split(escClose).join('}')
.split(escComma).join(',')
.split(escPeriod).join('.');
}
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
if (!str)
return [''];
var parts = [];
var m = balanced('{', '}', str);
if (!m)
return str.split(',');
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(',');
p[p.length-1] += '{' + body + '}';
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length-1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
// I don't know why Bash 4.3 does this, but it does.
// Anything starting with {} will have the first two bytes preserved
// but *only* at the top level, so {},a}b will not expand to anything,
// but a{},b}c will be expanded to [a}c,abc].
// One could argue that this is a bug in Bash, but since the goal of
// this module is to match Bash's rules, we escape a leading {}
if (str.substr(0, 2) === '{}') {
str = '\\{\\}' + str.substr(2);
}
return expand(escapeBraces(str), true).map(unescapeBraces);
}
function identity(e) {
return e;
}
function embrace(str) {
return '{' + str + '}';
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand(str, isTop) {
var expansions = [];
var m = balanced('{', '}', str);
if (!m || /\$$/.test(m.pre)) return [str];
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m.body.indexOf(',') >= 0;
if (!isSequence && !isOptions) {
// {a},b}
if (m.post.match(/,.*\}/)) {
str = m.pre + '{' + m.body + escClose + m.post;
return expand(str);
}
return [str];
}
var n;
if (isSequence) {
n = m.body.split(/\.\./);
} else {
n = parseCommaParts(m.body);
if (n.length === 1) {
// x{{a,b}}y ==> x{a}y x{b}y
n = expand(n[0], false).map(embrace);
if (n.length === 1) {
var post = m.post.length
? expand(m.post, false)
: [''];
return post.map(function(p) {
return m.pre + n[0] + p;
});
}
}
}
// at this point, n is the parts, and we know it's not a comma set
// with a single entry.
// no need to expand pre, since it is guaranteed to be free of brace-sets
var pre = m.pre;
var post = m.post.length
? expand(m.post, false)
: [''];
var N;
if (isSequence) {
var x = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length)
var incr = n.length == 3
? Math.abs(numeric(n[2]))
: 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === '\\')
c = '';
} else {
c = String(i);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join('0');
if (i < 0)
c = '-' + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = concatMap(n, function(el) { return expand(el, false) });
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
return expansions;
}

View file

@ -0,0 +1,47 @@
{
"name": "brace-expansion",
"description": "Brace expansion as known from sh/bash",
"version": "1.1.11",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/brace-expansion.git"
},
"homepage": "https://github.com/juliangruber/brace-expansion",
"main": "index.js",
"scripts": {
"test": "tape test/*.js",
"gentest": "bash test/generate.sh",
"bench": "matcha test/perf/bench.js"
},
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
},
"devDependencies": {
"matcha": "^0.7.0",
"tape": "^4.6.0"
},
"keywords": [],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT",
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"firefox/20..latest",
"firefox/nightly",
"chrome/25..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
}
}

View file

@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View file

@ -0,0 +1,230 @@
# minimatch
A minimal matching utility.
[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch)
This is the matching library used internally by npm.
It works by converting glob expressions into JavaScript `RegExp`
objects.
## Usage
```javascript
var minimatch = require("minimatch")
minimatch("bar.foo", "*.foo") // true!
minimatch("bar.foo", "*.bar") // false!
minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy!
```
## Features
Supports these glob features:
* Brace Expansion
* Extended glob matching
* "Globstar" `**` matching
See:
* `man sh`
* `man bash`
* `man 3 fnmatch`
* `man 5 gitignore`
## Minimatch Class
Create a minimatch object by instantiating the `minimatch.Minimatch` class.
```javascript
var Minimatch = require("minimatch").Minimatch
var mm = new Minimatch(pattern, options)
```
### Properties
* `pattern` The original pattern the minimatch object represents.
* `options` The options supplied to the constructor.
* `set` A 2-dimensional array of regexp or string expressions.
Each row in the
array corresponds to a brace-expanded pattern. Each item in the row
corresponds to a single path-part. For example, the pattern
`{a,b/c}/d` would expand to a set of patterns like:
[ [ a, d ]
, [ b, c, d ] ]
If a portion of the pattern doesn't have any "magic" in it
(that is, it's something like `"foo"` rather than `fo*o?`), then it
will be left as a string rather than converted to a regular
expression.
* `regexp` Created by the `makeRe` method. A single regular expression
expressing the entire pattern. This is useful in cases where you wish
to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
* `negate` True if the pattern is negated.
* `comment` True if the pattern is a comment.
* `empty` True if the pattern is `""`.
### Methods
* `makeRe` Generate the `regexp` member if necessary, and return it.
Will return `false` if the pattern is invalid.
* `match(fname)` Return true if the filename matches the pattern, or
false otherwise.
* `matchOne(fileArray, patternArray, partial)` Take a `/`-split
filename, and match it against a single row in the `regExpSet`. This
method is mainly for internal use, but is exposed so that it can be
used by a glob-walker that needs to avoid excessive filesystem calls.
All other methods are internal, and will be called as necessary.
### minimatch(path, pattern, options)
Main export. Tests a path against the pattern using the options.
```javascript
var isJS = minimatch(file, "*.js", { matchBase: true })
```
### minimatch.filter(pattern, options)
Returns a function that tests its
supplied argument, suitable for use with `Array.filter`. Example:
```javascript
var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true}))
```
### minimatch.match(list, pattern, options)
Match against the list of
files, in the style of fnmatch or glob. If nothing is matched, and
options.nonull is set, then return a list containing the pattern itself.
```javascript
var javascripts = minimatch.match(fileList, "*.js", {matchBase: true}))
```
### minimatch.makeRe(pattern, options)
Make a regular expression object from the pattern.
## Options
All options are `false` by default.
### debug
Dump a ton of stuff to stderr.
### nobrace
Do not expand `{a,b}` and `{1..3}` brace sets.
### noglobstar
Disable `**` matching against multiple folder names.
### dot
Allow patterns to match filenames starting with a period, even if
the pattern does not explicitly have a period in that spot.
Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
is set.
### noext
Disable "extglob" style patterns like `+(a|b)`.
### nocase
Perform a case-insensitive match.
### nonull
When a match is not found by `minimatch.match`, return a list containing
the pattern itself if this option is set. When not set, an empty list
is returned if there are no matches.
### matchBase
If set, then patterns without slashes will be matched
against the basename of the path if it contains slashes. For example,
`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
### nocomment
Suppress the behavior of treating `#` at the start of a pattern as a
comment.
### nonegate
Suppress the behavior of treating a leading `!` character as negation.
### flipNegate
Returns from negate expressions the same as if they were not negated.
(Ie, true on a hit, false on a miss.)
### partial
Compare a partial path to a pattern. As long as the parts of the path that
are present are not contradicted by the pattern, it will be treated as a
match. This is useful in applications where you're walking through a
folder structure, and don't yet have the full path, but want to ensure that
you do not walk down paths that can never be a match.
For example,
```js
minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d
minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d
minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a
```
### allowWindowsEscape
Windows path separator `\` is by default converted to `/`, which
prohibits the usage of `\` as a escape character. This flag skips that
behavior and allows using the escape character.
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between minimatch and other
implementations, and are intentional.
If the pattern starts with a `!` character, then it is negated. Set the
`nonegate` flag to suppress this behavior, and treat leading `!`
characters normally. This is perhaps relevant if you wish to start the
pattern with a negative extglob pattern like `!(a|B)`. Multiple `!`
characters at the start of a pattern will negate the pattern multiple
times.
If a pattern starts with `#`, then it is treated as a comment, and
will not match anything. Use `\#` to match a literal `#` at the
start of a line, or set the `nocomment` flag to suppress this behavior.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.1, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
If an escaped pattern has no matches, and the `nonull` flag is set,
then minimatch.match returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.

View file

@ -0,0 +1,947 @@
module.exports = minimatch
minimatch.Minimatch = Minimatch
var path = (function () { try { return require('path') } catch (e) {}}()) || {
sep: '/'
}
minimatch.sep = path.sep
var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
var expand = require('brace-expansion')
var plTypes = {
'!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
'?': { open: '(?:', close: ')?' },
'+': { open: '(?:', close: ')+' },
'*': { open: '(?:', close: ')*' },
'@': { open: '(?:', close: ')' }
}
// any single thing other than /
// don't need to escape / when using new RegExp()
var qmark = '[^/]'
// * => any number of characters
var star = qmark + '*?'
// ** when dots are allowed. Anything goes, except .. and .
// not (^ or / followed by one or two dots followed by $ or /),
// followed by anything, any number of times.
var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
// not a ^ or / followed by a dot,
// followed by anything, any number of times.
var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
// characters that need to be escaped in RegExp.
var reSpecials = charSet('().*{}+?[]^$\\!')
// "abc" -> { a:true, b:true, c:true }
function charSet (s) {
return s.split('').reduce(function (set, c) {
set[c] = true
return set
}, {})
}
// normalizes slashes.
var slashSplit = /\/+/
minimatch.filter = filter
function filter (pattern, options) {
options = options || {}
return function (p, i, list) {
return minimatch(p, pattern, options)
}
}
function ext (a, b) {
b = b || {}
var t = {}
Object.keys(a).forEach(function (k) {
t[k] = a[k]
})
Object.keys(b).forEach(function (k) {
t[k] = b[k]
})
return t
}
minimatch.defaults = function (def) {
if (!def || typeof def !== 'object' || !Object.keys(def).length) {
return minimatch
}
var orig = minimatch
var m = function minimatch (p, pattern, options) {
return orig(p, pattern, ext(def, options))
}
m.Minimatch = function Minimatch (pattern, options) {
return new orig.Minimatch(pattern, ext(def, options))
}
m.Minimatch.defaults = function defaults (options) {
return orig.defaults(ext(def, options)).Minimatch
}
m.filter = function filter (pattern, options) {
return orig.filter(pattern, ext(def, options))
}
m.defaults = function defaults (options) {
return orig.defaults(ext(def, options))
}
m.makeRe = function makeRe (pattern, options) {
return orig.makeRe(pattern, ext(def, options))
}
m.braceExpand = function braceExpand (pattern, options) {
return orig.braceExpand(pattern, ext(def, options))
}
m.match = function (list, pattern, options) {
return orig.match(list, pattern, ext(def, options))
}
return m
}
Minimatch.defaults = function (def) {
return minimatch.defaults(def).Minimatch
}
function minimatch (p, pattern, options) {
assertValidPattern(pattern)
if (!options) options = {}
// shortcut: comments match nothing.
if (!options.nocomment && pattern.charAt(0) === '#') {
return false
}
return new Minimatch(pattern, options).match(p)
}
function Minimatch (pattern, options) {
if (!(this instanceof Minimatch)) {
return new Minimatch(pattern, options)
}
assertValidPattern(pattern)
if (!options) options = {}
pattern = pattern.trim()
// windows support: need to use /, not \
if (!options.allowWindowsEscape && path.sep !== '/') {
pattern = pattern.split(path.sep).join('/')
}
this.options = options
this.set = []
this.pattern = pattern
this.regexp = null
this.negate = false
this.comment = false
this.empty = false
this.partial = !!options.partial
// make the set of regexps etc.
this.make()
}
Minimatch.prototype.debug = function () {}
Minimatch.prototype.make = make
function make () {
var pattern = this.pattern
var options = this.options
// empty patterns and comments match nothing.
if (!options.nocomment && pattern.charAt(0) === '#') {
this.comment = true
return
}
if (!pattern) {
this.empty = true
return
}
// step 1: figure out negation, etc.
this.parseNegate()
// step 2: expand braces
var set = this.globSet = this.braceExpand()
if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) }
this.debug(this.pattern, set)
// step 3: now we have a set, so turn each one into a series of path-portion
// matching patterns.
// These will be regexps, except in the case of "**", which is
// set to the GLOBSTAR object for globstar behavior,
// and will not contain any / characters
set = this.globParts = set.map(function (s) {
return s.split(slashSplit)
})
this.debug(this.pattern, set)
// glob --> regexps
set = set.map(function (s, si, set) {
return s.map(this.parse, this)
}, this)
this.debug(this.pattern, set)
// filter out everything that didn't compile properly.
set = set.filter(function (s) {
return s.indexOf(false) === -1
})
this.debug(this.pattern, set)
this.set = set
}
Minimatch.prototype.parseNegate = parseNegate
function parseNegate () {
var pattern = this.pattern
var negate = false
var options = this.options
var negateOffset = 0
if (options.nonegate) return
for (var i = 0, l = pattern.length
; i < l && pattern.charAt(i) === '!'
; i++) {
negate = !negate
negateOffset++
}
if (negateOffset) this.pattern = pattern.substr(negateOffset)
this.negate = negate
}
// Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
minimatch.braceExpand = function (pattern, options) {
return braceExpand(pattern, options)
}
Minimatch.prototype.braceExpand = braceExpand
function braceExpand (pattern, options) {
if (!options) {
if (this instanceof Minimatch) {
options = this.options
} else {
options = {}
}
}
pattern = typeof pattern === 'undefined'
? this.pattern : pattern
assertValidPattern(pattern)
// Thanks to Yeting Li <https://github.com/yetingli> for
// improving this regexp to avoid a ReDOS vulnerability.
if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
// shortcut. no need to expand.
return [pattern]
}
return expand(pattern)
}
var MAX_PATTERN_LENGTH = 1024 * 64
var assertValidPattern = function (pattern) {
if (typeof pattern !== 'string') {
throw new TypeError('invalid pattern')
}
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new TypeError('pattern is too long')
}
}
// parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion. Otherwise, any series
// of * is equivalent to a single *. Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
Minimatch.prototype.parse = parse
var SUBPARSE = {}
function parse (pattern, isSub) {
assertValidPattern(pattern)
var options = this.options
// shortcuts
if (pattern === '**') {
if (!options.noglobstar)
return GLOBSTAR
else
pattern = '*'
}
if (pattern === '') return ''
var re = ''
var hasMagic = !!options.nocase
var escaping = false
// ? => one single character
var patternListStack = []
var negativeLists = []
var stateChar
var inClass = false
var reClassStart = -1
var classStart = -1
// . and .. never match anything that doesn't start with .,
// even when options.dot is set.
var patternStart = pattern.charAt(0) === '.' ? '' // anything
// not (start or / followed by . or .. followed by / or end)
: options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
: '(?!\\.)'
var self = this
function clearStateChar () {
if (stateChar) {
// we had some state-tracking character
// that wasn't consumed by this pass.
switch (stateChar) {
case '*':
re += star
hasMagic = true
break
case '?':
re += qmark
hasMagic = true
break
default:
re += '\\' + stateChar
break
}
self.debug('clearStateChar %j %j', stateChar, re)
stateChar = false
}
}
for (var i = 0, len = pattern.length, c
; (i < len) && (c = pattern.charAt(i))
; i++) {
this.debug('%s\t%s %s %j', pattern, i, re, c)
// skip over any that are escaped.
if (escaping && reSpecials[c]) {
re += '\\' + c
escaping = false
continue
}
switch (c) {
/* istanbul ignore next */
case '/': {
// completely not allowed, even escaped.
// Should already be path-split by now.
return false
}
case '\\':
clearStateChar()
escaping = true
continue
// the various stateChar values
// for the "extglob" stuff.
case '?':
case '*':
case '+':
case '@':
case '!':
this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
// all of those are literals inside a class, except that
// the glob [!a] means [^a] in regexp
if (inClass) {
this.debug(' in class')
if (c === '!' && i === classStart + 1) c = '^'
re += c
continue
}
// if we already have a stateChar, then it means
// that there was something like ** or +? in there.
// Handle the stateChar, then proceed with this one.
self.debug('call clearStateChar %j', stateChar)
clearStateChar()
stateChar = c
// if extglob is disabled, then +(asdf|foo) isn't a thing.
// just clear the statechar *now*, rather than even diving into
// the patternList stuff.
if (options.noext) clearStateChar()
continue
case '(':
if (inClass) {
re += '('
continue
}
if (!stateChar) {
re += '\\('
continue
}
patternListStack.push({
type: stateChar,
start: i - 1,
reStart: re.length,
open: plTypes[stateChar].open,
close: plTypes[stateChar].close
})
// negation is (?:(?!js)[^/]*)
re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
this.debug('plType %j %j', stateChar, re)
stateChar = false
continue
case ')':
if (inClass || !patternListStack.length) {
re += '\\)'
continue
}
clearStateChar()
hasMagic = true
var pl = patternListStack.pop()
// negation is (?:(?!js)[^/]*)
// The others are (?:<pattern>)<type>
re += pl.close
if (pl.type === '!') {
negativeLists.push(pl)
}
pl.reEnd = re.length
continue
case '|':
if (inClass || !patternListStack.length || escaping) {
re += '\\|'
escaping = false
continue
}
clearStateChar()
re += '|'
continue
// these are mostly the same in regexp and glob
case '[':
// swallow any state-tracking char before the [
clearStateChar()
if (inClass) {
re += '\\' + c
continue
}
inClass = true
classStart = i
reClassStart = re.length
re += c
continue
case ']':
// a right bracket shall lose its special
// meaning and represent itself in
// a bracket expression if it occurs
// first in the list. -- POSIX.2 2.8.3.2
if (i === classStart + 1 || !inClass) {
re += '\\' + c
escaping = false
continue
}
// handle the case where we left a class open.
// "[z-a]" is valid, equivalent to "\[z-a\]"
// split where the last [ was, make sure we don't have
// an invalid re. if so, re-walk the contents of the
// would-be class to re-translate any characters that
// were passed through as-is
// TODO: It would probably be faster to determine this
// without a try/catch and a new RegExp, but it's tricky
// to do safely. For now, this is safe and works.
var cs = pattern.substring(classStart + 1, i)
try {
RegExp('[' + cs + ']')
} catch (er) {
// not a valid class!
var sp = this.parse(cs, SUBPARSE)
re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
hasMagic = hasMagic || sp[1]
inClass = false
continue
}
// finish up the class.
hasMagic = true
inClass = false
re += c
continue
default:
// swallow any state char that wasn't consumed
clearStateChar()
if (escaping) {
// no need
escaping = false
} else if (reSpecials[c]
&& !(c === '^' && inClass)) {
re += '\\'
}
re += c
} // switch
} // for
// handle the case where we left a class open.
// "[abc" is valid, equivalent to "\[abc"
if (inClass) {
// split where the last [ was, and escape it
// this is a huge pita. We now have to re-walk
// the contents of the would-be class to re-translate
// any characters that were passed through as-is
cs = pattern.substr(classStart + 1)
sp = this.parse(cs, SUBPARSE)
re = re.substr(0, reClassStart) + '\\[' + sp[0]
hasMagic = hasMagic || sp[1]
}
// handle the case where we had a +( thing at the *end*
// of the pattern.
// each pattern list stack adds 3 chars, and we need to go through
// and escape any | chars that were passed through as-is for the regexp.
// Go through and escape them, taking care not to double-escape any
// | chars that were already escaped.
for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
var tail = re.slice(pl.reStart + pl.open.length)
this.debug('setting tail', re, pl)
// maybe some even number of \, then maybe 1 \, followed by a |
tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) {
if (!$2) {
// the | isn't already escaped, so escape it.
$2 = '\\'
}
// need to escape all those slashes *again*, without escaping the
// one that we need for escaping the | character. As it works out,
// escaping an even number of slashes can be done by simply repeating
// it exactly after itself. That's why this trick works.
//
// I am sorry that you have to see this.
return $1 + $1 + $2 + '|'
})
this.debug('tail=%j\n %s', tail, tail, pl, re)
var t = pl.type === '*' ? star
: pl.type === '?' ? qmark
: '\\' + pl.type
hasMagic = true
re = re.slice(0, pl.reStart) + t + '\\(' + tail
}
// handle trailing things that only matter at the very end.
clearStateChar()
if (escaping) {
// trailing \\
re += '\\\\'
}
// only need to apply the nodot start if the re starts with
// something that could conceivably capture a dot
var addPatternStart = false
switch (re.charAt(0)) {
case '[': case '.': case '(': addPatternStart = true
}
// Hack to work around lack of negative lookbehind in JS
// A pattern like: *.!(x).!(y|z) needs to ensure that a name
// like 'a.xyz.yz' doesn't match. So, the first negative
// lookahead, has to look ALL the way ahead, to the end of
// the pattern.
for (var n = negativeLists.length - 1; n > -1; n--) {
var nl = negativeLists[n]
var nlBefore = re.slice(0, nl.reStart)
var nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
var nlLast = re.slice(nl.reEnd - 8, nl.reEnd)
var nlAfter = re.slice(nl.reEnd)
nlLast += nlAfter
// Handle nested stuff like *(*.js|!(*.json)), where open parens
// mean that we should *not* include the ) in the bit that is considered
// "after" the negated section.
var openParensBefore = nlBefore.split('(').length - 1
var cleanAfter = nlAfter
for (i = 0; i < openParensBefore; i++) {
cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
}
nlAfter = cleanAfter
var dollar = ''
if (nlAfter === '' && isSub !== SUBPARSE) {
dollar = '$'
}
var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast
re = newRe
}
// if the re is not "" at this point, then we need to make sure
// it doesn't match against an empty path part.
// Otherwise a/* will match a/, which it should not.
if (re !== '' && hasMagic) {
re = '(?=.)' + re
}
if (addPatternStart) {
re = patternStart + re
}
// parsing just a piece of a larger pattern.
if (isSub === SUBPARSE) {
return [re, hasMagic]
}
// skip the regexp for non-magical patterns
// unescape anything in it, though, so that it'll be
// an exact match against a file etc.
if (!hasMagic) {
return globUnescape(pattern)
}
var flags = options.nocase ? 'i' : ''
try {
var regExp = new RegExp('^' + re + '$', flags)
} catch (er) /* istanbul ignore next - should be impossible */ {
// If it was an invalid regular expression, then it can't match
// anything. This trick looks for a character after the end of
// the string, which is of course impossible, except in multi-line
// mode, but it's not a /m regex.
return new RegExp('$.')
}
regExp._glob = pattern
regExp._src = re
return regExp
}
minimatch.makeRe = function (pattern, options) {
return new Minimatch(pattern, options || {}).makeRe()
}
Minimatch.prototype.makeRe = makeRe
function makeRe () {
if (this.regexp || this.regexp === false) return this.regexp
// at this point, this.set is a 2d array of partial
// pattern strings, or "**".
//
// It's better to use .match(). This function shouldn't
// be used, really, but it's pretty convenient sometimes,
// when you just want to work with a regex.
var set = this.set
if (!set.length) {
this.regexp = false
return this.regexp
}
var options = this.options
var twoStar = options.noglobstar ? star
: options.dot ? twoStarDot
: twoStarNoDot
var flags = options.nocase ? 'i' : ''
var re = set.map(function (pattern) {
return pattern.map(function (p) {
return (p === GLOBSTAR) ? twoStar
: (typeof p === 'string') ? regExpEscape(p)
: p._src
}).join('\\\/')
}).join('|')
// must match entire pattern
// ending in a * or ** will make it less strict.
re = '^(?:' + re + ')$'
// can match anything, as long as it's not this.
if (this.negate) re = '^(?!' + re + ').*$'
try {
this.regexp = new RegExp(re, flags)
} catch (ex) /* istanbul ignore next - should be impossible */ {
this.regexp = false
}
return this.regexp
}
minimatch.match = function (list, pattern, options) {
options = options || {}
var mm = new Minimatch(pattern, options)
list = list.filter(function (f) {
return mm.match(f)
})
if (mm.options.nonull && !list.length) {
list.push(pattern)
}
return list
}
Minimatch.prototype.match = function match (f, partial) {
if (typeof partial === 'undefined') partial = this.partial
this.debug('match', f, this.pattern)
// short-circuit in the case of busted things.
// comments, etc.
if (this.comment) return false
if (this.empty) return f === ''
if (f === '/' && partial) return true
var options = this.options
// windows: need to use /, not \
if (path.sep !== '/') {
f = f.split(path.sep).join('/')
}
// treat the test path as a set of pathparts.
f = f.split(slashSplit)
this.debug(this.pattern, 'split', f)
// just ONE of the pattern sets in this.set needs to match
// in order for it to be valid. If negating, then just one
// match means that we have failed.
// Either way, return on the first hit.
var set = this.set
this.debug(this.pattern, 'set', set)
// Find the basename of the path by looking for the last non-empty segment
var filename
var i
for (i = f.length - 1; i >= 0; i--) {
filename = f[i]
if (filename) break
}
for (i = 0; i < set.length; i++) {
var pattern = set[i]
var file = f
if (options.matchBase && pattern.length === 1) {
file = [filename]
}
var hit = this.matchOne(file, pattern, partial)
if (hit) {
if (options.flipNegate) return true
return !this.negate
}
}
// didn't get any hits. this is success if it's a negative
// pattern, failure otherwise.
if (options.flipNegate) return false
return this.negate
}
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
Minimatch.prototype.matchOne = function (file, pattern, partial) {
var options = this.options
this.debug('matchOne',
{ 'this': this, file: file, pattern: pattern })
this.debug('matchOne', file.length, pattern.length)
for (var fi = 0,
pi = 0,
fl = file.length,
pl = pattern.length
; (fi < fl) && (pi < pl)
; fi++, pi++) {
this.debug('matchOne loop')
var p = pattern[pi]
var f = file[fi]
this.debug(pattern, p, f)
// should be impossible.
// some invalid regexp stuff in the set.
/* istanbul ignore if */
if (p === false) return false
if (p === GLOBSTAR) {
this.debug('GLOBSTAR', [pattern, p, f])
// "**"
// a/**/b/**/c would match the following:
// a/b/x/y/z/c
// a/x/y/z/b/c
// a/b/x/b/x/c
// a/b/c
// To do this, take the rest of the pattern after
// the **, and see if it would match the file remainder.
// If so, return success.
// If not, the ** "swallows" a segment, and try again.
// This is recursively awful.
//
// a/**/b/**/c matching a/b/x/y/z/c
// - a matches a
// - doublestar
// - matchOne(b/x/y/z/c, b/**/c)
// - b matches b
// - doublestar
// - matchOne(x/y/z/c, c) -> no
// - matchOne(y/z/c, c) -> no
// - matchOne(z/c, c) -> no
// - matchOne(c, c) yes, hit
var fr = fi
var pr = pi + 1
if (pr === pl) {
this.debug('** at the end')
// a ** at the end will just swallow the rest.
// We have found a match.
// however, it will not swallow /.x, unless
// options.dot is set.
// . and .. are *never* matched by **, for explosively
// exponential reasons.
for (; fi < fl; fi++) {
if (file[fi] === '.' || file[fi] === '..' ||
(!options.dot && file[fi].charAt(0) === '.')) return false
}
return true
}
// ok, let's see if we can swallow whatever we can.
while (fr < fl) {
var swallowee = file[fr]
this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
// XXX remove this slice. Just pass the start index.
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
this.debug('globstar found match!', fr, fl, swallowee)
// found a match.
return true
} else {
// can't swallow "." or ".." ever.
// can only swallow ".foo" when explicitly asked.
if (swallowee === '.' || swallowee === '..' ||
(!options.dot && swallowee.charAt(0) === '.')) {
this.debug('dot detected!', file, fr, pattern, pr)
break
}
// ** swallows a segment, and continue.
this.debug('globstar swallow a segment, and continue')
fr++
}
}
// no match was found.
// However, in partial mode, we can't say this is necessarily over.
// If there's more *pattern* left, then
/* istanbul ignore if */
if (partial) {
// ran out of file
this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
if (fr === fl) return true
}
return false
}
// something other than **
// non-magic patterns just have to match exactly
// patterns with magic have been turned into regexps.
var hit
if (typeof p === 'string') {
hit = f === p
this.debug('string match', p, f, hit)
} else {
hit = f.match(p)
this.debug('pattern match', p, f, hit)
}
if (!hit) return false
}
// Note: ending in / means that we'll get a final ""
// at the end of the pattern. This can only match a
// corresponding "" at the end of the file.
// If the file ends in /, then it can only match a
// a pattern that ends in /, unless the pattern just
// doesn't have any more for it. But, a/b/ should *not*
// match "a/b/*", even though "" matches against the
// [^/]*? pattern, except in partial mode, where it might
// simply not be reached yet.
// However, a/b/ should still satisfy a/*
// now either we fell off the end of the pattern, or we're done.
if (fi === fl && pi === pl) {
// ran out of pattern and filename at the same time.
// an exact hit!
return true
} else if (fi === fl) {
// ran out of file, but still had pattern left.
// this is ok if we're doing the match as part of
// a glob fs traversal.
return partial
} else /* istanbul ignore else */ if (pi === pl) {
// ran out of pattern, still have file left.
// this is only acceptable if we're on the very last
// empty segment of a file with a trailing slash.
// a/* should match a/b/
return (fi === fl - 1) && (file[fi] === '')
}
// should be unreachable.
/* istanbul ignore next */
throw new Error('wtf?')
}
// replace stuff like \* with *
function globUnescape (s) {
return s.replace(/\\(.)/g, '$1')
}
function regExpEscape (s) {
return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
}

View file

@ -0,0 +1,33 @@
{
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)",
"name": "minimatch",
"description": "a glob matcher in javascript",
"version": "3.1.2",
"publishConfig": {
"tag": "v3-legacy"
},
"repository": {
"type": "git",
"url": "git://github.com/isaacs/minimatch.git"
},
"main": "minimatch.js",
"scripts": {
"test": "tap",
"preversion": "npm test",
"postversion": "npm publish",
"postpublish": "git push origin --all; git push origin --tags"
},
"engines": {
"node": "*"
},
"dependencies": {
"brace-expansion": "^1.1.7"
},
"devDependencies": {
"tap": "^15.1.6"
},
"license": "ISC",
"files": [
"minimatch.js"
]
}

82
home/ags/node_modules/@eslint/eslintrc/package.json generated vendored Normal file
View file

@ -0,0 +1,82 @@
{
"name": "@eslint/eslintrc",
"version": "2.1.4",
"description": "The legacy ESLintRC config file format for ESLint",
"type": "module",
"main": "./dist/eslintrc.cjs",
"exports": {
".": {
"import": "./lib/index.js",
"require": "./dist/eslintrc.cjs"
},
"./package.json": "./package.json",
"./universal": {
"import": "./lib/index-universal.js",
"require": "./dist/eslintrc-universal.cjs"
}
},
"files": [
"lib",
"conf",
"LICENSE",
"dist",
"universal.js"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"build": "rollup -c",
"lint": "eslint . --report-unused-disable-directives",
"lint:fix": "npm run lint -- --fix",
"prepare": "npm run build",
"release:generate:latest": "eslint-generate-release",
"release:generate:alpha": "eslint-generate-prerelease alpha",
"release:generate:beta": "eslint-generate-prerelease beta",
"release:generate:rc": "eslint-generate-prerelease rc",
"release:publish": "eslint-publish-release",
"test": "mocha -R progress -c 'tests/lib/*.cjs' && c8 mocha -R progress -c 'tests/lib/**/*.js'"
},
"repository": "eslint/eslintrc",
"funding": "https://opencollective.com/eslint",
"keywords": [
"ESLint",
"ESLintRC",
"Configuration"
],
"author": "Nicholas C. Zakas",
"license": "MIT",
"bugs": {
"url": "https://github.com/eslint/eslintrc/issues"
},
"homepage": "https://github.com/eslint/eslintrc#readme",
"devDependencies": {
"c8": "^7.7.3",
"chai": "^4.3.4",
"eslint": "^7.31.0",
"eslint-config-eslint": "^7.0.0",
"eslint-plugin-jsdoc": "^35.4.1",
"eslint-plugin-node": "^11.1.0",
"eslint-release": "^3.2.0",
"fs-teardown": "^0.1.3",
"mocha": "^9.0.3",
"rollup": "^2.70.1",
"shelljs": "^0.8.4",
"sinon": "^11.1.2",
"temp-dir": "^2.0.0"
},
"dependencies": {
"ajv": "^6.12.4",
"debug": "^4.3.2",
"espree": "^9.6.0",
"globals": "^13.19.0",
"ignore": "^5.2.0",
"import-fresh": "^3.2.1",
"js-yaml": "^4.1.0",
"minimatch": "^3.1.2",
"strip-json-comments": "^3.1.1"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
}

9
home/ags/node_modules/@eslint/eslintrc/universal.js generated vendored Normal file
View file

@ -0,0 +1,9 @@
// Jest (and probably some other runtimes with custom implementations of
// `require`) doesn't support `exports` in `package.json`, so this file is here
// to help them load this module. Note that it is also `.js` and not `.cjs` for
// the same reason - `cjs` files requires to be loaded with an extension, but
// since Jest doesn't respect `module` outside of ESM mode it still works in
// this case (and the `require` in _this_ file does specify the extension).
// eslint-disable-next-line no-undef
module.exports = require("./dist/eslintrc-universal.cjs");

19
home/ags/node_modules/@eslint/js/LICENSE generated vendored Normal file
View file

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

57
home/ags/node_modules/@eslint/js/README.md generated vendored Normal file
View file

@ -0,0 +1,57 @@
[![npm version](https://img.shields.io/npm/v/@eslint/js.svg)](https://www.npmjs.com/package/@eslint/js)
# ESLint JavaScript Plugin
[Website](https://eslint.org) | [Configure ESLint](https://eslint.org/docs/latest/use/configure) | [Rules](https://eslint.org/docs/rules/) | [Contributing](https://eslint.org/docs/latest/contribute) | [Twitter](https://twitter.com/geteslint) | [Chatroom](https://eslint.org/chat)
The beginnings of separating out JavaScript-specific functionality from ESLint.
Right now, this plugin contains two configurations:
* `recommended` - enables the rules recommended by the ESLint team (the replacement for `"eslint:recommended"`)
* `all` - enables all ESLint rules (the replacement for `"eslint:all"`)
## Installation
```shell
npm install @eslint/js -D
```
## Usage
Use in your `eslint.config.js` file anytime you want to extend one of the configs:
```js
import js from "@eslint/js";
export default [
// apply recommended rules to JS files
{
files: ["**/*.js"],
rules: js.configs.recommended.rules
},
// apply recommended rules to JS files with an override
{
files: ["**/*.js"],
rules: {
...js.configs.recommended.rules,
"no-unused-vars": "warn"
}
},
// apply all rules to JS files
{
files: ["**/*.js"],
rules: {
...js.configs.all.rules,
"no-unused-vars": "warn"
}
}
]
```
## License
MIT

31
home/ags/node_modules/@eslint/js/package.json generated vendored Normal file
View file

@ -0,0 +1,31 @@
{
"name": "@eslint/js",
"version": "8.57.0",
"description": "ESLint JavaScript language implementation",
"main": "./src/index.js",
"scripts": {},
"files": [
"LICENSE",
"README.md",
"src"
],
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/eslint/eslint.git",
"directory": "packages/js"
},
"homepage": "https://eslint.org",
"bugs": "https://github.com/eslint/eslint/issues/",
"keywords": [
"javascript",
"eslint-plugin",
"eslint"
],
"license": "MIT",
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
}

View file

@ -0,0 +1,211 @@
/*
* WARNING: This file is autogenerated using the tools/update-eslint-all.js
* script. Do not edit manually.
*/
"use strict";
/* eslint quote-props: off -- autogenerated so don't lint */
module.exports = Object.freeze({
"rules": {
"accessor-pairs": "error",
"array-callback-return": "error",
"arrow-body-style": "error",
"block-scoped-var": "error",
"camelcase": "error",
"capitalized-comments": "error",
"class-methods-use-this": "error",
"complexity": "error",
"consistent-return": "error",
"consistent-this": "error",
"constructor-super": "error",
"curly": "error",
"default-case": "error",
"default-case-last": "error",
"default-param-last": "error",
"dot-notation": "error",
"eqeqeq": "error",
"for-direction": "error",
"func-name-matching": "error",
"func-names": "error",
"func-style": "error",
"getter-return": "error",
"grouped-accessor-pairs": "error",
"guard-for-in": "error",
"id-denylist": "error",
"id-length": "error",
"id-match": "error",
"init-declarations": "error",
"line-comment-position": "error",
"logical-assignment-operators": "error",
"max-classes-per-file": "error",
"max-depth": "error",
"max-lines": "error",
"max-lines-per-function": "error",
"max-nested-callbacks": "error",
"max-params": "error",
"max-statements": "error",
"multiline-comment-style": "error",
"new-cap": "error",
"no-alert": "error",
"no-array-constructor": "error",
"no-async-promise-executor": "error",
"no-await-in-loop": "error",
"no-bitwise": "error",
"no-caller": "error",
"no-case-declarations": "error",
"no-class-assign": "error",
"no-compare-neg-zero": "error",
"no-cond-assign": "error",
"no-console": "error",
"no-const-assign": "error",
"no-constant-binary-expression": "error",
"no-constant-condition": "error",
"no-constructor-return": "error",
"no-continue": "error",
"no-control-regex": "error",
"no-debugger": "error",
"no-delete-var": "error",
"no-div-regex": "error",
"no-dupe-args": "error",
"no-dupe-class-members": "error",
"no-dupe-else-if": "error",
"no-dupe-keys": "error",
"no-duplicate-case": "error",
"no-duplicate-imports": "error",
"no-else-return": "error",
"no-empty": "error",
"no-empty-character-class": "error",
"no-empty-function": "error",
"no-empty-pattern": "error",
"no-empty-static-block": "error",
"no-eq-null": "error",
"no-eval": "error",
"no-ex-assign": "error",
"no-extend-native": "error",
"no-extra-bind": "error",
"no-extra-boolean-cast": "error",
"no-extra-label": "error",
"no-fallthrough": "error",
"no-func-assign": "error",
"no-global-assign": "error",
"no-implicit-coercion": "error",
"no-implicit-globals": "error",
"no-implied-eval": "error",
"no-import-assign": "error",
"no-inline-comments": "error",
"no-inner-declarations": "error",
"no-invalid-regexp": "error",
"no-invalid-this": "error",
"no-irregular-whitespace": "error",
"no-iterator": "error",
"no-label-var": "error",
"no-labels": "error",
"no-lone-blocks": "error",
"no-lonely-if": "error",
"no-loop-func": "error",
"no-loss-of-precision": "error",
"no-magic-numbers": "error",
"no-misleading-character-class": "error",
"no-multi-assign": "error",
"no-multi-str": "error",
"no-negated-condition": "error",
"no-nested-ternary": "error",
"no-new": "error",
"no-new-func": "error",
"no-new-native-nonconstructor": "error",
"no-new-symbol": "error",
"no-new-wrappers": "error",
"no-nonoctal-decimal-escape": "error",
"no-obj-calls": "error",
"no-object-constructor": "error",
"no-octal": "error",
"no-octal-escape": "error",
"no-param-reassign": "error",
"no-plusplus": "error",
"no-promise-executor-return": "error",
"no-proto": "error",
"no-prototype-builtins": "error",
"no-redeclare": "error",
"no-regex-spaces": "error",
"no-restricted-exports": "error",
"no-restricted-globals": "error",
"no-restricted-imports": "error",
"no-restricted-properties": "error",
"no-restricted-syntax": "error",
"no-return-assign": "error",
"no-script-url": "error",
"no-self-assign": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-setter-return": "error",
"no-shadow": "error",
"no-shadow-restricted-names": "error",
"no-sparse-arrays": "error",
"no-template-curly-in-string": "error",
"no-ternary": "error",
"no-this-before-super": "error",
"no-throw-literal": "error",
"no-undef": "error",
"no-undef-init": "error",
"no-undefined": "error",
"no-underscore-dangle": "error",
"no-unexpected-multiline": "error",
"no-unmodified-loop-condition": "error",
"no-unneeded-ternary": "error",
"no-unreachable": "error",
"no-unreachable-loop": "error",
"no-unsafe-finally": "error",
"no-unsafe-negation": "error",
"no-unsafe-optional-chaining": "error",
"no-unused-expressions": "error",
"no-unused-labels": "error",
"no-unused-private-class-members": "error",
"no-unused-vars": "error",
"no-use-before-define": "error",
"no-useless-backreference": "error",
"no-useless-call": "error",
"no-useless-catch": "error",
"no-useless-computed-key": "error",
"no-useless-concat": "error",
"no-useless-constructor": "error",
"no-useless-escape": "error",
"no-useless-rename": "error",
"no-useless-return": "error",
"no-var": "error",
"no-void": "error",
"no-warning-comments": "error",
"no-with": "error",
"object-shorthand": "error",
"one-var": "error",
"operator-assignment": "error",
"prefer-arrow-callback": "error",
"prefer-const": "error",
"prefer-destructuring": "error",
"prefer-exponentiation-operator": "error",
"prefer-named-capture-group": "error",
"prefer-numeric-literals": "error",
"prefer-object-has-own": "error",
"prefer-object-spread": "error",
"prefer-promise-reject-errors": "error",
"prefer-regex-literals": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "error",
"radix": "error",
"require-atomic-updates": "error",
"require-await": "error",
"require-unicode-regexp": "error",
"require-yield": "error",
"sort-imports": "error",
"sort-keys": "error",
"sort-vars": "error",
"strict": "error",
"symbol-description": "error",
"unicode-bom": "error",
"use-isnan": "error",
"valid-typeof": "error",
"vars-on-top": "error",
"yoda": "error"
}
});

View file

@ -0,0 +1,76 @@
/**
* @fileoverview Configuration applied when a user configuration extends from
* eslint:recommended.
* @author Nicholas C. Zakas
*/
"use strict";
/* eslint sort-keys: ["error", "asc"] -- Long, so make more readable */
/** @type {import("../lib/shared/types").ConfigData} */
module.exports = Object.freeze({
rules: Object.freeze({
"constructor-super": "error",
"for-direction": "error",
"getter-return": "error",
"no-async-promise-executor": "error",
"no-case-declarations": "error",
"no-class-assign": "error",
"no-compare-neg-zero": "error",
"no-cond-assign": "error",
"no-const-assign": "error",
"no-constant-condition": "error",
"no-control-regex": "error",
"no-debugger": "error",
"no-delete-var": "error",
"no-dupe-args": "error",
"no-dupe-class-members": "error",
"no-dupe-else-if": "error",
"no-dupe-keys": "error",
"no-duplicate-case": "error",
"no-empty": "error",
"no-empty-character-class": "error",
"no-empty-pattern": "error",
"no-ex-assign": "error",
"no-extra-boolean-cast": "error",
"no-extra-semi": "error",
"no-fallthrough": "error",
"no-func-assign": "error",
"no-global-assign": "error",
"no-import-assign": "error",
"no-inner-declarations": "error",
"no-invalid-regexp": "error",
"no-irregular-whitespace": "error",
"no-loss-of-precision": "error",
"no-misleading-character-class": "error",
"no-mixed-spaces-and-tabs": "error",
"no-new-symbol": "error",
"no-nonoctal-decimal-escape": "error",
"no-obj-calls": "error",
"no-octal": "error",
"no-prototype-builtins": "error",
"no-redeclare": "error",
"no-regex-spaces": "error",
"no-self-assign": "error",
"no-setter-return": "error",
"no-shadow-restricted-names": "error",
"no-sparse-arrays": "error",
"no-this-before-super": "error",
"no-undef": "error",
"no-unexpected-multiline": "error",
"no-unreachable": "error",
"no-unsafe-finally": "error",
"no-unsafe-negation": "error",
"no-unsafe-optional-chaining": "error",
"no-unused-labels": "error",
"no-unused-vars": "error",
"no-useless-backreference": "error",
"no-useless-catch": "error",
"no-useless-escape": "error",
"no-with": "error",
"require-yield": "error",
"use-isnan": "error",
"valid-typeof": "error"
})
});

17
home/ags/node_modules/@eslint/js/src/index.js generated vendored Normal file
View file

@ -0,0 +1,17 @@
/**
* @fileoverview Main package entrypoint.
* @author Nicholas C. Zakas
*/
"use strict";
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
configs: {
all: require("./configs/eslint-all"),
recommended: require("./configs/eslint-recommended")
}
};

View file

@ -0,0 +1,105 @@
# AccountsService-1.0
![version](https://img.shields.io/npm/v/@girs/accountsservice-1.0)
![downloads/week](https://img.shields.io/npm/dw/@girs/accountsservice-1.0)
GJS TypeScript type definitions for AccountsService-1.0, generated from library version 1.0.0 using [ts-for-gir](https://github.com/gjsify/ts-for-gir) v3.3.0.
Query and manipulate user account information
## Install
To use this type definitions, install them with NPM:
```bash
npm install @girs/accountsservice-1.0
```
## Usage
You can import this package into your project like this:
```ts
import AccountsService from '@girs/accountsservice-1.0';
```
Or if you prefer CommonJS, you can also use this:
```ts
const AccountsService = require('@girs/accountsservice-1.0');
```
### Ambient Modules
You can also use [ambient modules](https://github.com/gjsify/ts-for-gir/tree/main/packages/cli#ambient-modules) to import this module like you would do this in JavaScript.
For this you need to include `@girs/accountsservice-1.0` or `@girs/accountsservice-1.0/ambient` in your `tsconfig` or entry point Typescript file:
`index.ts`:
```ts
import '@girs/accountsservice-1.0'
```
`tsconfig.json`:
```json
{
"compilerOptions": {
...
},
"include": ["@girs/accountsservice-1.0"],
...
}
```
Now you can import the ambient module with TypeScript support:
```ts
import AccountsService from 'gi://AccountsService?version=1.0';
```
### Global import
You can also import the module with Typescript support using the global `imports.gi` object of GJS.
For this you need to include `@girs/accountsservice-1.0` or `@girs/accountsservice-1.0/import` in your `tsconfig` or entry point Typescript file:
`index.ts`:
```ts
import '@girs/accountsservice-1.0'
```
`tsconfig.json`:
```json
{
"compilerOptions": {
...
},
"include": ["@girs/accountsservice-1.0"],
...
}
```
Now you have also type support for this, too:
```ts
const AccountsService = imports.gi.AccountsService;
```
### ESM vs. CommonJS
GJS supports two different import syntaxes. The new modern ESM syntax and the old global imports syntax.
In TypeScript projects for GJS and GNOME Shell extensions, you have the flexibility to use `ESM` syntax and then decide the import syntax for your bundled file. If your bundler is configured to use `CommonJS`, it will convert to the GJS-specific global imports syntax, like `const moduleName = imports.gi[moduleName]`. This is different from the traditional `require` syntax seen in Node.js. The global imports syntax is chosen because it aligns with the CommonJS format supported by NPM, which is used for the generated type definitions and this package.
On the other hand, if you configure your bundler to use ESM, it will retain the ESM import syntax. It's crucial to ensure that your bundler is set up to correctly translate and bundle these imports into either CommonJS or ESM format, depending on your project's requirements.
This approach is particularly important due to the `@girs` types, which include both `*.cjs `files, using the GJS global imports syntax, and `*.js` files, which utilize the ESM syntax. By appropriately setting up your bundler, you can control which syntax—CommonJS or ESM—is used in your project. The choice of CommonJS in this context is also due to the similarity between the GJS-specific global imports and CommonJS syntax, allowing for easier management and bundling in these specific types of projects.
Since GNOME Shell 45, you should only use ESM, even for GNOME Shell extensions. Before that, extensions had to use the global import syntax, unlike normal GJS applications, where ESM has been available for some time.
### Bundle
Depending on your project configuration, it is recommended to use a bundler like [esbuild](https://esbuild.github.io/). You can find examples using different bundlers [here](https://github.com/gjsify/ts-for-gir/tree/main/examples).
## Other packages
All existing pre-generated packages can be found on [gjsify/types](https://github.com/gjsify/types).

View file

@ -0,0 +1,12 @@
declare module 'gi://AccountsService?version=1.0' {
import AccountsService10 from '@girs/accountsservice-1.0';
export default AccountsService10;
}
declare module 'gi://AccountsService' {
import AccountsService10 from '@girs/accountsservice-1.0';
export default AccountsService10;
}

View file

@ -0,0 +1,2 @@
export {}

View file

@ -0,0 +1,12 @@
import AccountsService10 from '@girs/accountsservice-1.0';
declare global {
export interface GjsGiImports {
AccountsService: typeof AccountsService10;
}
}
export default GjsGiImports;

View file

@ -0,0 +1,3 @@
const gi = globalThis.imports?.gi || {};
export default gi;

View file

@ -0,0 +1,11 @@
imports.gi.versions.AccountsService = '1.0'
const AccountsService = imports.gi.AccountsService;
module.exports = AccountsService;

View file

@ -0,0 +1,938 @@
/*
* Type Definitions for Gjs (https://gjs.guide/)
*
* These type definitions are automatically generated, do not edit them by hand.
* If you found a bug fix it in `ts-for-gir` or create a bug report on https://github.com/gjsify/ts-for-gir
*/
import './accountsservice-1.0-ambient.d.ts';
import './accountsservice-1.0-import.d.ts';
/**
* AccountsService-1.0
*/
import type Gio from '@girs/gio-2.0';
import type GObject from '@girs/gobject-2.0';
import type GLib from '@girs/glib-2.0';
/**
* Type of user account
*/
export enum UserAccountType {
/**
* Normal non-administrative user
*/
STANDARD,
/**
* Administrative user
*/
ADMINISTRATOR,
}
/**
* Various error codes returned by the accounts service.
*/
export enum UserManagerError {
/**
* Generic failure
*/
FAILED,
/**
* The user already exists
*/
USER_EXISTS,
/**
* The user does not exist
*/
USER_DOES_NOT_EXIST,
/**
* Permission denied
*/
PERMISSION_DENIED,
/**
* Operation not supported
*/
NOT_SUPPORTED,
}
/**
* Mode for setting the user's password.
*/
export enum UserPasswordMode {
/**
* Password set normally
*/
REGULAR,
/**
* Password will be chosen at next login
*/
SET_AT_LOGIN,
/**
* No password set
*/
NONE,
}
export function user_manager_error_quark(): GLib.Quark
export module User {
// Signal callback interfaces
/**
* Signal callback interface for `changed`
*/
export interface ChangedSignalCallback {
($obj: User): void
}
/**
* Signal callback interface for `sessions-changed`
*/
export interface SessionsChangedSignalCallback {
($obj: User): void
}
// Constructor properties interface
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
}
}
export interface User {
// Own properties of AccountsService-1.0.AccountsService.User
readonly accountType: number
readonly automaticLogin: boolean
readonly email: string | null
readonly homeDirectory: string | null
readonly iconFile: string | null
readonly isLoaded: boolean
/**
* The users locale, in the format
* `language[_territory][.codeset][`modifier]``, where `language` is an
* ISO 639 language code, `territory` is an ISO 3166 country code, and
* `codeset` is a character set or encoding identifier like `ISO-8859-1`
* or `UTF-8`; as specified by [`setlocale(3)`](man:setlocale(3)).
*
* The locale may be the empty string, which means the user is using the
* system default locale.
*
* The property may be %NULL if it wasnt possible to load it from the
* daemon.
*/
readonly language: string | null
readonly localAccount: boolean
readonly location: string | null
readonly locked: boolean
readonly loginFrequency: number
readonly loginHistory: GLib.Variant
readonly loginTime: number
readonly nonexistent: boolean
readonly passwordHint: string | null
readonly passwordMode: number
readonly realName: string | null
readonly shell: string | null
readonly systemAccount: boolean
readonly uid: number
readonly userName: string | null
readonly xSession: string | null
// Owm methods of AccountsService-1.0.AccountsService.User
/**
* Organize the user by login frequency and names.
* @param user2 a user
* @returns negative if @user1 is before @user2, zero if equal or positive if @user1 is after @user2
*/
collate(user2: User): number
/**
* Retrieves the account type of `user`.
* @returns a #ActUserAccountType
*/
get_account_type(): UserAccountType
/**
* Returns whether or not #ActUser is automatically logged in at boot time.
* @returns %TRUE or %FALSE
*/
get_automatic_login(): boolean
/**
* Retrieves the email address set by `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_email(): string
/**
* Retrieves the home directory for `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_home_dir(): string
/**
* Returns the path to the account icon belonging to `user`.
* @returns a path to an icon
*/
get_icon_file(): string
/**
* Returns the value of #ActUser:language.
* @returns the users language, or the empty string if they are using the system default language, or %NULL if there is no connection to the daemon
*/
get_language(): string | null
/**
* Returns the value of #ActUser:languages.
* @returns the users preferred languages, or the empty string if they are using the system default language, or %NULL if there is no connection to the daemon
*/
get_languages(): string[] | null
/**
* Retrieves the location set by `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_location(): string
/**
* Returns whether or not the #ActUser account is locked.
* @returns %TRUE or %FALSE
*/
get_locked(): boolean
/**
* Returns the number of times `user` has logged in.
* @returns the login frequency
*/
get_login_frequency(): number
/**
* Returns the login history for `user`.
* @returns a pointer to GVariant of type "a(xxa{sv})" which must not be modified or freed, or %NULL.
*/
get_login_history(): GLib.Variant
/**
* Returns the last login time for `user`.
* @returns the login time
*/
get_login_time(): number
/**
* Get the number of sessions for a user that are graphical and on the
* same seat as the session of the calling process.
* @returns the number of sessions
*/
get_num_sessions(): number
/**
* Get the number of sessions for a user on any seat of any type.
* See also act_user_get_num_sessions().
*
* (Currently, this function is only implemented for systemd-logind.
* For ConsoleKit, it is equivalent to act_user_get_num_sessions.)
* @returns the number of sessions
*/
get_num_sessions_anywhere(): number
/**
* Returns the user accounts service object path of `user,`
* or %NULL if `user` doesn't have an object path associated
* with it.
* @returns the object path of the user
*/
get_object_path(): string
/**
* Get the password expiration policy for a user.
*
* Note this function is synchronous and ignores errors.
*/
get_password_expiration_policy(): [ /* expiration_time */ number, /* last_change_time */ number, /* min_days_between_changes */ number, /* max_days_between_changes */ number, /* days_to_warn */ number, /* days_after_expiration_until_lock */ number ]
/**
* Retrieves the password hint set by `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_password_hint(): string
/**
* Retrieves the password mode of `user`.
* @returns a #ActUserPasswordMode
*/
get_password_mode(): UserPasswordMode
/**
* Returns the id of the primary session of `user,` or %NULL if `user`
* has no primary session. The primary session will always be
* graphical and will be chosen from the sessions on the same seat as
* the seat of the session of the calling process.
* @returns the id of the primary session of the user
*/
get_primary_session_id(): string
/**
* Retrieves the display name of `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_real_name(): string
/**
* Returns whether or not the #ActUser account has retained state in accountsservice.
* @returns %TRUE or %FALSE
*/
get_saved(): boolean
/**
* Returns the path to the configured session for `user`.
* @returns a path to an icon
*/
get_session(): string
/**
* Returns the type of the configured session for `user`.
* @returns a path to an icon
*/
get_session_type(): string
/**
* Retrieves the shell assigned to `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_shell(): string
/**
* Retrieves the ID of `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_uid(): number
/**
* Retrieves the login name of `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_user_name(): string
/**
* Returns the path to the configured X session for `user`.
* @returns a path to an icon
*/
get_x_session(): string
/**
* Determines whether or not the user object is loaded and ready to read from.
* #ActUserManager:is-loaded property must be %TRUE before calling
* act_user_manager_list_users()
* @returns %TRUE or %FALSE
*/
is_loaded(): boolean
/**
* Retrieves whether the user is a local account or not.
* @returns %TRUE if the user is local
*/
is_local_account(): boolean
/**
* Returns whether or not #ActUser is currently graphically logged in
* on the same seat as the seat of the session of the calling process.
* @returns %TRUE or %FALSE
*/
is_logged_in(): boolean
/**
* Returns whether or not #ActUser is currently logged in in any way
* whatsoever. See also act_user_is_logged_in().
*
* (Currently, this function is only implemented for systemd-logind.
* For ConsoleKit, it is equivalent to act_user_is_logged_in.)
* @returns %TRUE or %FALSE
*/
is_logged_in_anywhere(): boolean
/**
* Retrieves whether the user is nonexistent or not.
* @returns %TRUE if the user is nonexistent
*/
is_nonexistent(): boolean
/**
* Returns whether or not #ActUser represents a 'system account' like
* 'root' or 'nobody'.
* @returns %TRUE or %FALSE
*/
is_system_account(): boolean
/**
* Changes the account type of `user`.
*
* Note this function is synchronous and ignores errors.
* @param account_type a #ActUserAccountType
*/
set_account_type(account_type: UserAccountType): void
/**
* If enabled is set to %TRUE then this user will automatically be logged in
* at boot up time. Only one user can be configured to auto login at any given
* time, so subsequent calls to act_user_set_automatic_login() override previous
* calls.
*
* Note this function is synchronous and ignores errors.
* @param enabled whether or not to autologin for user.
*/
set_automatic_login(enabled: boolean): void
/**
* Assigns a new email to `user`.
*
* Note this function is synchronous and ignores errors.
* @param email an email address
*/
set_email(email: string): void
/**
* Assigns a new icon for `user`.
*
* Note this function is synchronous and ignores errors.
* @param icon_file path to an icon
*/
set_icon_file(icon_file: string): void
/**
* Assigns a new locale for `user,` setting #ActUser:language.
*
* Note this function is synchronous and ignores errors.
* @param language a locale (for example, `en_US.utf8`), or the empty string to use the system default locale
*/
set_language(language: string): void
/**
* Assigns preferred languages for `user,` setting #ActUser:languages, and
* overriding #ActUser:language with the first item in the list if there is one.
*
* Note this function is synchronous and ignores errors.
* @param languages an array of locale (for example, `en_US.utf8`), or the empty string to use the system default locale
*/
set_languages(languages: string[]): void
/**
* Assigns a new location for `user`.
*
* Note this function is synchronous and ignores errors.
* @param location a location
*/
set_location(location: string): void
/**
* Note this function is synchronous and ignores errors.
* @param locked whether or not the account is locked
*/
set_locked(locked: boolean): void
/**
* Changes the password of `user` to `password`.
* `hint` is displayed to the user if they forget the password.
*
* Note this function is synchronous and ignores errors.
* @param password a password
* @param hint a hint to help user recall password
*/
set_password(password: string, hint: string): void
/**
* Set the password expiration policy for a user.
*
* Note this function is synchronous and ignores errors.
* @param min_days_between_changes location to write minimum number of days needed between password changes.
* @param max_days_between_changes location to write maximum number of days password can stay unchanged.
* @param days_to_warn location to write number of days to warn user password is about to expire.
* @param days_after_expiration_until_lock location to write number of days account will be locked after password expires.
*/
set_password_expiration_policy(min_days_between_changes: number, max_days_between_changes: number, days_to_warn: number, days_after_expiration_until_lock: number): void
set_password_hint(hint: string): void
/**
* Changes the password of `user`. If `password_mode` is
* ACT_USER_PASSWORD_MODE_SET_AT_LOGIN then the user will
* be asked for a new password at the next login. If `password_mode`
* is ACT_USER_PASSWORD_MODE_NONE then the user will not require
* a password to log in.
*
* Note this function is synchronous and ignores errors.
* @param password_mode a #ActUserPasswordMode
*/
set_password_mode(password_mode: UserPasswordMode): void
/**
* Assigns a new name for `user`.
*
* Note this function is synchronous and ignores errors.
* @param real_name a new name
*/
set_real_name(real_name: string): void
/**
* Assigns a new session for `user`.
*
* Note this function is synchronous and ignores errors.
* @param session a session (e.g. gnome)
*/
set_session(session: string): void
/**
* Assigns a type to the session for `user`.
*
* Note this function is synchronous and ignores errors.
* @param session_type a type of session (e.g. "wayland" or "x11")
*/
set_session_type(session_type: string): void
/**
* Set the user expiration policy for a user.
*
* Note this function is synchronous and ignores errors.
* @param expiration_time location to write users expires timestamp
*/
set_user_expiration_policy(expiration_time: number): void
/**
* Assigns a new username for `user`.
*
* Note this function is synchronous and ignores errors.
* @param user_name a new user name
*/
set_user_name(user_name: string): void
/**
* Assigns a new x session for `user`.
*
* Note this function is synchronous and ignores errors.
* @param x_session an x session (e.g. gnome)
*/
set_x_session(x_session: string): void
// Own signals of AccountsService-1.0.AccountsService.User
connect(sigName: "changed", callback: User.ChangedSignalCallback): number
connect_after(sigName: "changed", callback: User.ChangedSignalCallback): number
emit(sigName: "changed", ...args: any[]): void
connect(sigName: "sessions-changed", callback: User.SessionsChangedSignalCallback): number
connect_after(sigName: "sessions-changed", callback: User.SessionsChangedSignalCallback): number
emit(sigName: "sessions-changed", ...args: any[]): void
// Class property signals of AccountsService-1.0.AccountsService.User
connect(sigName: "notify::account-type", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::account-type", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::account-type", ...args: any[]): void
connect(sigName: "notify::automatic-login", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::automatic-login", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::automatic-login", ...args: any[]): void
connect(sigName: "notify::email", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::email", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::email", ...args: any[]): void
connect(sigName: "notify::home-directory", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::home-directory", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::home-directory", ...args: any[]): void
connect(sigName: "notify::icon-file", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::icon-file", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::icon-file", ...args: any[]): void
connect(sigName: "notify::is-loaded", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::is-loaded", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::is-loaded", ...args: any[]): void
connect(sigName: "notify::language", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::language", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::language", ...args: any[]): void
connect(sigName: "notify::local-account", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::local-account", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::local-account", ...args: any[]): void
connect(sigName: "notify::location", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::location", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::location", ...args: any[]): void
connect(sigName: "notify::locked", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::locked", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::locked", ...args: any[]): void
connect(sigName: "notify::login-frequency", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::login-frequency", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::login-frequency", ...args: any[]): void
connect(sigName: "notify::login-history", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::login-history", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::login-history", ...args: any[]): void
connect(sigName: "notify::login-time", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::login-time", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::login-time", ...args: any[]): void
connect(sigName: "notify::nonexistent", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::nonexistent", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::nonexistent", ...args: any[]): void
connect(sigName: "notify::password-hint", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::password-hint", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::password-hint", ...args: any[]): void
connect(sigName: "notify::password-mode", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::password-mode", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::password-mode", ...args: any[]): void
connect(sigName: "notify::real-name", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::real-name", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::real-name", ...args: any[]): void
connect(sigName: "notify::shell", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::shell", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::shell", ...args: any[]): void
connect(sigName: "notify::system-account", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::system-account", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::system-account", ...args: any[]): void
connect(sigName: "notify::uid", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::uid", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::uid", ...args: any[]): void
connect(sigName: "notify::user-name", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::user-name", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::user-name", ...args: any[]): void
connect(sigName: "notify::x-session", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::x-session", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::x-session", ...args: any[]): void
connect(sigName: string, callback: (...args: any[]) => void): number
connect_after(sigName: string, callback: (...args: any[]) => void): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
}
/**
* Represents a user account on the system.
* @class
*/
export class User extends GObject.Object {
// Own properties of AccountsService-1.0.AccountsService.User
static name: string
static $gtype: GObject.GType<User>
// Constructors of AccountsService-1.0.AccountsService.User
constructor(config?: User.ConstructorProperties)
_init(config?: User.ConstructorProperties): void
}
export module UserManager {
// Signal callback interfaces
/**
* Signal callback interface for `user-added`
*/
export interface UserAddedSignalCallback {
($obj: UserManager, user: User): void
}
/**
* Signal callback interface for `user-changed`
*/
export interface UserChangedSignalCallback {
($obj: UserManager, user: User): void
}
/**
* Signal callback interface for `user-is-logged-in-changed`
*/
export interface UserIsLoggedInChangedSignalCallback {
($obj: UserManager, user: User): void
}
/**
* Signal callback interface for `user-removed`
*/
export interface UserRemovedSignalCallback {
($obj: UserManager, user: User): void
}
// Constructor properties interface
export interface ConstructorProperties extends GObject.Object.ConstructorProperties {
// Own constructor properties of AccountsService-1.0.AccountsService.UserManager
excludeUsernamesList?: any | null
hasMultipleUsers?: boolean | null
includeUsernamesList?: any | null
}
}
export interface UserManager {
// Own properties of AccountsService-1.0.AccountsService.UserManager
excludeUsernamesList: any
hasMultipleUsers: boolean
includeUsernamesList: any
readonly isLoaded: boolean
// Own fields of AccountsService-1.0.AccountsService.UserManager
parent: GObject.Object
// Owm methods of AccountsService-1.0.AccountsService.UserManager
/**
* Activate the session for a given user.
* @param user the user to activate
* @returns whether successfully activated
*/
activate_user_session(user: User): boolean
/**
* Caches a user account so it shows up via act_user_manager_list_users().
* @param username a user name
* @returns user object
*/
cache_user(username: string): User
/**
* Asynchronously caches a user account so it shows up via
* act_user_manager_list_users().
*
* For more details, see act_user_manager_cache_user(), which
* is the synchronous version of this call.
* @param username a unix user name
* @param cancellable optional #GCancellable object, %NULL to ignore
* @param callback a #GAsyncReadyCallback to call when the request is satisfied
*/
cache_user_async(username: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void
// Overloads of cache_user_async
/**
* Promisified version of {@link cache_user_async}
*
* Asynchronously caches a user account so it shows up via
* act_user_manager_list_users().
*
* For more details, see act_user_manager_cache_user(), which
* is the synchronous version of this call.
* @param username a unix user name
* @param cancellable optional #GCancellable object, %NULL to ignore
* @returns A Promise of: user object
*/
cache_user_async(username: string, cancellable: Gio.Cancellable | null): globalThis.Promise<User>
/**
* Finishes an asynchronous user caching.
*
* See act_user_manager_cache_user_async().
* @param result a #GAsyncResult
* @returns user object
*/
cache_user_finish(result: Gio.AsyncResult): User
/**
* Check whether the user can switch to another session.
* @returns whether we can switch to another session
*/
can_switch(): boolean
/**
* Creates a user account on the system.
* @param username a unix user name
* @param fullname a unix GECOS value
* @param accounttype a #ActUserAccountType
* @returns user object
*/
create_user(username: string, fullname: string, accounttype: UserAccountType): User
/**
* Asynchronously creates a user account on the system.
*
* For more details, see act_user_manager_create_user(), which
* is the synchronous version of this call.
* @param username a unix user name
* @param fullname a unix GECOS value
* @param accounttype a #ActUserAccountType
* @param cancellable optional #GCancellable object, %NULL to ignore
* @param callback a #GAsyncReadyCallback to call when the request is satisfied
*/
create_user_async(username: string, fullname: string, accounttype: UserAccountType, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void
// Overloads of create_user_async
/**
* Promisified version of {@link create_user_async}
*
* Asynchronously creates a user account on the system.
*
* For more details, see act_user_manager_create_user(), which
* is the synchronous version of this call.
* @param username a unix user name
* @param fullname a unix GECOS value
* @param accounttype a #ActUserAccountType
* @param cancellable optional #GCancellable object, %NULL to ignore
* @returns A Promise of: user object
*/
create_user_async(username: string, fullname: string, accounttype: UserAccountType, cancellable: Gio.Cancellable | null): globalThis.Promise<User>
/**
* Finishes an asynchronous user creation.
*
* See act_user_manager_create_user_async().
* @param result a #GAsyncResult
* @returns user object
*/
create_user_finish(result: Gio.AsyncResult): User
/**
* Deletes a user account on the system.
* @param user an #ActUser object
* @param remove_files %TRUE to delete the users home directory
* @returns %TRUE if the user account was successfully deleted
*/
delete_user(user: User, remove_files: boolean): boolean
/**
* Asynchronously deletes a user account from the system.
*
* For more details, see act_user_manager_delete_user(), which
* is the synchronous version of this call.
* @param user a #ActUser object
* @param remove_files %TRUE to delete the users home directory
* @param cancellable optional #GCancellable object, %NULL to ignore
* @param callback a #GAsyncReadyCallback to call when the request is satisfied
*/
delete_user_async(user: User, remove_files: boolean, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void
// Overloads of delete_user_async
/**
* Promisified version of {@link delete_user_async}
*
* Asynchronously deletes a user account from the system.
*
* For more details, see act_user_manager_delete_user(), which
* is the synchronous version of this call.
* @param user a #ActUser object
* @param remove_files %TRUE to delete the users home directory
* @param cancellable optional #GCancellable object, %NULL to ignore
* @returns A Promise of: %TRUE if the user account was successfully deleted
*/
delete_user_async(user: User, remove_files: boolean, cancellable: Gio.Cancellable | null): globalThis.Promise<boolean>
/**
* Finishes an asynchronous user account deletion.
*
* See act_user_manager_delete_user_async().
* @param result a #GAsyncResult
* @returns %TRUE if the user account was successfully deleted
*/
delete_user_finish(result: Gio.AsyncResult): boolean
/**
* Retrieves a pointer to the #ActUser object for the login `username`
* from `manager`. Trying to use this object before its
* #ActUser:is-loaded property is %TRUE will result in undefined
* behavior.
* @param username the login name of the user to get.
* @returns #ActUser object
*/
get_user(username: string): User
/**
* Retrieves a pointer to the #ActUser object for the user with the
* given uid from `manager`. Trying to use this object before its
* #ActUser:is-loaded property is %TRUE will result in undefined
* behavior.
* @param id the uid of the user to get.
* @returns #ActUser object
*/
get_user_by_id(id: number): User
/**
* Switch the display to the login manager.
* @returns whether successful or not
*/
goto_login_session(): boolean
/**
* Get a list of system user accounts
* @returns List of #ActUser objects
*/
list_users(): User[]
/**
* Check whether or not the accounts service is running.
* @returns whether or not accounts service is running
*/
no_service(): boolean
/**
* Releases all metadata about a user account, including icon,
* language and session. If the user account is from a remote
* server and the user has never logged in before, then that
* account will no longer show up in ListCachedUsers() output.
* @param username a user name
* @returns %TRUE if successful, otherwise %FALSE
*/
uncache_user(username: string): boolean
uncache_user_async(username: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void
// Overloads of uncache_user_async
/**
* Promisified version of {@link uncache_user_async}
*
*
* @param username
* @param cancellable
* @returns A Promise of: %TRUE if the user account was successfully uncached
*/
uncache_user_async(username: string, cancellable: Gio.Cancellable | null): globalThis.Promise<boolean>
/**
* Finishes an asynchronous user uncaching.
*
* See act_user_manager_uncache_user_async().
* @param result a #GAsyncResult
* @returns %TRUE if the user account was successfully uncached
*/
uncache_user_finish(result: Gio.AsyncResult): boolean
// Own virtual methods of AccountsService-1.0.AccountsService.UserManager
vfunc_user_added(user: User): void
vfunc_user_changed(user: User): void
vfunc_user_is_logged_in_changed(user: User): void
vfunc_user_removed(user: User): void
// Own signals of AccountsService-1.0.AccountsService.UserManager
connect(sigName: "user-added", callback: UserManager.UserAddedSignalCallback): number
connect_after(sigName: "user-added", callback: UserManager.UserAddedSignalCallback): number
emit(sigName: "user-added", user: User, ...args: any[]): void
connect(sigName: "user-changed", callback: UserManager.UserChangedSignalCallback): number
connect_after(sigName: "user-changed", callback: UserManager.UserChangedSignalCallback): number
emit(sigName: "user-changed", user: User, ...args: any[]): void
connect(sigName: "user-is-logged-in-changed", callback: UserManager.UserIsLoggedInChangedSignalCallback): number
connect_after(sigName: "user-is-logged-in-changed", callback: UserManager.UserIsLoggedInChangedSignalCallback): number
emit(sigName: "user-is-logged-in-changed", user: User, ...args: any[]): void
connect(sigName: "user-removed", callback: UserManager.UserRemovedSignalCallback): number
connect_after(sigName: "user-removed", callback: UserManager.UserRemovedSignalCallback): number
emit(sigName: "user-removed", user: User, ...args: any[]): void
// Class property signals of AccountsService-1.0.AccountsService.UserManager
connect(sigName: "notify::exclude-usernames-list", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::exclude-usernames-list", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::exclude-usernames-list", ...args: any[]): void
connect(sigName: "notify::has-multiple-users", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::has-multiple-users", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::has-multiple-users", ...args: any[]): void
connect(sigName: "notify::include-usernames-list", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::include-usernames-list", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::include-usernames-list", ...args: any[]): void
connect(sigName: "notify::is-loaded", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::is-loaded", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::is-loaded", ...args: any[]): void
connect(sigName: string, callback: (...args: any[]) => void): number
connect_after(sigName: string, callback: (...args: any[]) => void): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
}
/**
* A user manager object.
* @class
*/
export class UserManager extends GObject.Object {
// Own properties of AccountsService-1.0.AccountsService.UserManager
static name: string
static $gtype: GObject.GType<UserManager>
// Constructors of AccountsService-1.0.AccountsService.UserManager
constructor(config?: UserManager.ConstructorProperties)
_init(config?: UserManager.ConstructorProperties): void
/**
* Returns the user manager singleton instance. Calling this function will
* automatically being loading the user list if it isn't loaded already.
* The #ActUserManager:is-loaded property will be set to %TRUE when the users
* are finished loading and then act_user_manager_list_users() can be called.
* @returns user manager object
*/
static get_default(): UserManager
}
export interface UserClass {
// Own fields of AccountsService-1.0.AccountsService.UserClass
parent_class: GObject.ObjectClass
}
export abstract class UserClass {
// Own properties of AccountsService-1.0.AccountsService.UserClass
static name: string
}
export interface UserManagerClass {
// Own fields of AccountsService-1.0.AccountsService.UserManagerClass
parent_class: GObject.ObjectClass
user_added: (user_manager: UserManager, user: User) => void
user_removed: (user_manager: UserManager, user: User) => void
user_is_logged_in_changed: (user_manager: UserManager, user: User) => void
user_changed: (user_manager: UserManager, user: User) => void
}
export abstract class UserManagerClass {
// Own properties of AccountsService-1.0.AccountsService.UserManagerClass
static name: string
}
/**
* Name of the imported GIR library
* @see https://gitlab.gnome.org/GNOME/gjs/-/blob/master/gi/ns.cpp#L188
*/
export const __name__: string
/**
* Version of the imported GIR library
* @see https://gitlab.gnome.org/GNOME/gjs/-/blob/master/gi/ns.cpp#L189
*/
export const __version__: string
// END

View file

@ -0,0 +1,943 @@
/*
* Type Definitions for Gjs (https://gjs.guide/)
*
* These type definitions are automatically generated, do not edit them by hand.
* If you found a bug fix it in `ts-for-gir` or create a bug report on https://github.com/gjsify/ts-for-gir
*/
import './accountsservice-1.0-ambient.d.ts';
import './accountsservice-1.0-import.d.ts';
/**
* AccountsService-1.0
*/
import type Gio from '@girs/gio-2.0';
import type GObject from '@girs/gobject-2.0';
import type GLib from '@girs/glib-2.0';
export namespace AccountsService {
/**
* Type of user account
*/
enum UserAccountType {
/**
* Normal non-administrative user
*/
STANDARD,
/**
* Administrative user
*/
ADMINISTRATOR,
}
/**
* Various error codes returned by the accounts service.
*/
enum UserManagerError {
/**
* Generic failure
*/
FAILED,
/**
* The user already exists
*/
USER_EXISTS,
/**
* The user does not exist
*/
USER_DOES_NOT_EXIST,
/**
* Permission denied
*/
PERMISSION_DENIED,
/**
* Operation not supported
*/
NOT_SUPPORTED,
}
/**
* Mode for setting the user's password.
*/
enum UserPasswordMode {
/**
* Password set normally
*/
REGULAR,
/**
* Password will be chosen at next login
*/
SET_AT_LOGIN,
/**
* No password set
*/
NONE,
}
function user_manager_error_quark(): GLib.Quark
module User {
// Signal callback interfaces
/**
* Signal callback interface for `changed`
*/
interface ChangedSignalCallback {
($obj: User): void
}
/**
* Signal callback interface for `sessions-changed`
*/
interface SessionsChangedSignalCallback {
($obj: User): void
}
// Constructor properties interface
interface ConstructorProperties extends GObject.Object.ConstructorProperties {
}
}
interface User {
// Own properties of AccountsService-1.0.AccountsService.User
readonly accountType: number
readonly automaticLogin: boolean
readonly email: string | null
readonly homeDirectory: string | null
readonly iconFile: string | null
readonly isLoaded: boolean
/**
* The users locale, in the format
* `language[_territory][.codeset][`modifier]``, where `language` is an
* ISO 639 language code, `territory` is an ISO 3166 country code, and
* `codeset` is a character set or encoding identifier like `ISO-8859-1`
* or `UTF-8`; as specified by [`setlocale(3)`](man:setlocale(3)).
*
* The locale may be the empty string, which means the user is using the
* system default locale.
*
* The property may be %NULL if it wasnt possible to load it from the
* daemon.
*/
readonly language: string | null
readonly localAccount: boolean
readonly location: string | null
readonly locked: boolean
readonly loginFrequency: number
readonly loginHistory: GLib.Variant
readonly loginTime: number
readonly nonexistent: boolean
readonly passwordHint: string | null
readonly passwordMode: number
readonly realName: string | null
readonly shell: string | null
readonly systemAccount: boolean
readonly uid: number
readonly userName: string | null
readonly xSession: string | null
// Owm methods of AccountsService-1.0.AccountsService.User
/**
* Organize the user by login frequency and names.
* @param user2 a user
* @returns negative if @user1 is before @user2, zero if equal or positive if @user1 is after @user2
*/
collate(user2: User): number
/**
* Retrieves the account type of `user`.
* @returns a #ActUserAccountType
*/
get_account_type(): UserAccountType
/**
* Returns whether or not #ActUser is automatically logged in at boot time.
* @returns %TRUE or %FALSE
*/
get_automatic_login(): boolean
/**
* Retrieves the email address set by `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_email(): string
/**
* Retrieves the home directory for `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_home_dir(): string
/**
* Returns the path to the account icon belonging to `user`.
* @returns a path to an icon
*/
get_icon_file(): string
/**
* Returns the value of #ActUser:language.
* @returns the users language, or the empty string if they are using the system default language, or %NULL if there is no connection to the daemon
*/
get_language(): string | null
/**
* Returns the value of #ActUser:languages.
* @returns the users preferred languages, or the empty string if they are using the system default language, or %NULL if there is no connection to the daemon
*/
get_languages(): string[] | null
/**
* Retrieves the location set by `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_location(): string
/**
* Returns whether or not the #ActUser account is locked.
* @returns %TRUE or %FALSE
*/
get_locked(): boolean
/**
* Returns the number of times `user` has logged in.
* @returns the login frequency
*/
get_login_frequency(): number
/**
* Returns the login history for `user`.
* @returns a pointer to GVariant of type "a(xxa{sv})" which must not be modified or freed, or %NULL.
*/
get_login_history(): GLib.Variant
/**
* Returns the last login time for `user`.
* @returns the login time
*/
get_login_time(): number
/**
* Get the number of sessions for a user that are graphical and on the
* same seat as the session of the calling process.
* @returns the number of sessions
*/
get_num_sessions(): number
/**
* Get the number of sessions for a user on any seat of any type.
* See also act_user_get_num_sessions().
*
* (Currently, this function is only implemented for systemd-logind.
* For ConsoleKit, it is equivalent to act_user_get_num_sessions.)
* @returns the number of sessions
*/
get_num_sessions_anywhere(): number
/**
* Returns the user accounts service object path of `user,`
* or %NULL if `user` doesn't have an object path associated
* with it.
* @returns the object path of the user
*/
get_object_path(): string
/**
* Get the password expiration policy for a user.
*
* Note this function is synchronous and ignores errors.
*/
get_password_expiration_policy(): [ /* expiration_time */ number, /* last_change_time */ number, /* min_days_between_changes */ number, /* max_days_between_changes */ number, /* days_to_warn */ number, /* days_after_expiration_until_lock */ number ]
/**
* Retrieves the password hint set by `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_password_hint(): string
/**
* Retrieves the password mode of `user`.
* @returns a #ActUserPasswordMode
*/
get_password_mode(): UserPasswordMode
/**
* Returns the id of the primary session of `user,` or %NULL if `user`
* has no primary session. The primary session will always be
* graphical and will be chosen from the sessions on the same seat as
* the seat of the session of the calling process.
* @returns the id of the primary session of the user
*/
get_primary_session_id(): string
/**
* Retrieves the display name of `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_real_name(): string
/**
* Returns whether or not the #ActUser account has retained state in accountsservice.
* @returns %TRUE or %FALSE
*/
get_saved(): boolean
/**
* Returns the path to the configured session for `user`.
* @returns a path to an icon
*/
get_session(): string
/**
* Returns the type of the configured session for `user`.
* @returns a path to an icon
*/
get_session_type(): string
/**
* Retrieves the shell assigned to `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_shell(): string
/**
* Retrieves the ID of `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_uid(): number
/**
* Retrieves the login name of `user`.
* @returns a pointer to an array of characters which must not be modified or freed, or %NULL.
*/
get_user_name(): string
/**
* Returns the path to the configured X session for `user`.
* @returns a path to an icon
*/
get_x_session(): string
/**
* Determines whether or not the user object is loaded and ready to read from.
* #ActUserManager:is-loaded property must be %TRUE before calling
* act_user_manager_list_users()
* @returns %TRUE or %FALSE
*/
is_loaded(): boolean
/**
* Retrieves whether the user is a local account or not.
* @returns %TRUE if the user is local
*/
is_local_account(): boolean
/**
* Returns whether or not #ActUser is currently graphically logged in
* on the same seat as the seat of the session of the calling process.
* @returns %TRUE or %FALSE
*/
is_logged_in(): boolean
/**
* Returns whether or not #ActUser is currently logged in in any way
* whatsoever. See also act_user_is_logged_in().
*
* (Currently, this function is only implemented for systemd-logind.
* For ConsoleKit, it is equivalent to act_user_is_logged_in.)
* @returns %TRUE or %FALSE
*/
is_logged_in_anywhere(): boolean
/**
* Retrieves whether the user is nonexistent or not.
* @returns %TRUE if the user is nonexistent
*/
is_nonexistent(): boolean
/**
* Returns whether or not #ActUser represents a 'system account' like
* 'root' or 'nobody'.
* @returns %TRUE or %FALSE
*/
is_system_account(): boolean
/**
* Changes the account type of `user`.
*
* Note this function is synchronous and ignores errors.
* @param account_type a #ActUserAccountType
*/
set_account_type(account_type: UserAccountType): void
/**
* If enabled is set to %TRUE then this user will automatically be logged in
* at boot up time. Only one user can be configured to auto login at any given
* time, so subsequent calls to act_user_set_automatic_login() override previous
* calls.
*
* Note this function is synchronous and ignores errors.
* @param enabled whether or not to autologin for user.
*/
set_automatic_login(enabled: boolean): void
/**
* Assigns a new email to `user`.
*
* Note this function is synchronous and ignores errors.
* @param email an email address
*/
set_email(email: string): void
/**
* Assigns a new icon for `user`.
*
* Note this function is synchronous and ignores errors.
* @param icon_file path to an icon
*/
set_icon_file(icon_file: string): void
/**
* Assigns a new locale for `user,` setting #ActUser:language.
*
* Note this function is synchronous and ignores errors.
* @param language a locale (for example, `en_US.utf8`), or the empty string to use the system default locale
*/
set_language(language: string): void
/**
* Assigns preferred languages for `user,` setting #ActUser:languages, and
* overriding #ActUser:language with the first item in the list if there is one.
*
* Note this function is synchronous and ignores errors.
* @param languages an array of locale (for example, `en_US.utf8`), or the empty string to use the system default locale
*/
set_languages(languages: string[]): void
/**
* Assigns a new location for `user`.
*
* Note this function is synchronous and ignores errors.
* @param location a location
*/
set_location(location: string): void
/**
* Note this function is synchronous and ignores errors.
* @param locked whether or not the account is locked
*/
set_locked(locked: boolean): void
/**
* Changes the password of `user` to `password`.
* `hint` is displayed to the user if they forget the password.
*
* Note this function is synchronous and ignores errors.
* @param password a password
* @param hint a hint to help user recall password
*/
set_password(password: string, hint: string): void
/**
* Set the password expiration policy for a user.
*
* Note this function is synchronous and ignores errors.
* @param min_days_between_changes location to write minimum number of days needed between password changes.
* @param max_days_between_changes location to write maximum number of days password can stay unchanged.
* @param days_to_warn location to write number of days to warn user password is about to expire.
* @param days_after_expiration_until_lock location to write number of days account will be locked after password expires.
*/
set_password_expiration_policy(min_days_between_changes: number, max_days_between_changes: number, days_to_warn: number, days_after_expiration_until_lock: number): void
set_password_hint(hint: string): void
/**
* Changes the password of `user`. If `password_mode` is
* ACT_USER_PASSWORD_MODE_SET_AT_LOGIN then the user will
* be asked for a new password at the next login. If `password_mode`
* is ACT_USER_PASSWORD_MODE_NONE then the user will not require
* a password to log in.
*
* Note this function is synchronous and ignores errors.
* @param password_mode a #ActUserPasswordMode
*/
set_password_mode(password_mode: UserPasswordMode): void
/**
* Assigns a new name for `user`.
*
* Note this function is synchronous and ignores errors.
* @param real_name a new name
*/
set_real_name(real_name: string): void
/**
* Assigns a new session for `user`.
*
* Note this function is synchronous and ignores errors.
* @param session a session (e.g. gnome)
*/
set_session(session: string): void
/**
* Assigns a type to the session for `user`.
*
* Note this function is synchronous and ignores errors.
* @param session_type a type of session (e.g. "wayland" or "x11")
*/
set_session_type(session_type: string): void
/**
* Set the user expiration policy for a user.
*
* Note this function is synchronous and ignores errors.
* @param expiration_time location to write users expires timestamp
*/
set_user_expiration_policy(expiration_time: number): void
/**
* Assigns a new username for `user`.
*
* Note this function is synchronous and ignores errors.
* @param user_name a new user name
*/
set_user_name(user_name: string): void
/**
* Assigns a new x session for `user`.
*
* Note this function is synchronous and ignores errors.
* @param x_session an x session (e.g. gnome)
*/
set_x_session(x_session: string): void
// Own signals of AccountsService-1.0.AccountsService.User
connect(sigName: "changed", callback: User.ChangedSignalCallback): number
connect_after(sigName: "changed", callback: User.ChangedSignalCallback): number
emit(sigName: "changed", ...args: any[]): void
connect(sigName: "sessions-changed", callback: User.SessionsChangedSignalCallback): number
connect_after(sigName: "sessions-changed", callback: User.SessionsChangedSignalCallback): number
emit(sigName: "sessions-changed", ...args: any[]): void
// Class property signals of AccountsService-1.0.AccountsService.User
connect(sigName: "notify::account-type", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::account-type", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::account-type", ...args: any[]): void
connect(sigName: "notify::automatic-login", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::automatic-login", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::automatic-login", ...args: any[]): void
connect(sigName: "notify::email", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::email", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::email", ...args: any[]): void
connect(sigName: "notify::home-directory", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::home-directory", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::home-directory", ...args: any[]): void
connect(sigName: "notify::icon-file", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::icon-file", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::icon-file", ...args: any[]): void
connect(sigName: "notify::is-loaded", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::is-loaded", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::is-loaded", ...args: any[]): void
connect(sigName: "notify::language", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::language", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::language", ...args: any[]): void
connect(sigName: "notify::local-account", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::local-account", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::local-account", ...args: any[]): void
connect(sigName: "notify::location", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::location", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::location", ...args: any[]): void
connect(sigName: "notify::locked", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::locked", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::locked", ...args: any[]): void
connect(sigName: "notify::login-frequency", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::login-frequency", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::login-frequency", ...args: any[]): void
connect(sigName: "notify::login-history", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::login-history", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::login-history", ...args: any[]): void
connect(sigName: "notify::login-time", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::login-time", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::login-time", ...args: any[]): void
connect(sigName: "notify::nonexistent", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::nonexistent", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::nonexistent", ...args: any[]): void
connect(sigName: "notify::password-hint", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::password-hint", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::password-hint", ...args: any[]): void
connect(sigName: "notify::password-mode", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::password-mode", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::password-mode", ...args: any[]): void
connect(sigName: "notify::real-name", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::real-name", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::real-name", ...args: any[]): void
connect(sigName: "notify::shell", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::shell", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::shell", ...args: any[]): void
connect(sigName: "notify::system-account", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::system-account", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::system-account", ...args: any[]): void
connect(sigName: "notify::uid", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::uid", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::uid", ...args: any[]): void
connect(sigName: "notify::user-name", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::user-name", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::user-name", ...args: any[]): void
connect(sigName: "notify::x-session", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::x-session", callback: (($obj: User, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::x-session", ...args: any[]): void
connect(sigName: string, callback: (...args: any[]) => void): number
connect_after(sigName: string, callback: (...args: any[]) => void): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
}
/**
* Represents a user account on the system.
* @class
*/
class User extends GObject.Object {
// Own properties of AccountsService-1.0.AccountsService.User
static name: string
static $gtype: GObject.GType<User>
// Constructors of AccountsService-1.0.AccountsService.User
constructor(config?: User.ConstructorProperties)
_init(config?: User.ConstructorProperties): void
}
module UserManager {
// Signal callback interfaces
/**
* Signal callback interface for `user-added`
*/
interface UserAddedSignalCallback {
($obj: UserManager, user: User): void
}
/**
* Signal callback interface for `user-changed`
*/
interface UserChangedSignalCallback {
($obj: UserManager, user: User): void
}
/**
* Signal callback interface for `user-is-logged-in-changed`
*/
interface UserIsLoggedInChangedSignalCallback {
($obj: UserManager, user: User): void
}
/**
* Signal callback interface for `user-removed`
*/
interface UserRemovedSignalCallback {
($obj: UserManager, user: User): void
}
// Constructor properties interface
interface ConstructorProperties extends GObject.Object.ConstructorProperties {
// Own constructor properties of AccountsService-1.0.AccountsService.UserManager
excludeUsernamesList?: any | null
hasMultipleUsers?: boolean | null
includeUsernamesList?: any | null
}
}
interface UserManager {
// Own properties of AccountsService-1.0.AccountsService.UserManager
excludeUsernamesList: any
hasMultipleUsers: boolean
includeUsernamesList: any
readonly isLoaded: boolean
// Own fields of AccountsService-1.0.AccountsService.UserManager
parent: GObject.Object
// Owm methods of AccountsService-1.0.AccountsService.UserManager
/**
* Activate the session for a given user.
* @param user the user to activate
* @returns whether successfully activated
*/
activate_user_session(user: User): boolean
/**
* Caches a user account so it shows up via act_user_manager_list_users().
* @param username a user name
* @returns user object
*/
cache_user(username: string): User
/**
* Asynchronously caches a user account so it shows up via
* act_user_manager_list_users().
*
* For more details, see act_user_manager_cache_user(), which
* is the synchronous version of this call.
* @param username a unix user name
* @param cancellable optional #GCancellable object, %NULL to ignore
* @param callback a #GAsyncReadyCallback to call when the request is satisfied
*/
cache_user_async(username: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void
// Overloads of cache_user_async
/**
* Promisified version of {@link cache_user_async}
*
* Asynchronously caches a user account so it shows up via
* act_user_manager_list_users().
*
* For more details, see act_user_manager_cache_user(), which
* is the synchronous version of this call.
* @param username a unix user name
* @param cancellable optional #GCancellable object, %NULL to ignore
* @returns A Promise of: user object
*/
cache_user_async(username: string, cancellable: Gio.Cancellable | null): globalThis.Promise<User>
/**
* Finishes an asynchronous user caching.
*
* See act_user_manager_cache_user_async().
* @param result a #GAsyncResult
* @returns user object
*/
cache_user_finish(result: Gio.AsyncResult): User
/**
* Check whether the user can switch to another session.
* @returns whether we can switch to another session
*/
can_switch(): boolean
/**
* Creates a user account on the system.
* @param username a unix user name
* @param fullname a unix GECOS value
* @param accounttype a #ActUserAccountType
* @returns user object
*/
create_user(username: string, fullname: string, accounttype: UserAccountType): User
/**
* Asynchronously creates a user account on the system.
*
* For more details, see act_user_manager_create_user(), which
* is the synchronous version of this call.
* @param username a unix user name
* @param fullname a unix GECOS value
* @param accounttype a #ActUserAccountType
* @param cancellable optional #GCancellable object, %NULL to ignore
* @param callback a #GAsyncReadyCallback to call when the request is satisfied
*/
create_user_async(username: string, fullname: string, accounttype: UserAccountType, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void
// Overloads of create_user_async
/**
* Promisified version of {@link create_user_async}
*
* Asynchronously creates a user account on the system.
*
* For more details, see act_user_manager_create_user(), which
* is the synchronous version of this call.
* @param username a unix user name
* @param fullname a unix GECOS value
* @param accounttype a #ActUserAccountType
* @param cancellable optional #GCancellable object, %NULL to ignore
* @returns A Promise of: user object
*/
create_user_async(username: string, fullname: string, accounttype: UserAccountType, cancellable: Gio.Cancellable | null): globalThis.Promise<User>
/**
* Finishes an asynchronous user creation.
*
* See act_user_manager_create_user_async().
* @param result a #GAsyncResult
* @returns user object
*/
create_user_finish(result: Gio.AsyncResult): User
/**
* Deletes a user account on the system.
* @param user an #ActUser object
* @param remove_files %TRUE to delete the users home directory
* @returns %TRUE if the user account was successfully deleted
*/
delete_user(user: User, remove_files: boolean): boolean
/**
* Asynchronously deletes a user account from the system.
*
* For more details, see act_user_manager_delete_user(), which
* is the synchronous version of this call.
* @param user a #ActUser object
* @param remove_files %TRUE to delete the users home directory
* @param cancellable optional #GCancellable object, %NULL to ignore
* @param callback a #GAsyncReadyCallback to call when the request is satisfied
*/
delete_user_async(user: User, remove_files: boolean, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void
// Overloads of delete_user_async
/**
* Promisified version of {@link delete_user_async}
*
* Asynchronously deletes a user account from the system.
*
* For more details, see act_user_manager_delete_user(), which
* is the synchronous version of this call.
* @param user a #ActUser object
* @param remove_files %TRUE to delete the users home directory
* @param cancellable optional #GCancellable object, %NULL to ignore
* @returns A Promise of: %TRUE if the user account was successfully deleted
*/
delete_user_async(user: User, remove_files: boolean, cancellable: Gio.Cancellable | null): globalThis.Promise<boolean>
/**
* Finishes an asynchronous user account deletion.
*
* See act_user_manager_delete_user_async().
* @param result a #GAsyncResult
* @returns %TRUE if the user account was successfully deleted
*/
delete_user_finish(result: Gio.AsyncResult): boolean
/**
* Retrieves a pointer to the #ActUser object for the login `username`
* from `manager`. Trying to use this object before its
* #ActUser:is-loaded property is %TRUE will result in undefined
* behavior.
* @param username the login name of the user to get.
* @returns #ActUser object
*/
get_user(username: string): User
/**
* Retrieves a pointer to the #ActUser object for the user with the
* given uid from `manager`. Trying to use this object before its
* #ActUser:is-loaded property is %TRUE will result in undefined
* behavior.
* @param id the uid of the user to get.
* @returns #ActUser object
*/
get_user_by_id(id: number): User
/**
* Switch the display to the login manager.
* @returns whether successful or not
*/
goto_login_session(): boolean
/**
* Get a list of system user accounts
* @returns List of #ActUser objects
*/
list_users(): User[]
/**
* Check whether or not the accounts service is running.
* @returns whether or not accounts service is running
*/
no_service(): boolean
/**
* Releases all metadata about a user account, including icon,
* language and session. If the user account is from a remote
* server and the user has never logged in before, then that
* account will no longer show up in ListCachedUsers() output.
* @param username a user name
* @returns %TRUE if successful, otherwise %FALSE
*/
uncache_user(username: string): boolean
uncache_user_async(username: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void
// Overloads of uncache_user_async
/**
* Promisified version of {@link uncache_user_async}
*
*
* @param username
* @param cancellable
* @returns A Promise of: %TRUE if the user account was successfully uncached
*/
uncache_user_async(username: string, cancellable: Gio.Cancellable | null): globalThis.Promise<boolean>
/**
* Finishes an asynchronous user uncaching.
*
* See act_user_manager_uncache_user_async().
* @param result a #GAsyncResult
* @returns %TRUE if the user account was successfully uncached
*/
uncache_user_finish(result: Gio.AsyncResult): boolean
// Own virtual methods of AccountsService-1.0.AccountsService.UserManager
vfunc_user_added(user: User): void
vfunc_user_changed(user: User): void
vfunc_user_is_logged_in_changed(user: User): void
vfunc_user_removed(user: User): void
// Own signals of AccountsService-1.0.AccountsService.UserManager
connect(sigName: "user-added", callback: UserManager.UserAddedSignalCallback): number
connect_after(sigName: "user-added", callback: UserManager.UserAddedSignalCallback): number
emit(sigName: "user-added", user: User, ...args: any[]): void
connect(sigName: "user-changed", callback: UserManager.UserChangedSignalCallback): number
connect_after(sigName: "user-changed", callback: UserManager.UserChangedSignalCallback): number
emit(sigName: "user-changed", user: User, ...args: any[]): void
connect(sigName: "user-is-logged-in-changed", callback: UserManager.UserIsLoggedInChangedSignalCallback): number
connect_after(sigName: "user-is-logged-in-changed", callback: UserManager.UserIsLoggedInChangedSignalCallback): number
emit(sigName: "user-is-logged-in-changed", user: User, ...args: any[]): void
connect(sigName: "user-removed", callback: UserManager.UserRemovedSignalCallback): number
connect_after(sigName: "user-removed", callback: UserManager.UserRemovedSignalCallback): number
emit(sigName: "user-removed", user: User, ...args: any[]): void
// Class property signals of AccountsService-1.0.AccountsService.UserManager
connect(sigName: "notify::exclude-usernames-list", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::exclude-usernames-list", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::exclude-usernames-list", ...args: any[]): void
connect(sigName: "notify::has-multiple-users", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::has-multiple-users", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::has-multiple-users", ...args: any[]): void
connect(sigName: "notify::include-usernames-list", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::include-usernames-list", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::include-usernames-list", ...args: any[]): void
connect(sigName: "notify::is-loaded", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
connect_after(sigName: "notify::is-loaded", callback: (($obj: UserManager, pspec: GObject.ParamSpec) => void)): number
emit(sigName: "notify::is-loaded", ...args: any[]): void
connect(sigName: string, callback: (...args: any[]) => void): number
connect_after(sigName: string, callback: (...args: any[]) => void): number
emit(sigName: string, ...args: any[]): void
disconnect(id: number): void
}
/**
* A user manager object.
* @class
*/
class UserManager extends GObject.Object {
// Own properties of AccountsService-1.0.AccountsService.UserManager
static name: string
static $gtype: GObject.GType<UserManager>
// Constructors of AccountsService-1.0.AccountsService.UserManager
constructor(config?: UserManager.ConstructorProperties)
_init(config?: UserManager.ConstructorProperties): void
/**
* Returns the user manager singleton instance. Calling this function will
* automatically being loading the user list if it isn't loaded already.
* The #ActUserManager:is-loaded property will be set to %TRUE when the users
* are finished loading and then act_user_manager_list_users() can be called.
* @returns user manager object
*/
static get_default(): UserManager
}
interface UserClass {
// Own fields of AccountsService-1.0.AccountsService.UserClass
parent_class: GObject.ObjectClass
}
abstract class UserClass {
// Own properties of AccountsService-1.0.AccountsService.UserClass
static name: string
}
interface UserManagerClass {
// Own fields of AccountsService-1.0.AccountsService.UserManagerClass
parent_class: GObject.ObjectClass
user_added: (user_manager: UserManager, user: User) => void
user_removed: (user_manager: UserManager, user: User) => void
user_is_logged_in_changed: (user_manager: UserManager, user: User) => void
user_changed: (user_manager: UserManager, user: User) => void
}
abstract class UserManagerClass {
// Own properties of AccountsService-1.0.AccountsService.UserManagerClass
static name: string
}
/**
* Name of the imported GIR library
* @see https://gitlab.gnome.org/GNOME/gjs/-/blob/master/gi/ns.cpp#L188
*/
const __name__: string
/**
* Version of the imported GIR library
* @see https://gitlab.gnome.org/GNOME/gjs/-/blob/master/gi/ns.cpp#L189
*/
const __version__: string
}
export default AccountsService;
// END

View file

@ -0,0 +1,10 @@
// @ts-expect-error
import AccountsService from 'gi://AccountsService?version=1.0';
export { AccountsService };
export default AccountsService;

View file

@ -0,0 +1,60 @@
{
"name": "@girs/accountsservice-1.0",
"version": "1.0.0-3.3.0",
"description": "GJS TypeScript type definitions for AccountsService-1.0, generated from library version 1.0.0",
"type": "module",
"module": "accountsservice-1.0.js",
"main": "accountsservice-1.0.js",
"exports": {
"./ambient": {
"types": "./accountsservice-1.0-ambient.d.ts",
"default": "./accountsservice-1.0-ambient.js"
},
"./import": {
"types": "./accountsservice-1.0-import.d.ts",
"default": "./accountsservice-1.0-import.js"
},
".": {
"import": {
"types": "./accountsservice-1.0.d.ts",
"default": "./accountsservice-1.0.js"
},
"require": {
"types": "./accountsservice-1.0.d.cts",
"default": "./accountsservice-1.0.cjs"
}
}
},
"scripts": {
"test": "yarn test:esm && yarn test:cjs",
"test:esm": "NODE_OPTIONS=--max_old_space_size=9216 tsc --noEmit accountsservice-1.0.d.ts",
"test:cjs": "NODE_OPTIONS=--max_old_space_size=9216 tsc --noEmit accountsservice-1.0.d.cts"
},
"dependencies": {
"@girs/gio-2.0": "^2.78.0-3.3.0",
"@girs/gjs": "^3.3.0",
"@girs/glib-2.0": "^2.78.0-3.3.0",
"@girs/gobject-2.0": "^2.78.0-3.3.0"
},
"devDependencies": {
"typescript": "*"
},
"keywords": [
"Gir",
"TypeScript",
"types",
"GObject-Introspection",
"GJS",
"AccountsService-1.0"
],
"author": "ts-for-gir",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/gjsify/ts-for-gir.git"
},
"bugs": {
"url": "https://github.com/gjsify/ts-for-gir/issues"
},
"homepage": "https://github.com/gjsify/types/tree/main/accountsservice-1.0#readme"
}

View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
// General settings for code interpretation
"target": "ESNext",
"module": "ESNext",
"lib": ["ESNext"],
"types": [],
"experimentalDecorators": true,
"moduleResolution": "node",
"noEmit": true,
"noEmitOnError": false,
"baseUrl": "./",
"rootDir": ".",
// General settings for code generation
"removeComments": false,
"inlineSourceMap": false,
"inlineSources": false,
"newLine": "LF"
},
"include": ["./accountsservice-1.0.d.ts"]
}

View file

@ -0,0 +1,7 @@
{
"entryPoints": ["./accountsservice-1.0.d.ts"],
"readme": "./README.md",
"name": "AccountsService-1.0",
"tsconfig": "./tsconfig.json"
}

105
home/ags/node_modules/@girs/gio-2.0/README.md generated vendored Normal file
View file

@ -0,0 +1,105 @@
# Gio-2.0
![version](https://img.shields.io/npm/v/@girs/gio-2.0)
![downloads/week](https://img.shields.io/npm/dw/@girs/gio-2.0)
GJS TypeScript type definitions for Gio-2.0, generated from library version 2.78.0 using [ts-for-gir](https://github.com/gjsify/ts-for-gir) v3.3.0.
GIO provides a modern and easy-to-use VFS API. It provides a file system abstraction which allows applications to access local and remote files with a single consistent API.
## Install
To use this type definitions, install them with NPM:
```bash
npm install @girs/gio-2.0
```
## Usage
You can import this package into your project like this:
```ts
import Gio from '@girs/gio-2.0';
```
Or if you prefer CommonJS, you can also use this:
```ts
const Gio = require('@girs/gio-2.0');
```
### Ambient Modules
You can also use [ambient modules](https://github.com/gjsify/ts-for-gir/tree/main/packages/cli#ambient-modules) to import this module like you would do this in JavaScript.
For this you need to include `@girs/gio-2.0` or `@girs/gio-2.0/ambient` in your `tsconfig` or entry point Typescript file:
`index.ts`:
```ts
import '@girs/gio-2.0'
```
`tsconfig.json`:
```json
{
"compilerOptions": {
...
},
"include": ["@girs/gio-2.0"],
...
}
```
Now you can import the ambient module with TypeScript support:
```ts
import Gio from 'gi://Gio?version=2.0';
```
### Global import
You can also import the module with Typescript support using the global `imports.gi` object of GJS.
For this you need to include `@girs/gio-2.0` or `@girs/gio-2.0/import` in your `tsconfig` or entry point Typescript file:
`index.ts`:
```ts
import '@girs/gio-2.0'
```
`tsconfig.json`:
```json
{
"compilerOptions": {
...
},
"include": ["@girs/gio-2.0"],
...
}
```
Now you have also type support for this, too:
```ts
const Gio = imports.gi.Gio;
```
### ESM vs. CommonJS
GJS supports two different import syntaxes. The new modern ESM syntax and the old global imports syntax.
In TypeScript projects for GJS and GNOME Shell extensions, you have the flexibility to use `ESM` syntax and then decide the import syntax for your bundled file. If your bundler is configured to use `CommonJS`, it will convert to the GJS-specific global imports syntax, like `const moduleName = imports.gi[moduleName]`. This is different from the traditional `require` syntax seen in Node.js. The global imports syntax is chosen because it aligns with the CommonJS format supported by NPM, which is used for the generated type definitions and this package.
On the other hand, if you configure your bundler to use ESM, it will retain the ESM import syntax. It's crucial to ensure that your bundler is set up to correctly translate and bundle these imports into either CommonJS or ESM format, depending on your project's requirements.
This approach is particularly important due to the `@girs` types, which include both `*.cjs `files, using the GJS global imports syntax, and `*.js` files, which utilize the ESM syntax. By appropriately setting up your bundler, you can control which syntax—CommonJS or ESM—is used in your project. The choice of CommonJS in this context is also due to the similarity between the GJS-specific global imports and CommonJS syntax, allowing for easier management and bundling in these specific types of projects.
Since GNOME Shell 45, you should only use ESM, even for GNOME Shell extensions. Before that, extensions had to use the global import syntax, unlike normal GJS applications, where ESM has been available for some time.
### Bundle
Depending on your project configuration, it is recommended to use a bundler like [esbuild](https://esbuild.github.io/). You can find examples using different bundlers [here](https://github.com/gjsify/ts-for-gir/tree/main/examples).
## Other packages
All existing pre-generated packages can be found on [gjsify/types](https://github.com/gjsify/types).

View file

@ -0,0 +1,12 @@
declare module 'gi://Gio?version=2.0' {
import Gio20 from '@girs/gio-2.0';
export default Gio20;
}
declare module 'gi://Gio' {
import Gio20 from '@girs/gio-2.0';
export default Gio20;
}

View file

@ -0,0 +1,2 @@
export {}

View file

@ -0,0 +1,12 @@
import Gio20 from '@girs/gio-2.0';
declare global {
export interface GjsGiImports {
Gio: typeof Gio20;
}
}
export default GjsGiImports;

View file

@ -0,0 +1,3 @@
const gi = globalThis.imports?.gi || {};
export default gi;

11
home/ags/node_modules/@girs/gio-2.0/gio-2.0.cjs generated vendored Normal file
View file

@ -0,0 +1,11 @@
imports.gi.versions.Gio = '2.0'
const Gio = imports.gi.Gio;
module.exports = Gio;

53528
home/ags/node_modules/@girs/gio-2.0/gio-2.0.d.cts generated vendored Normal file

File diff suppressed because it is too large Load diff

53533
home/ags/node_modules/@girs/gio-2.0/gio-2.0.d.ts generated vendored Normal file

File diff suppressed because it is too large Load diff

10
home/ags/node_modules/@girs/gio-2.0/gio-2.0.js generated vendored Normal file
View file

@ -0,0 +1,10 @@
// @ts-expect-error
import Gio from 'gi://Gio?version=2.0';
export { Gio };
export default Gio;

59
home/ags/node_modules/@girs/gio-2.0/package.json generated vendored Normal file
View file

@ -0,0 +1,59 @@
{
"name": "@girs/gio-2.0",
"version": "2.78.0-3.3.0",
"description": "GJS TypeScript type definitions for Gio-2.0, generated from library version 2.78.0",
"type": "module",
"module": "gio-2.0.js",
"main": "gio-2.0.js",
"exports": {
"./ambient": {
"types": "./gio-2.0-ambient.d.ts",
"default": "./gio-2.0-ambient.js"
},
"./import": {
"types": "./gio-2.0-import.d.ts",
"default": "./gio-2.0-import.js"
},
".": {
"import": {
"types": "./gio-2.0.d.ts",
"default": "./gio-2.0.js"
},
"require": {
"types": "./gio-2.0.d.cts",
"default": "./gio-2.0.cjs"
}
}
},
"scripts": {
"test": "yarn test:esm && yarn test:cjs",
"test:esm": "NODE_OPTIONS=--max_old_space_size=9216 tsc --noEmit gio-2.0.d.ts",
"test:cjs": "NODE_OPTIONS=--max_old_space_size=9216 tsc --noEmit gio-2.0.d.cts"
},
"dependencies": {
"@girs/gjs": "^3.3.0",
"@girs/glib-2.0": "^2.78.0-3.3.0",
"@girs/gobject-2.0": "^2.78.0-3.3.0"
},
"devDependencies": {
"typescript": "*"
},
"keywords": [
"Gir",
"TypeScript",
"types",
"GObject-Introspection",
"GJS",
"Gio-2.0"
],
"author": "ts-for-gir",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/gjsify/ts-for-gir.git"
},
"bugs": {
"url": "https://github.com/gjsify/ts-for-gir/issues"
},
"homepage": "https://github.com/gjsify/types/tree/main/gio-2.0#readme"
}

23
home/ags/node_modules/@girs/gio-2.0/tsconfig.json generated vendored Normal file
View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
// General settings for code interpretation
"target": "ESNext",
"module": "ESNext",
"lib": ["ESNext"],
"types": [],
"experimentalDecorators": true,
"moduleResolution": "node",
"noEmit": true,
"noEmitOnError": false,
"baseUrl": "./",
"rootDir": ".",
// General settings for code generation
"removeComments": false,
"inlineSourceMap": false,
"inlineSources": false,
"newLine": "LF"
},
"include": ["./gio-2.0.d.ts"]
}

7
home/ags/node_modules/@girs/gio-2.0/typedoc.json generated vendored Normal file
View file

@ -0,0 +1,7 @@
{
"entryPoints": ["./gio-2.0.d.ts"],
"readme": "./README.md",
"name": "Gio-2.0",
"tsconfig": "./tsconfig.json"
}

126
home/ags/node_modules/@girs/gjs/README.md generated vendored Normal file
View file

@ -0,0 +1,126 @@
# Gjs
![version](https://img.shields.io/npm/v/@girs/gjs)
![downloads/week](https://img.shields.io/npm/dw/@girs/gjs)
GJS TypeScript type definitions for Gjs using [ts-for-gir](https://github.com/gjsify/ts-for-gir) v3.3.0.
[GJS](https://gitlab.gnome.org/GNOME/gjs) is a JavaScript runtime for the GNOME ecosystem. Using GJS and the type definitions in this NPM package, you can build GTK applications in JavaScript or TypeScript with type checking, better autocompletion and inline documentations.
## Install
To use this type definitions, install them with NPM:
```bash
npm install @girs/gjs
```
## Usage
You can import this package into your project like this:
```ts
import Gjs from '@girs/gjs';
```
Or if you prefer CommonJS, you can also use this:
```ts
const Gjs = require('@girs/gjs');
```
### Global types
After the import, the global types of GJS are also available:
```ts
import '@girs/gjs';
print('Hello World from print');
const ByteArray = imports.byteArray;
// And so on...
```
### Global DOM types
Some types that conflict with the DOM are outsourced to allow frameworks like Gjsify to rebuild the DOM API without causing type conflicts.
But you can easily import them:
```ts
import '@girs/gjs/dom';
console.log('Hello World from console');
const encoder = new TextEncoder();
const encoded = encoder.encode('𝓽𝓮𝔁𝓽');
setTimeout(() => {
// ...
}, 1000);
// And so on...
```
To avoid a type conflict with the DOM types it is recommended to either modify your `tsconfig.json` or `jsconfig.json` file to exclude the DOM lib, or to enable the `noLib` property.
### Ambient Modules
You can import the built in [ambient modules](https://github.com/gjsify/ts-for-gir/tree/main/packages/cli#ambient-modules) of GJS.
For this you need to include the `@girs/gjs` or `@girs/gjs/ambient` in your `tsconfig` or entry point Typescript file:
`index.ts`:
```ts
import '@girs/gjs'
```
`tsconfig.json`:
```json
{
"compilerOptions": {
...
},
"include": ["@girs/gjs"],
...
}
```
Now you can import `gettext`, `system` and `cairo` in ESM style with Typescript support:
```ts
import gettext from 'gettext';
import system from 'system';
import cairo from 'cairo';
```
### GIR modules
If you want to have types for [GObject Introspection](https://gi.readthedocs.io/en/latest/) modules, you have to add them to your dependencies and import them as well, see the description of these modules, e.g. [gtk-4.0](https://www.npmjs.com/package/@girs/gtk-4.0), [gio-2.0](https://www.npmjs.com/package/@girs/gio-2.0), [adw-1](https://www.npmjs.com/package/@girs/adw-1) and [much more](https://github.com/gjsify/types).
These types will then be available to you:
```ts
import '@girs/gjs'
import '@girs/gjs/dom'
import '@girs/gio-2.0'
import '@girs/gtk-4.0'
import '@girs/adw-1'
import Gio from 'gi://Gio?version=2.0';
import Gtk from 'gi://Gtk?version=4.0';
import Adwaita from 'gi://adw?version=1';
const button = new Gtk.Button();
// ...
```
### Bundle
Depending on your project configuration, it is recommended to use a bundler like [esbuild](https://esbuild.github.io/). You can find examples using different bundlers [here](https://github.com/gjsify/ts-for-gir/tree/main/examples).
## Other packages
All existing pre-generated packages can be found on [gjsify/types](https://github.com/gjsify/types).

20
home/ags/node_modules/@girs/gjs/ambient.d.ts generated vendored Normal file
View file

@ -0,0 +1,20 @@
// https://www.typescriptlang.org/docs/handbook/modules.html#ambient-modules
// https://stackoverflow.com/questions/45099605/ambient-declaration-with-an-imported-type-in-typescript
declare module 'gettext' {
export * from '@girs/gjs/gettext';
import Gettext from '@girs/gjs/gettext';
export default Gettext;
}
declare module 'system' {
export * from '@girs/gjs/system';
import System from '@girs/gjs/system';
export default System;
}
declare module 'cairo' {
import Cairo from '@girs/gjs/cairo';
export default Cairo;
}

3
home/ags/node_modules/@girs/gjs/ambient.js generated vendored Normal file
View file

@ -0,0 +1,3 @@
export {};

8
home/ags/node_modules/@girs/gjs/cairo.cjs generated vendored Normal file
View file

@ -0,0 +1,8 @@
const Cairo = imports.cairo;
module.exports = Cairo;
exports.default = Cairo;

10
home/ags/node_modules/@girs/gjs/cairo.d.cts generated vendored Normal file
View file

@ -0,0 +1,10 @@
// TODO: See ./cairo-1.0.d.ts
declare const Cairo: any;
export default Cairo;
// TODO declare named exports here, cairo doesn't have named exports for its esm module but for cjs we can use `const { Context } = imports.cairo` for that, see `./cairo.js`

8
home/ags/node_modules/@girs/gjs/cairo.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
// TODO: See ./cairo-1.0.d.ts
declare const Cairo: any;
export default Cairo;

8
home/ags/node_modules/@girs/gjs/cairo.js generated vendored Normal file
View file

@ -0,0 +1,8 @@
import Cairo from 'cairo';
// cairo doesn't have named exports, see https://gitlab.gnome.org/GNOME/gjs/-/blob/c2a714f348d6848037f072063e0a914fd537c4f4/installed-tests/js/testCairoModule.js#L14
export default Cairo;

316
home/ags/node_modules/@girs/gjs/dom.d.ts generated vendored Normal file
View file

@ -0,0 +1,316 @@
/**
* Gjs has implemented some functionality from the DOM API,
* this leads to a conflict when all DOM (`lib.dom.d.ts`) should be used.
* This should normally not be the case, since the other - not yet reimplemented - API's cannot be used in GJS anyway.
* In particular, Gjsify tries to rebuild the DOM API and therefore does not need these types.
* For this reason they are stored in this separate file to make them optional.
*
* See also https://github.com/microsoft/TypeScript/blob/main/lib/lib.dom.d.ts
*/
import type GLib from '@girs/glib-2.0';
declare global {
interface ImportMeta {
/**
* The absolute file: or resource: URL of the module.
*
* @see https://gitlab.gnome.org/GNOME/gjs/-/blob/master/doc/ESModules.md#importmetaurl
*/
readonly url: string;
}
// Timers
// See https://gitlab.gnome.org/GNOME/gjs/-/blob/master/modules/esm/_timers.js
/**
* @version Gjs 1.71.1
* @param callback a callback function
* @param delay the duration in milliseconds to wait before running callback
* @param args arguments to pass to callback
*/
function setTimeout(callback: (...args: any[]) => any, delay?: number, ...args: any[]): GLib.Source
/**
* @version Gjs 1.71.1
* @param callback a callback function
* @param delay the duration in milliseconds to wait between calling callback
* @param args arguments to pass to callback
*/
function setInterval(callback: (...args: any[]) => any, delay?: number, ...args: any[]): GLib.Source
/**
* @version Gjs 1.71.1
* @param timeout the timeout to clear
*/
function clearTimeout(timeout: GLib.Source): void
/**
* @version Gjs 1.71.1
* @param timeout the timeout to clear
*/
function clearInterval(timeout: GLib.Source): void
interface Console {
/**
* Logs a critical message if the condition is not truthy.
* {@link console.error()} for additional information.
*
* @param condition a boolean condition which, if false, causes
* the log to print
* @param data formatting substitutions, if applicable
* @returns
*/
assert(condition: boolean, ...data: any[]): void
/**
* Resets grouping and clears the terminal on systems supporting ANSI
* terminal control sequences.
*
* In file-based stdout or systems which do not support clearing,
* console.clear() has no visual effect.
*
*/
clear(): void
/**
* Logs a message with severity equal to {@link GLib.LogLevelFlags.DEBUG}.
*
* @param {...any} data formatting substitutions, if applicable
*/
debug(...data: any[]): void
/**
* Logs a message with severity equal to {@link GLib.LogLevelFlags.CRITICAL}.
* Does not use {@link GLib.LogLevelFlags.ERROR} to avoid asserting and
* forcibly shutting down the application.
*
* @param data formatting substitutions, if applicable
*/
error(...data: any[]): void
/**
* Logs a message with severity equal to {@link GLib.LogLevelFlags.INFO}.
*
* @param data formatting substitutions, if applicable
*/
info(...data: any[]): void
/**
* Logs a message with severity equal to {@link GLib.LogLevelFlags.MESSAGE}.
*
* @param data formatting substitutions, if applicable
*/
log(...data: any[]): void
// 1.1.7 table(tabularData, properties)
table(tabularData: any, _properties: never): void
/**
* @param data formatting substitutions, if applicable
*/
trace(...data: any[]): void
/**
* @param data formatting substitutions, if applicable
*/
warn(...data: any[]): void
/**
* @param item an item to format generically
* @param [options] any additional options for the formatter. Unused
* in our implementation.
*/
dir(item: object, options: never): void
/**
* @param data formatting substitutions, if applicable
*/
dirxml(...data: any[]): void
// 1.2 Counting functions
// https://console.spec.whatwg.org/#counting
/**
* Logs how many times console.count(label) has been called with a given
* label.
* {@link console.countReset()} for resetting a count.
*
* @param label unique identifier for this action
*/
count(label: string): void
/**
* @param label the unique label to reset the count for
*/
countReset(label: string): void
// 1.3 Grouping functions
// https://console.spec.whatwg.org/#grouping
/**
* @param data formatting substitutions, if applicable
*/
group(...data: any[]): void
/**
* Alias for console.group()
*
* @param {...any} data formatting substitutions, if applicable
*/
groupCollapsed(...data: any[]): void
/**
*/
groupEnd(): void
// 1.4 Timing functions
// https://console.spec.whatwg.org/#timing
/**
* @param label unique identifier for this action, pass to
* console.timeEnd() to complete
*/
time(label: string): void
/**
* Logs the time since the last call to console.time(label) where label is
* the same.
*
* @param label unique identifier for this action, pass to
* console.timeEnd() to complete
* @param data string substitutions, if applicable
*/
timeLog(label: string, ...data: any[]): void
/**
* Logs the time since the last call to console.time(label) and completes
* the action.
* Call console.time(label) again to re-measure.
*
* @param label unique identifier for this action
*/
timeEnd(label: string): void
// Non-standard functions which are de-facto standards.
// Similar to Node, we define these as no-ops for now.
/**
* @deprecated Not implemented in GJS
*
* @param _label unique identifier for this action, pass to
* console.profileEnd to complete
*/
profile(_label: string): void
/**
* @deprecated Not implemented in GJS
*
* @param _label unique identifier for this action
*/
profileEnd(_label: string): void
/**
* @deprecated Not implemented in GJS
*
* @param _label unique identifier for this action
*/
timeStamp(_label: string): void
// GJS-specific extensions for integrating with GLib structured logging
/**
* @param logDomain the GLib log domain this Console should print
* with. Defaults to 'Gjs-Console'.
*/
setLogDomain(logDomain: string): void
logDomain: string
interact(): void
}
interface TextDecodeOptions {
// As of Gjs 1.73.2 stream mode is not supported yet.
// stream?: boolean
}
interface TextDecoderOptions {
/** Indicates whether the error mode is fatal. */
fatal?: boolean
/** Indicates whether whether the byte order mark is ignored. */
ignoreBOM?: boolean
}
/**
* The TextDecoder interface represents a decoder for a specific text encoding.
* It takes a stream of bytes as input and emits a stream of code points.
*
* @version Gjs 1.69.2
*/
interface TextDecoder {
/** A string containing the name of the decoder, that is a string describing the method the TextDecoder will use. */
readonly encoding: TextDecoderEncoding
/** A Boolean indicating whether the error mode is fatal. */
readonly fatal: boolean
/** A Boolean indicating whether the byte order mark is ignored. */
readonly ignoreBOM: boolean
/**
* Returns a string containing the text decoded with the method of the specific TextDecoder object.
*
* If the error mode is "fatal" and the encoder method encounter an error it WILL THROW a TypeError.
*
* @param input Buffer containing the text to decode
* @param options Object defining the decode options
*/
decode(input?: ArrayBufferView | ArrayBuffer, options?: TextDecodeOptions): string
}
interface TextEncoderEncodeIntoResult {
read?: number
written?: number
}
/**
* TextEncoder takes a stream of code points as input and emits a stream of bytes.
*
* @version Gjs 1.69.2
*/
interface TextEncoder {
readonly encoding: 'utf-8'
/**
* Takes a string as input, and returns a buffer containing the text given in parameters encoded with the UTF-8 method.
*
* @param input Text to encode.
*/
encode(input?: string): Uint8Array
/**
* Takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into,
* and returns a dictionary object indicating the progress of the encoding.
*
* This is potentially more performant than the older encode() method.
*
* @param source Text to encode.
* @param destination Buffer where to place the resulting UTF-8 encoded text into.
*/
encodeInto(source: string, destination: Uint8Array): TextEncoderEncodeIntoResult
}
const console: Console
const TextDecoder: {
prototype: TextDecoder
new (label?: TextDecoderEncoding, options?: TextDecoderOptions): TextDecoder
}
const TextEncoder: {
prototype: TextEncoder
new (): TextEncoder
}
}
export {}

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