docs: 仓库链接指向本镜像仓库
Build NapCat Artifacts / Windows Loader Test (push) Canceled after 0s
Build NapCat Artifacts / Type Check & Test (push) Canceled after 0s
Build NapCat Artifacts / Build NapCat.Framework (push) Canceled after 0s
Build NapCat Artifacts / Build NapCat.Shell (push) Canceled after 0s

This commit is contained in:
TanTan committed 2026-11-13 09:25:58 +08:00
1 parent f954252a34
commit e311ca3275
35554 files changed
+6229626 -4

No files matched your search

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2020 James Halliday (mail@substack.net) and Mathias Buus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,21 @@
{
"name": "@react-types/link",
"version": "3.5.9",
"description": "Spectrum UI components in React",
"license": "Apache-2.0",
"types": "src/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/adobe/react-spectrum"
},
"dependencies": {
"@react-types/shared": "^3.26.0"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1"
},
"publishConfig": {
"access": "public"
},
"gitHead": "71f0ef23053f9e03ee7e97df736e8b083e006849"
}
@@ -0,0 +1,38 @@
{
"name": "@types/cors",
"version": "2.8.19",
"description": "TypeScript definitions for cors",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cors",
"license": "MIT",
"contributors": [
{
"name": "Alan Plum",
"githubUsername": "pluma",
"url": "https://github.com/pluma"
},
{
"name": "Gaurav Sharma",
"githubUsername": "gtpan77",
"url": "https://github.com/gtpan77"
},
{
"name": "Sebastian Beltran",
"githubUsername": "bjohansebas",
"url": "https://github.com/bjohansebas"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/cors"
},
"scripts": {},
"dependencies": {
"@types/node": "*"
},
"peerDependencies": {},
"typesPublisherContentHash": "a090e558c5f443573318c2955deecddc840bd8dfaac7cdedf31c7f6ede8d0b47",
"typeScriptVersion": "5.1"
}
@@ -0,0 +1,7 @@
import * as react_jsx_runtime from 'react/jsx-runtime';
import { IconSvgProps } from './types.js';
import 'react';
declare const ChevronDownIcon: ({ strokeWidth, ...props }: IconSvgProps) => react_jsx_runtime.JSX.Element;
export { ChevronDownIcon };
@@ -0,0 +1,45 @@
import arrayMap from './_arrayMap.js';
import baseIntersection from './_baseIntersection.js';
import baseIteratee from './_baseIteratee.js';
import baseRest from './_baseRest.js';
import castArrayLikeObject from './_castArrayLikeObject.js';
import last from './last.js';
/**
* This method is like `_.intersection` except that it accepts `iteratee`
* which is invoked for each element of each `arrays` to generate the criterion
* by which they're compared. The order and references of result values are
* determined by the first array. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns the new array of intersecting values.
* @example
*
* _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
* // => [2.1]
*
* // The `_.property` iteratee shorthand.
* _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }]
*/
var intersectionBy = baseRest(function(arrays) {
var iteratee = last(arrays),
mapped = arrayMap(arrays, castArrayLikeObject);
if (iteratee === last(mapped)) {
iteratee = undefined;
} else {
mapped.pop();
}
return (mapped.length && mapped[0] === arrays[0])
? baseIntersection(mapped, baseIteratee(iteratee, 2))
: [];
});
export default intersectionBy;
@@ -0,0 +1 @@
module.exports={C:{"115":0.11849,"123":0.00539,"125":0.00539,"133":0.00539,"134":0.00539,"136":0.01616,"137":0.00539,"138":0.01616,"140":0.01077,"141":0.01077,"142":0.01616,"143":0.87792,"144":0.65171,"145":0.00539,_:"2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 116 117 118 119 120 121 122 124 126 127 128 129 130 131 132 135 139 146 147 3.5 3.6"},D:{"39":0.02154,"40":0.02154,"41":0.02154,"42":0.02154,"43":0.02154,"44":0.02154,"45":0.02154,"46":0.02154,"47":0.02154,"48":0.02154,"49":0.02154,"50":0.02154,"51":0.02154,"52":0.02154,"53":0.02154,"54":0.02154,"55":0.02154,"56":0.02154,"57":0.02154,"58":0.02154,"59":0.02154,"60":0.02154,"65":0.00539,"66":0.00539,"70":0.00539,"75":0.00539,"78":0.00539,"79":0.02154,"86":0.02693,"87":0.01616,"89":0.03232,"91":0.05386,"92":0.00539,"93":0.06463,"96":0.00539,"98":0.01077,"100":0.00539,"101":0.00539,"102":0.0377,"103":1.86894,"105":0.14004,"107":0.00539,"108":0.01077,"109":1.08259,"111":0.02154,"112":0.01077,"113":0.00539,"114":0.09695,"115":0.00539,"116":0.08618,"117":0.00539,"118":0.01077,"119":0.01616,"120":0.04847,"121":0.02154,"122":0.10772,"123":0.02154,"124":0.02154,"125":3.44165,"126":0.24237,"127":0.02693,"128":0.06463,"129":0.0377,"130":0.0377,"131":0.10233,"132":0.14004,"133":0.0754,"134":0.08079,"135":0.08079,"136":0.07002,"137":0.2316,"138":0.74865,"139":0.70557,"140":12.26392,"141":17.98385,"142":0.12926,"143":0.00539,_:"4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 61 62 63 64 67 68 69 71 72 73 74 76 77 80 81 83 84 85 88 90 94 95 97 99 104 106 110 144 145"},F:{"85":0.00539,"91":0.01616,"92":0.02693,"95":0.01077,"119":0.00539,"120":0.08079,"121":0.04847,"122":0.44165,_:"9 11 12 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 60 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 86 87 88 89 90 93 94 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 9.5-9.6 10.0-10.1 10.5 10.6 11.1 11.5 11.6 12.1"},B:{"92":0.00539,"109":0.01077,"114":0.01077,"118":0.00539,"120":0.00539,"122":0.00539,"131":0.00539,"132":0.00539,"133":0.00539,"134":0.00539,"135":0.00539,"136":0.00539,"137":0.00539,"138":0.02693,"139":0.03232,"140":0.71095,"141":2.36445,"142":0.00539,_:"12 13 14 15 16 17 18 79 80 81 83 84 85 86 87 88 89 90 91 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 110 111 112 113 115 116 117 119 121 123 124 125 126 127 128 129 130"},E:{"14":0.00539,_:"0 4 5 6 7 8 9 10 11 12 13 15 3.1 3.2 5.1 6.1 7.1 9.1 10.1 11.1 12.1 15.1 26.2","13.1":0.00539,"14.1":0.02693,"15.2-15.3":0.00539,"15.4":0.00539,"15.5":0.00539,"15.6":0.05925,"16.0":0.00539,"16.1":0.01077,"16.2":0.01077,"16.3":0.01077,"16.4":0.00539,"16.5":0.01616,"16.6":0.05925,"17.0":0.01077,"17.1":0.0377,"17.2":0.01077,"17.3":0.01616,"17.4":0.02154,"17.5":0.04309,"17.6":0.14542,"18.0":0.02154,"18.1":0.0377,"18.2":0.01616,"18.3":0.06463,"18.4":0.04847,"18.5-18.6":0.25314,"26.0":0.47935,"26.1":0.01077},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00141,"5.0-5.1":0,"6.0-6.1":0.00565,"7.0-7.1":0.00424,"8.1-8.4":0,"9.0-9.2":0,"9.3":0.01271,"10.0-10.2":0.00141,"10.3":0.02401,"11.0-11.2":0.35591,"11.3-11.4":0.00847,"12.0-12.1":0.00282,"12.2-12.5":0.0692,"13.0-13.1":0,"13.2":0.00706,"13.3":0.00282,"13.4-13.7":0.0113,"14.0-14.4":0.02401,"14.5-14.8":0.02542,"15.0-15.1":0.02401,"15.2-15.3":0.01836,"15.4":0.02119,"15.5":0.02401,"15.6-15.8":0.31354,"16.0":0.04237,"16.1":0.07909,"16.2":0.04096,"16.3":0.07344,"16.4":0.01836,"16.5":0.03248,"16.6-16.7":0.41947,"17.0":0.02966,"17.1":0.0452,"17.2":0.03248,"17.3":0.04802,"17.4":0.08474,"17.5":0.14547,"17.6-17.7":0.36721,"18.0":0.08333,"18.1":0.17231,"18.2":0.09321,"18.3":0.29942,"18.4":0.15395,"18.5-18.6":7.84982,"26.0":0.97028,"26.1":0.03531},P:{"4":0.05279,"22":0.01056,"23":0.01056,"25":0.01056,"26":0.01056,"27":0.03167,"28":0.96079,"29":0.05279,_:"20 21 24 5.0-5.4 6.2-6.4 8.2 9.2 10.1 11.1-11.2 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0","7.2-7.4":0.03167},I:{"0":0.01382,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0,"4.2-4.3":0,"4.4":0,"4.4.3-4.4.4":0.00001},K:{"0":0.39219,_:"10 11 12 11.1 11.5 12.1"},A:{"8":0.00846,"11":0.05078,_:"6 7 9 10 5.5"},S:{_:"2.5 3.0-3.1"},J:{_:"7 10"},N:{_:"10 11"},R:{_:"0"},M:{"0":0.17533},Q:{"14.9":0.00461},O:{"0":0.32298},H:{"0":0},L:{"0":34.15531}};
@@ -0,0 +1,188 @@
# style-to-object
[![NPM](https://nodei.co/npm/style-to-object.png)](https://nodei.co/npm/style-to-object/)
[![NPM version](https://badgen.net/npm/v/style-to-object)](https://www.npmjs.com/package/style-to-object)
[![Bundlephobia minified + gzip](https://badgen.net/bundlephobia/minzip/style-to-object)](https://bundlephobia.com/package/style-to-object)
[![build](https://github.com/remarkablemark/style-to-object/actions/workflows/build.yml/badge.svg)](https://github.com/remarkablemark/style-to-object/actions/workflows/build.yml)
[![codecov](https://codecov.io/gh/remarkablemark/style-to-object/branch/master/graph/badge.svg?token=XWxph9dpa4)](https://codecov.io/gh/remarkablemark/style-to-object)
[![NPM downloads](https://badgen.net/npm/dm/style-to-object)](https://www.npmjs.com/package/style-to-object)
Parse CSS inline style to JavaScript object:
```js
import parse from 'style-to-object';
parse('color: #C0FFEE; background: #BADA55;');
```
Output:
```js
{ color: '#C0FFEE', background: '#BADA55' }
```
[JSFiddle](https://jsfiddle.net/remarkablemark/ykz2meot/) | [Replit](https://replit.com/@remarkablemark/style-to-object) | [Examples](https://github.com/remarkablemark/style-to-object/tree/master/examples)
## Installation
[NPM](https://www.npmjs.com/package/style-to-object):
```sh
npm install style-to-object --save
```
[Yarn](https://yarn.fyi/style-to-object):
```sh
yarn add style-to-object
```
[CDN](https://unpkg.com/style-to-object/):
```html
<script src="https://unpkg.com/style-to-object@latest/dist/style-to-object.min.js"></script>
<script>
window.StyleToObject(/* string */);
</script>
```
## Usage
Import with ES Modules:
```js
import parse from 'style-to-object';
```
Require with CommonJS:
```js
const parse = require('style-to-object').default;
```
Parse single declaration:
```js
parse('line-height: 42');
```
Output:
```js
{ 'line-height': '42' }
```
Parse multiple declarations:
```js
parse(`
border-color: #ACE;
z-index: 1337;
`);
```
Output:
```js
{ 'border-color': '#ACE', 'z-index': '1337' }
```
Parse unknown declarations:
```js
parse('answer: 42;');
```
Output:
```js
{ 'answer': '42' }
```
Invalid declarations/arguments:
<!-- prettier-ignore-start -->
```js
parse(`
top: ;
right: 1em;
`); // { right: '1em' }
parse(); // null
parse(null); // null
parse(1); // null
parse(true); // null
parse('top:'); // null
parse(':12px'); // null
parse(':'); // null
parse(';'); // null
parse('top'); // throws Error
parse('/*'); // throws Error
```
<!-- prettier-ignore-end -->
### Iterator
If the 2nd argument is a function, then the parser will return `null`:
```js
parse('color: #f00', () => {}); // null
```
But the function will iterate through each declaration:
<!-- prettier-ignore-start -->
```js
parse('color: #f00', (name, value, declaration) => {
console.log(name); // 'color'
console.log(value); // '#f00'
console.log(declaration); // { type: 'declaration', property: 'color', value: '#f00' }
});
```
<!-- prettier-ignore-end -->
This makes it easy to customize the output:
```js
const style = `
color: red;
background: blue;
`;
const output = [];
function iterator(name, value) {
output.push([name, value]);
}
parse(style, iterator);
console.log(output); // [['color', 'red'], ['background', 'blue']]
```
## Migration
### v1
Migrated to TypeScript. Iterator excludes `Comment`. CommonJS requires the `.default` key:
```js
const parse = require('style-to-object').default;
```
## Release
Release and publish are automated by [Release Please](https://github.com/googleapis/release-please).
## Special Thanks
- [inline-style-parser](https://github.com/remarkablemark/inline-style-parser)
- [Contributors](https://github.com/remarkablemark/style-to-object/graphs/contributors)
## License
[MIT](https://github.com/remarkablemark/style-to-object/blob/master/LICENSE)
@@ -0,0 +1,55 @@
# merge-descriptors
> Merge objects using their property descriptors
## Install
```sh
npm install merge-descriptors
```
## Usage
```js
import mergeDescriptors from 'merge-descriptors';
const thing = {
get name() {
return 'John'
}
}
const animal = {};
mergeDescriptors(animal, thing);
console.log(animal.name);
//=> 'John'
```
## API
### merge(destination, source, overwrite?)
Merges "own" properties from a source to a destination object, including non-enumerable and accessor-defined properties. It retains original values and descriptors, ensuring the destination receives a complete and accurate copy of the source's properties.
Returns the modified destination object.
#### destination
Type: `object`
The object to receive properties.
#### source
Type: `object`
The object providing properties.
#### overwrite
Type: `boolean`\
Default: `true`
A boolean to control overwriting of existing properties.
@@ -0,0 +1,3 @@
export * from './omit-from-mapped-key.mjs';
export * from './omit-from-mapped-result.mjs';
export * from './omit.mjs';
@@ -0,0 +1,50 @@
{
"name": "@babel/parser",
"version": "7.28.5",
"description": "A JavaScript parser",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-parser",
"bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A+parser+%28babylon%29%22+is%3Aopen",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"keywords": [
"babel",
"javascript",
"parser",
"tc39",
"ecmascript",
"@babel/parser"
],
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-parser"
},
"main": "./lib/index.js",
"types": "./typings/babel-parser.d.ts",
"files": [
"bin",
"lib",
"typings/babel-parser.d.ts",
"index.cjs"
],
"engines": {
"node": ">=6.0.0"
},
"# dependencies": "This package doesn't actually have runtime dependencies. @babel/types is only needed for type definitions.",
"dependencies": {
"@babel/types": "^7.28.5"
},
"devDependencies": {
"@babel/code-frame": "^7.27.1",
"@babel/helper-check-duplicate-nodes": "^7.27.1",
"@babel/helper-fixtures": "^7.28.0",
"@babel/helper-string-parser": "^7.27.1",
"@babel/helper-validator-identifier": "^7.28.5",
"charcodes": "^0.2.0"
},
"bin": "./bin/babel-parser.js",
"type": "commonjs"
}
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E F A B wC"},B:{"1":"0 1 2 3 4 5 Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I","2":"C L M G N O P"},C:{"1":"0 1 2 3 4 5 xB yB zB 0B 1B 2B 3B UC 4B VC 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R WC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I XC MC YC yC zC","2":"6 7 8 9 xC TC J ZB K D E F A B C L M G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB 0C 1C"},D:{"1":"0 1 2 3 4 5 4B VC 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I XC MC YC","2":"6 7 8 9 J ZB K D E F A B C L M G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B","194":"UC"},E:{"1":"B C L M G aC NC OC 7C 8C 9C bC cC PC AD QC dC eC fC gC hC BD RC iC jC kC lC mC CD SC nC oC pC qC rC sC tC DD ED","2":"J ZB K D E F A 2C ZC 3C 4C 5C 6C"},F:{"1":"0 1 2 3 4 5 sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R WC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z","2":"6 7 8 9 F B C G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB FD GD HD ID NC uC JD OC","194":"rB"},G:{"1":"SD TD UD VD WD XD YD ZD aD bD cD dD bC cC PC eD QC dC eC fC gC hC fD RC iC jC kC lC mC gD SC nC oC pC qC rC sC tC","2":"E ZC KD vC LD MD ND OD PD QD RD"},H:{"2":"hD"},I:{"1":"I","2":"TC J iD jD kD lD vC mD nD"},J:{"2":"D A"},K:{"1":"H","2":"A B C NC uC OC"},L:{"1":"I"},M:{"1":"MC"},N:{"2":"A B"},O:{"1":"PC"},P:{"1":"6 7 8 9 AB BB CB DB EB FB rD sD aC tD uD vD wD xD QC RC SC yD","2":"J oD pD qD"},Q:{"1":"zD"},R:{"1":"0D"},S:{"1":"2D","2":"1D"}},B:7,C:":focus-within CSS pseudo-class",D:true};
@@ -0,0 +1,361 @@
/**
* @file 字体管理对象,处理字体相关的读取、查询、转换
*
* @author mengke01(kekee000@gmail.com)
*/
import bufferTool from '../nodejs/buffer';
import getEmptyttfObject from './getEmptyttfObject';
import TTF from './ttf';
import woff2ttf from './woff2ttf';
import otf2ttfobject from './otf2ttfobject';
import eot2ttf from './eot2ttf';
import svg2ttfobject from './svg2ttfobject';
import TTFReader from './ttfreader';
import TTFWriter from './ttfwriter';
import ttf2eot from './ttf2eot';
import ttf2woff from './ttf2woff';
import ttf2svg from './ttf2svg';
import ttf2symbol from './ttf2symbol';
import ttftowoff2 from './ttftowoff2';
import woff2tottf from './woff2tottf';
import ttf2base64 from './ttf2base64';
import eot2base64 from './eot2base64';
import woff2base64 from './woff2base64';
import svg2base64 from './svg2base64';
import bytes2base64 from './util/bytes2base64';
import woff2tobase64 from './woff2tobase64';
import optimizettf from './util/optimizettf';
// 必须是nodejs环境下的Buffer对象才能触发buffer转换
const SUPPORT_BUFFER =
typeof process === 'object' &&
typeof process.versions === 'object' &&
typeof process.versions.node !== 'undefined' &&
typeof Buffer === 'function';
class Font {
/**
* 字体对象构造函数
*
* @param {ArrayBuffer|Buffer|string|Document} buffer 字体数据
* @param {Object} options 读取参数
*/
constructor(buffer, options = { type: 'ttf' }) {
// 字形对象
if (typeof buffer === 'object' && buffer.glyf) {
this.set(buffer);
}
// buffer
else if (buffer) {
this.read(buffer, options);
}
// 空
else {
this.readEmpty();
}
}
/**
* Create a Font instance
*
* @param {ArrayBuffer|Buffer|string|Document} buffer 字体数据
* @param {Object} options 读取参数
* @return {Font}
*/
static create(buffer, options) {
return new Font(buffer, options);
}
/**
* 设置一个空的 ttfObject 对象
*
* @return {Font}
*/
readEmpty() {
this.data = getEmptyttfObject();
return this;
}
/**
* 读取字体数据
*
* @param {ArrayBuffer|Buffer|string|Document} buffer 字体数据
* @param {Object} options 读取参数
* @param {string} options.type 字体类型
*
* ttf, woff , eot 读取配置
* @param {boolean} options.hinting 是否保留 hinting 信息
* @param {boolean} options.kerning 是否保留 kerning 信息
* @param {boolean} options.compound2simple 复合字形转简单字形
*
* woff 读取配置
* @param {Function} options.inflate 解压相关函数
*
* svg 读取配置
* @param {boolean} options.combinePath 是否合并成单个字形,仅限于普通svg导入
* @return {Font}
*/
read(buffer, options) {
// nodejs buffer
if (SUPPORT_BUFFER) {
if (buffer instanceof Buffer) {
buffer = bufferTool.toArrayBuffer(buffer);
}
}
if (options.type === 'ttf') {
this.data = new TTFReader(options).read(buffer);
} else if (options.type === 'otf') {
this.data = otf2ttfobject(buffer, options);
} else if (options.type === 'eot') {
buffer = eot2ttf(buffer, options);
this.data = new TTFReader(options).read(buffer);
} else if (options.type === 'woff') {
buffer = woff2ttf(buffer, options);
this.data = new TTFReader(options).read(buffer);
} else if (options.type === 'woff2') {
buffer = woff2tottf(buffer, options);
this.data = new TTFReader(options).read(buffer);
} else if (options.type === 'svg') {
this.data = svg2ttfobject(buffer, options);
} else {
throw new Error('not support font type' + options.type);
}
this.type = options.type;
return this;
}
/**
* 写入字体数据
*
* @param {Object} options 写入参数
* @param {string} options.type 字体类型, 默认 ttf
* @param {boolean} options.toBuffer nodejs 环境中返回 Buffer 对象, 默认 true
*
* ttf 字体参数
* @param {boolean} options.hinting 是否保留 hinting 信息
* @param {boolean} options.kerning 是否保留 kerning 信息
* svg,woff 字体参数
* @param {Object} options.metadata 字体相关的信息
*
* woff 字体参数
* @param {Function} options.deflate 压缩相关函数
* @return {Buffer|ArrayBuffer|string}
*/
write(options = {}) {
if (!options.type) {
options.type = this.type;
}
let buffer = null;
if (options.type === 'ttf') {
buffer = new TTFWriter(options).write(this.data);
} else if (options.type === 'eot') {
buffer = new TTFWriter(options).write(this.data);
buffer = ttf2eot(buffer, options);
} else if (options.type === 'woff') {
buffer = new TTFWriter(options).write(this.data);
buffer = ttf2woff(buffer, options);
} else if (options.type === 'woff2') {
buffer = new TTFWriter(options).write(this.data);
buffer = ttftowoff2(buffer, options);
} else if (options.type === 'svg') {
buffer = ttf2svg(this.data, options);
} else if (options.type === 'symbol') {
buffer = ttf2symbol(this.data, options);
} else {
throw new Error('not support font type' + options.type);
}
if (SUPPORT_BUFFER) {
if (false !== options.toBuffer && buffer instanceof ArrayBuffer) {
buffer = bufferTool.toBuffer(buffer);
}
}
return buffer;
}
/**
* 转换成 base64编码
*
* @param {Object} options 写入参数
* @param {string} options.type 字体类型, 默认 ttf
* 其他 options参数, 参考 write
* @see write
*
* @param {ArrayBuffer=} buffer 如果提供了buffer数据则使用 buffer数据, 否则转换现有的 font
* @return {string}
*/
toBase64(options, buffer) {
if (!options.type) {
options.type = this.type;
}
if (buffer) {
if (SUPPORT_BUFFER) {
if (buffer instanceof Buffer) {
buffer = bufferTool.toArrayBuffer(buffer);
}
}
} else {
options.toBuffer = false;
buffer = this.write(options);
}
let base64Str;
if (options.type === 'ttf') {
base64Str = ttf2base64(buffer);
} else if (options.type === 'eot') {
base64Str = eot2base64(buffer);
} else if (options.type === 'woff') {
base64Str = woff2base64(buffer);
} else if (options.type === 'woff2') {
base64Str = woff2tobase64(buffer);
} else if (options.type === 'svg') {
base64Str = svg2base64(buffer);
} else if (options.type === 'symbol') {
base64Str = svg2base64(buffer, 'image/svg+xml');
} else {
throw new Error('not support font type' + options.type);
}
return base64Str;
}
/**
* 设置 font 对象
*
* @param {Object} data font的ttfObject对象
* @return {this}
*/
set(data) {
this.data = data;
return this;
}
/**
* 获取 font 数据
*
* @return {Object} ttfObject 对象
*/
get() {
return this.data;
}
/**
* 对字形数据进行优化
*
* @param {Object} out 输出结果
* @param {boolean|Object} out.result `true` 或者有问题的地方
* @return {Font}
*/
optimize(out) {
const result = optimizettf(this.data);
if (out) {
out.result = result;
}
return this;
}
/**
* 将字体中的复合字形转为简单字形
*
* @return {this}
*/
compound2simple() {
const ttfHelper = this.getHelper();
ttfHelper.compound2simple();
this.data = ttfHelper.get();
return this;
}
/**
* 对字形按照unicode编码排序
*
* @return {this}
*/
sort() {
const ttfHelper = this.getHelper();
ttfHelper.sortGlyf();
this.data = ttfHelper.get();
return this;
}
/**
* 查找相关字形
*
* @param {Object} condition 查询条件
* @param {Array|number} condition.unicode unicode编码列表或者单个unicode编码
* @param {string} condition.name glyf名字,例如`uniE001`, `uniE`
* @param {Function} condition.filter 自定义过滤器
* @example
* condition.filter(glyf) {
* return glyf.name === 'logo';
* }
* @return {Array} glyf字形列表
*/
find(condition) {
const ttfHelper = this.getHelper();
const indexList = ttfHelper.findGlyf(condition);
return indexList.length ? ttfHelper.getGlyf(indexList) : indexList;
}
/**
* 合并 font 到当前的 font
*
* @param {Object} font Font 对象
* @param {Object} options 参数选项
* @param {boolean} options.scale 是否自动缩放
* @param {boolean} options.adjustGlyf 是否调整字形以适应边界
* (和 options.scale 参数互斥)
*
* @return {Font}
*/
merge(font, options) {
const ttfHelper = this.getHelper();
ttfHelper.mergeGlyf(font.get(), options);
this.data = ttfHelper.get();
return this;
}
/**
* 获取 TTF helper 实例
*/
getHelper() {
return new TTF(this.data);
}
}
/**
* base64序列化buffer 数据
*
* @param {ArrayBuffer|Buffer|string} buffer 字体数据
* @return {Font}
*/
Font.toBase64 = function (buffer) {
if (typeof buffer === 'string') {
// node 环境中没有 btoa 函数
if (typeof btoa === 'undefined') {
return Buffer.from(buffer, 'binary').toString('base64');
}
return btoa(buffer);
}
return bytes2base64(buffer);
};
function createFont(buffer, options) {
return new Font(buffer, options);
}
export {Font, createFont};
export default Font;
@@ -0,0 +1,2 @@
export default function extractFormValues<T extends object, K extends Record<string, unknown>>(fieldsState: T, formValues: K): Record<string, unknown>;
//# sourceMappingURL=extractFormValues.d.ts.map
@@ -0,0 +1,394 @@
/**
* @fileoverview Rule to flag non-quoted property names in object literals.
* @author Mathias Bynens <http://mathiasbynens.be/>
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const espree = require("espree");
const astUtils = require("./utils/ast-utils");
const keywords = require("./utils/keywords");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "quote-props",
url: "https://eslint.style/rules/quote-props",
},
},
],
},
type: "suggestion",
docs: {
description: "Require quotes around object literal property names",
recommended: false,
url: "https://eslint.org/docs/latest/rules/quote-props",
},
schema: {
anyOf: [
{
type: "array",
items: [
{
enum: [
"always",
"as-needed",
"consistent",
"consistent-as-needed",
],
},
],
minItems: 0,
maxItems: 1,
},
{
type: "array",
items: [
{
enum: [
"always",
"as-needed",
"consistent",
"consistent-as-needed",
],
},
{
type: "object",
properties: {
keywords: {
type: "boolean",
},
unnecessary: {
type: "boolean",
},
numbers: {
type: "boolean",
},
},
additionalProperties: false,
},
],
minItems: 0,
maxItems: 2,
},
],
},
fixable: "code",
messages: {
requireQuotesDueToReservedWord:
"Properties should be quoted as '{{property}}' is a reserved word.",
inconsistentlyQuotedProperty:
"Inconsistently quoted property '{{key}}' found.",
unnecessarilyQuotedProperty:
"Unnecessarily quoted property '{{property}}' found.",
unquotedReservedProperty:
"Unquoted reserved word '{{property}}' used as key.",
unquotedNumericProperty:
"Unquoted number literal '{{property}}' used as key.",
unquotedPropertyFound: "Unquoted property '{{property}}' found.",
redundantQuoting:
"Properties shouldn't be quoted as all quotes are redundant.",
},
},
create(context) {
const MODE = context.options[0],
KEYWORDS = context.options[1] && context.options[1].keywords,
CHECK_UNNECESSARY =
!context.options[1] || context.options[1].unnecessary !== false,
NUMBERS = context.options[1] && context.options[1].numbers,
sourceCode = context.sourceCode;
/**
* Checks whether a certain string constitutes an ES3 token
* @param {string} tokenStr The string to be checked.
* @returns {boolean} `true` if it is an ES3 token.
*/
function isKeyword(tokenStr) {
return keywords.includes(tokenStr);
}
/**
* Checks if an espree-tokenized key has redundant quotes (i.e. whether quotes are unnecessary)
* @param {string} rawKey The raw key value from the source
* @param {espreeTokens} tokens The espree-tokenized node key
* @param {boolean} [skipNumberLiterals=false] Indicates whether number literals should be checked
* @returns {boolean} Whether or not a key has redundant quotes.
* @private
*/
function areQuotesRedundant(rawKey, tokens, skipNumberLiterals) {
return (
tokens.length === 1 &&
tokens[0].start === 0 &&
tokens[0].end === rawKey.length &&
(["Identifier", "Keyword", "Null", "Boolean"].includes(
tokens[0].type,
) ||
(tokens[0].type === "Numeric" &&
!skipNumberLiterals &&
String(+tokens[0].value) === tokens[0].value))
);
}
/**
* Returns a string representation of a property node with quotes removed
* @param {ASTNode} key Key AST Node, which may or may not be quoted
* @returns {string} A replacement string for this property
*/
function getUnquotedKey(key) {
return key.type === "Identifier" ? key.name : key.value;
}
/**
* Returns a string representation of a property node with quotes added
* @param {ASTNode} key Key AST Node, which may or may not be quoted
* @returns {string} A replacement string for this property
*/
function getQuotedKey(key) {
if (key.type === "Literal" && typeof key.value === "string") {
// If the key is already a string literal, don't replace the quotes with double quotes.
return sourceCode.getText(key);
}
// Otherwise, the key is either an identifier or a number literal.
return `"${key.type === "Identifier" ? key.name : key.value}"`;
}
/**
* Ensures that a property's key is quoted only when necessary
* @param {ASTNode} node Property AST node
* @returns {void}
*/
function checkUnnecessaryQuotes(node) {
const key = node.key;
if (node.method || node.computed || node.shorthand) {
return;
}
if (key.type === "Literal" && typeof key.value === "string") {
let tokens;
try {
tokens = espree.tokenize(key.value);
} catch {
return;
}
if (tokens.length !== 1) {
return;
}
const isKeywordToken = isKeyword(tokens[0].value);
if (isKeywordToken && KEYWORDS) {
return;
}
if (
CHECK_UNNECESSARY &&
areQuotesRedundant(key.value, tokens, NUMBERS)
) {
context.report({
node,
messageId: "unnecessarilyQuotedProperty",
data: { property: key.value },
fix: fixer =>
fixer.replaceText(key, getUnquotedKey(key)),
});
}
} else if (
KEYWORDS &&
key.type === "Identifier" &&
isKeyword(key.name)
) {
context.report({
node,
messageId: "unquotedReservedProperty",
data: { property: key.name },
fix: fixer => fixer.replaceText(key, getQuotedKey(key)),
});
} else if (
NUMBERS &&
key.type === "Literal" &&
astUtils.isNumericLiteral(key)
) {
context.report({
node,
messageId: "unquotedNumericProperty",
data: { property: key.value },
fix: fixer => fixer.replaceText(key, getQuotedKey(key)),
});
}
}
/**
* Ensures that a property's key is quoted
* @param {ASTNode} node Property AST node
* @returns {void}
*/
function checkOmittedQuotes(node) {
const key = node.key;
if (
!node.method &&
!node.computed &&
!node.shorthand &&
!(key.type === "Literal" && typeof key.value === "string")
) {
context.report({
node,
messageId: "unquotedPropertyFound",
data: { property: key.name || key.value },
fix: fixer => fixer.replaceText(key, getQuotedKey(key)),
});
}
}
/**
* Ensures that an object's keys are consistently quoted, optionally checks for redundancy of quotes
* @param {ASTNode} node Property AST node
* @param {boolean} checkQuotesRedundancy Whether to check quotes' redundancy
* @returns {void}
*/
function checkConsistency(node, checkQuotesRedundancy) {
const quotedProps = [],
unquotedProps = [];
let keywordKeyName = null,
necessaryQuotes = false;
node.properties.forEach(property => {
const key = property.key;
if (
!key ||
property.method ||
property.computed ||
property.shorthand
) {
return;
}
if (key.type === "Literal" && typeof key.value === "string") {
quotedProps.push(property);
if (checkQuotesRedundancy) {
let tokens;
try {
tokens = espree.tokenize(key.value);
} catch {
necessaryQuotes = true;
return;
}
necessaryQuotes =
necessaryQuotes ||
!areQuotesRedundant(key.value, tokens) ||
(KEYWORDS && isKeyword(tokens[0].value));
}
} else if (
KEYWORDS &&
checkQuotesRedundancy &&
key.type === "Identifier" &&
isKeyword(key.name)
) {
unquotedProps.push(property);
necessaryQuotes = true;
keywordKeyName = key.name;
} else {
unquotedProps.push(property);
}
});
if (
checkQuotesRedundancy &&
quotedProps.length &&
!necessaryQuotes
) {
quotedProps.forEach(property => {
context.report({
node: property,
messageId: "redundantQuoting",
fix: fixer =>
fixer.replaceText(
property.key,
getUnquotedKey(property.key),
),
});
});
} else if (unquotedProps.length && keywordKeyName) {
unquotedProps.forEach(property => {
context.report({
node: property,
messageId: "requireQuotesDueToReservedWord",
data: { property: keywordKeyName },
fix: fixer =>
fixer.replaceText(
property.key,
getQuotedKey(property.key),
),
});
});
} else if (quotedProps.length && unquotedProps.length) {
unquotedProps.forEach(property => {
context.report({
node: property,
messageId: "inconsistentlyQuotedProperty",
data: { key: property.key.name || property.key.value },
fix: fixer =>
fixer.replaceText(
property.key,
getQuotedKey(property.key),
),
});
});
}
}
return {
Property(node) {
if (MODE === "always" || !MODE) {
checkOmittedQuotes(node);
}
if (MODE === "as-needed") {
checkUnnecessaryQuotes(node);
}
},
ObjectExpression(node) {
if (MODE === "consistent") {
checkConsistency(node, false);
}
if (MODE === "consistent-as-needed") {
checkConsistency(node, true);
}
},
};
},
};
@@ -0,0 +1,17 @@
import {parser} from "../dist/index.js"
import {fileTests} from "@lezer/generator/dist/test"
import * as fs from "fs"
import * as path from "path"
import {fileURLToPath} from "url"
let caseDir = path.dirname(fileURLToPath(import.meta.url))
for (let file of fs.readdirSync(caseDir)) {
if (!/\.txt$/.test(file)) continue
let name = /^[^\.]*/.exec(file)[0]
describe(name, () => {
for (let {name, run} of fileTests(fs.readFileSync(path.join(caseDir, file), "utf8"), file))
it(name, () => run(parser))
})
}
@@ -0,0 +1,578 @@
/**
* Clusters of Node.js processes can be used to run multiple instances of Node.js
* that can distribute workloads among their application threads. When process isolation
* is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v22.x/api/worker_threads.html)
* module instead, which allows running multiple application threads within a single Node.js instance.
*
* The cluster module allows easy creation of child processes that all share
* server ports.
*
* ```js
* import cluster from 'node:cluster';
* import http from 'node:http';
* import { availableParallelism } from 'node:os';
* import process from 'node:process';
*
* const numCPUs = availableParallelism();
*
* if (cluster.isPrimary) {
* console.log(`Primary ${process.pid} is running`);
*
* // Fork workers.
* for (let i = 0; i < numCPUs; i++) {
* cluster.fork();
* }
*
* cluster.on('exit', (worker, code, signal) => {
* console.log(`worker ${worker.process.pid} died`);
* });
* } else {
* // Workers can share any TCP connection
* // In this case it is an HTTP server
* http.createServer((req, res) => {
* res.writeHead(200);
* res.end('hello world\n');
* }).listen(8000);
*
* console.log(`Worker ${process.pid} started`);
* }
* ```
*
* Running Node.js will now share port 8000 between the workers:
*
* ```console
* $ node server.js
* Primary 3596 is running
* Worker 4324 started
* Worker 4520 started
* Worker 6056 started
* Worker 5644 started
* ```
*
* On Windows, it is not yet possible to set up a named pipe server in a worker.
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/cluster.js)
*/
declare module "cluster" {
import * as child from "node:child_process";
import EventEmitter = require("node:events");
import * as net from "node:net";
type SerializationType = "json" | "advanced";
export interface ClusterSettings {
/**
* List of string arguments passed to the Node.js executable.
* @default process.execArgv
*/
execArgv?: string[] | undefined;
/**
* File path to worker file.
* @default process.argv[1]
*/
exec?: string | undefined;
/**
* String arguments passed to worker.
* @default process.argv.slice(2)
*/
args?: readonly string[] | undefined;
/**
* Whether or not to send output to parent's stdio.
* @default false
*/
silent?: boolean | undefined;
/**
* Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must
* contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processspawncommand-args-options)'s
* [`stdio`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#optionsstdio).
*/
stdio?: any[] | undefined;
/**
* Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).)
*/
uid?: number | undefined;
/**
* Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).)
*/
gid?: number | undefined;
/**
* Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number.
* By default each worker gets its own port, incremented from the primary's `process.debugPort`.
*/
inspectPort?: number | (() => number) | undefined;
/**
* Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`.
* See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#advanced-serialization) for more details.
* @default false
*/
serialization?: SerializationType | undefined;
/**
* Current working directory of the worker process.
* @default undefined (inherits from parent process)
*/
cwd?: string | undefined;
/**
* Hide the forked processes console window that would normally be created on Windows systems.
* @default false
*/
windowsHide?: boolean | undefined;
}
export interface Address {
address: string;
port: number;
/**
* The `addressType` is one of:
*
* * `4` (TCPv4)
* * `6` (TCPv6)
* * `-1` (Unix domain socket)
* * `'udp4'` or `'udp6'` (UDPv4 or UDPv6)
*/
addressType: 4 | 6 | -1 | "udp4" | "udp6";
}
/**
* A `Worker` object contains all public information and method about a worker.
* In the primary it can be obtained using `cluster.workers`. In a worker
* it can be obtained using `cluster.worker`.
* @since v0.7.0
*/
export class Worker extends EventEmitter {
/**
* Each new worker is given its own unique id, this id is stored in the `id`.
*
* While a worker is alive, this is the key that indexes it in `cluster.workers`.
* @since v0.8.0
*/
id: number;
/**
* All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object
* from this function is stored as `.process`. In a worker, the global `process` is stored.
*
* See: [Child Process module](https://nodejs.org/docs/latest-v22.x/api/child_process.html#child_processforkmodulepath-args-options).
*
* Workers will call `process.exit(0)` if the `'disconnect'` event occurs
* on `process` and `.exitedAfterDisconnect` is not `true`. This protects against
* accidental disconnection.
* @since v0.7.0
*/
process: child.ChildProcess;
/**
* Send a message to a worker or primary, optionally with a handle.
*
* In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v22.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback).
*
* In a worker, this sends a message to the primary. It is identical to `process.send()`.
*
* This example will echo back all messages from the primary:
*
* ```js
* if (cluster.isPrimary) {
* const worker = cluster.fork();
* worker.send('hi there');
*
* } else if (cluster.isWorker) {
* process.on('message', (msg) => {
* process.send(msg);
* });
* }
* ```
* @since v0.7.0
* @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles.
*/
send(message: child.Serializable, callback?: (error: Error | null) => void): boolean;
send(
message: child.Serializable,
sendHandle: child.SendHandle,
callback?: (error: Error | null) => void,
): boolean;
send(
message: child.Serializable,
sendHandle: child.SendHandle,
options?: child.MessageOptions,
callback?: (error: Error | null) => void,
): boolean;
/**
* This function will kill the worker. In the primary worker, it does this by
* disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`.
*
* The `kill()` function kills the worker process without waiting for a graceful
* disconnect, it has the same behavior as `worker.process.kill()`.
*
* This method is aliased as `worker.destroy()` for backwards compatibility.
*
* In a worker, `process.kill()` exists, but it is not this function;
* it is [`kill()`](https://nodejs.org/docs/latest-v22.x/api/process.html#processkillpid-signal).
* @since v0.9.12
* @param [signal='SIGTERM'] Name of the kill signal to send to the worker process.
*/
kill(signal?: string): void;
destroy(signal?: string): void;
/**
* In a worker, this function will close all servers, wait for the `'close'` event
* on those servers, and then disconnect the IPC channel.
*
* In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself.
*
* Causes `.exitedAfterDisconnect` to be set.
*
* After a server is closed, it will no longer accept new connections,
* but connections may be accepted by any other listening worker. Existing
* connections will be allowed to close as usual. When no more connections exist,
* see `server.close()`, the IPC channel to the worker will close allowing it
* to die gracefully.
*
* The above applies _only_ to server connections, client connections are not
* automatically closed by workers, and disconnect does not wait for them to close
* before exiting.
*
* In a worker, `process.disconnect` exists, but it is not this function;
* it is `disconnect()`.
*
* Because long living server connections may block workers from disconnecting, it
* may be useful to send a message, so application specific actions may be taken to
* close them. It also may be useful to implement a timeout, killing a worker if
* the `'disconnect'` event has not been emitted after some time.
*
* ```js
* import net from 'node:net';
*
* if (cluster.isPrimary) {
* const worker = cluster.fork();
* let timeout;
*
* worker.on('listening', (address) => {
* worker.send('shutdown');
* worker.disconnect();
* timeout = setTimeout(() => {
* worker.kill();
* }, 2000);
* });
*
* worker.on('disconnect', () => {
* clearTimeout(timeout);
* });
*
* } else if (cluster.isWorker) {
* const server = net.createServer((socket) => {
* // Connections never end
* });
*
* server.listen(8000);
*
* process.on('message', (msg) => {
* if (msg === 'shutdown') {
* // Initiate graceful close of any connections to server
* }
* });
* }
* ```
* @since v0.7.7
* @return A reference to `worker`.
*/
disconnect(): this;
/**
* This function returns `true` if the worker is connected to its primary via its
* IPC channel, `false` otherwise. A worker is connected to its primary after it
* has been created. It is disconnected after the `'disconnect'` event is emitted.
* @since v0.11.14
*/
isConnected(): boolean;
/**
* This function returns `true` if the worker's process has terminated (either
* because of exiting or being signaled). Otherwise, it returns `false`.
*
* ```js
* import cluster from 'node:cluster';
* import http from 'node:http';
* import { availableParallelism } from 'node:os';
* import process from 'node:process';
*
* const numCPUs = availableParallelism();
*
* if (cluster.isPrimary) {
* console.log(`Primary ${process.pid} is running`);
*
* // Fork workers.
* for (let i = 0; i < numCPUs; i++) {
* cluster.fork();
* }
*
* cluster.on('fork', (worker) => {
* console.log('worker is dead:', worker.isDead());
* });
*
* cluster.on('exit', (worker, code, signal) => {
* console.log('worker is dead:', worker.isDead());
* });
* } else {
* // Workers can share any TCP connection. In this case, it is an HTTP server.
* http.createServer((req, res) => {
* res.writeHead(200);
* res.end(`Current process\n ${process.pid}`);
* process.kill(process.pid);
* }).listen(8000);
* }
* ```
* @since v0.11.14
*/
isDead(): boolean;
/**
* This property is `true` if the worker exited due to `.disconnect()`.
* If the worker exited any other way, it is `false`. If the
* worker has not exited, it is `undefined`.
*
* The boolean `worker.exitedAfterDisconnect` allows distinguishing between
* voluntary and accidental exit, the primary may choose not to respawn a worker
* based on this value.
*
* ```js
* cluster.on('exit', (worker, code, signal) => {
* if (worker.exitedAfterDisconnect === true) {
* console.log('Oh, it was just voluntary – no need to worry');
* }
* });
*
* // kill worker
* worker.kill();
* ```
* @since v6.0.0
*/
exitedAfterDisconnect: boolean;
/**
* events.EventEmitter
* 1. disconnect
* 2. error
* 3. exit
* 4. listening
* 5. message
* 6. online
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "disconnect", listener: () => void): this;
addListener(event: "error", listener: (error: Error) => void): this;
addListener(event: "exit", listener: (code: number, signal: string) => void): this;
addListener(event: "listening", listener: (address: Address) => void): this;
addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: "online", listener: () => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "disconnect"): boolean;
emit(event: "error", error: Error): boolean;
emit(event: "exit", code: number, signal: string): boolean;
emit(event: "listening", address: Address): boolean;
emit(event: "message", message: any, handle: net.Socket | net.Server): boolean;
emit(event: "online"): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "disconnect", listener: () => void): this;
on(event: "error", listener: (error: Error) => void): this;
on(event: "exit", listener: (code: number, signal: string) => void): this;
on(event: "listening", listener: (address: Address) => void): this;
on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: "online", listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "disconnect", listener: () => void): this;
once(event: "error", listener: (error: Error) => void): this;
once(event: "exit", listener: (code: number, signal: string) => void): this;
once(event: "listening", listener: (address: Address) => void): this;
once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: "online", listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "disconnect", listener: () => void): this;
prependListener(event: "error", listener: (error: Error) => void): this;
prependListener(event: "exit", listener: (code: number, signal: string) => void): this;
prependListener(event: "listening", listener: (address: Address) => void): this;
prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependListener(event: "online", listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "disconnect", listener: () => void): this;
prependOnceListener(event: "error", listener: (error: Error) => void): this;
prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this;
prependOnceListener(event: "listening", listener: (address: Address) => void): this;
prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(event: "online", listener: () => void): this;
}
export interface Cluster extends EventEmitter {
disconnect(callback?: () => void): void;
/**
* Spawn a new worker process.
*
* This can only be called from the primary process.
* @param env Key/value pairs to add to worker process environment.
* @since v0.6.0
*/
fork(env?: any): Worker;
/** @deprecated since v16.0.0 - use isPrimary. */
readonly isMaster: boolean;
/**
* True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID`
* is undefined, then `isPrimary` is `true`.
* @since v16.0.0
*/
readonly isPrimary: boolean;
/**
* True if the process is not a primary (it is the negation of `cluster.isPrimary`).
* @since v0.6.0
*/
readonly isWorker: boolean;
/**
* The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a
* global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings)
* is called, whichever comes first.
*
* `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute
* IOCP handles without incurring a large performance hit.
*
* `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`.
* @since v0.11.2
*/
schedulingPolicy: number;
/**
* After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings)
* (or [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv)) this settings object will contain
* the settings, including the default values.
*
* This object is not intended to be changed or set manually.
* @since v0.7.1
*/
readonly settings: ClusterSettings;
/** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clustersetupprimarysettings) instead. */
setupMaster(settings?: ClusterSettings): void;
/**
* `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`.
*
* Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv)
* and have no effect on workers that are already running.
*
* The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to
* [`.fork()`](https://nodejs.org/docs/latest-v22.x/api/cluster.html#clusterforkenv).
*
* The defaults above apply to the first call only; the defaults for later calls are the current values at the time of
* `cluster.setupPrimary()` is called.
*
* ```js
* import cluster from 'node:cluster';
*
* cluster.setupPrimary({
* exec: 'worker.js',
* args: ['--use', 'https'],
* silent: true,
* });
* cluster.fork(); // https worker
* cluster.setupPrimary({
* exec: 'worker.js',
* args: ['--use', 'http'],
* });
* cluster.fork(); // http worker
* ```
*
* This can only be called from the primary process.
* @since v16.0.0
*/
setupPrimary(settings?: ClusterSettings): void;
/**
* A reference to the current worker object. Not available in the primary process.
*
* ```js
* import cluster from 'node:cluster';
*
* if (cluster.isPrimary) {
* console.log('I am primary');
* cluster.fork();
* cluster.fork();
* } else if (cluster.isWorker) {
* console.log(`I am worker #${cluster.worker.id}`);
* }
* ```
* @since v0.7.0
*/
readonly worker?: Worker;
/**
* A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process.
*
* A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it
* is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted.
*
* ```js
* import cluster from 'node:cluster';
*
* for (const worker of Object.values(cluster.workers)) {
* worker.send('big announcement to all workers');
* }
* ```
* @since v0.7.0
*/
readonly workers?: NodeJS.Dict<Worker>;
readonly SCHED_NONE: number;
readonly SCHED_RR: number;
/**
* events.EventEmitter
* 1. disconnect
* 2. exit
* 3. fork
* 4. listening
* 5. message
* 6. online
* 7. setup
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "disconnect", listener: (worker: Worker) => void): this;
addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
addListener(event: "fork", listener: (worker: Worker) => void): this;
addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
addListener(
event: "message",
listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void,
): this; // the handle is a net.Socket or net.Server object, or undefined.
addListener(event: "online", listener: (worker: Worker) => void): this;
addListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "disconnect", worker: Worker): boolean;
emit(event: "exit", worker: Worker, code: number, signal: string): boolean;
emit(event: "fork", worker: Worker): boolean;
emit(event: "listening", worker: Worker, address: Address): boolean;
emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
emit(event: "online", worker: Worker): boolean;
emit(event: "setup", settings: ClusterSettings): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "disconnect", listener: (worker: Worker) => void): this;
on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
on(event: "fork", listener: (worker: Worker) => void): this;
on(event: "listening", listener: (worker: Worker, address: Address) => void): this;
on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
on(event: "online", listener: (worker: Worker) => void): this;
on(event: "setup", listener: (settings: ClusterSettings) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "disconnect", listener: (worker: Worker) => void): this;
once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
once(event: "fork", listener: (worker: Worker) => void): this;
once(event: "listening", listener: (worker: Worker, address: Address) => void): this;
once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
once(event: "online", listener: (worker: Worker) => void): this;
once(event: "setup", listener: (settings: ClusterSettings) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "disconnect", listener: (worker: Worker) => void): this;
prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
prependListener(event: "fork", listener: (worker: Worker) => void): this;
prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
prependListener(
event: "message",
listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void,
): this;
prependListener(event: "online", listener: (worker: Worker) => void): this;
prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this;
prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
prependOnceListener(event: "fork", listener: (worker: Worker) => void): this;
prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
// the handle is a net.Socket or net.Server object, or undefined.
prependOnceListener(
event: "message",
listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void,
): this;
prependOnceListener(event: "online", listener: (worker: Worker) => void): this;
prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
}
const cluster: Cluster;
export default cluster;
}
declare module "node:cluster" {
export * from "cluster";
export { default as default } from "cluster";
}
@@ -0,0 +1,52 @@
/**
* @author Toru Nagashima
* See LICENSE file in root directory for full license.
*/
"use strict"
const getAllowModules = require("./get-allow-modules")
const getPackageJson = require("./get-package-json")
/**
* Checks whether or not each requirement target is published via package.json.
*
* It reads package.json and checks the target exists in `dependencies`.
*
* @param {RuleContext} context - A context to report.
* @param {string} filePath - The current file path.
* @param {ImportTarget[]} targets - A list of target information to check.
* @returns {void}
*/
module.exports = function checkForExtraneous(context, filePath, targets) {
const packageInfo = getPackageJson(filePath)
if (!packageInfo) {
return
}
const allowed = new Set(getAllowModules(context))
const dependencies = new Set(
[].concat(
Object.keys(packageInfo.dependencies || {}),
Object.keys(packageInfo.devDependencies || {}),
Object.keys(packageInfo.peerDependencies || {}),
Object.keys(packageInfo.optionalDependencies || {})
)
)
for (const target of targets) {
const extraneous =
target.moduleName != null &&
target.filePath != null &&
!dependencies.has(target.moduleName) &&
!allowed.has(target.moduleName)
if (extraneous) {
context.report({
node: target.node,
loc: target.node.loc,
message: '"{{moduleName}}" is extraneous.',
data: target,
})
}
}
}
@@ -0,0 +1 @@
{"mappings":";;AAAA;;;;;;;;;;CAUC;AAcM,MAAM;IAIX,MAAM,KAAiC,EAAE,OAAiB,EAAqB;QAC7E,IAAI,CAAC,OAAO,GAAG;QACf,OAAO,+BAAS,IAAM,IAAI,CAAC,iBAAiB,CAAC;IAC/C;IAEA,CAAS,kBAAkB,KAAiC,EAAsB;QAChF,IAAI,YAAC,QAAQ,SAAE,KAAK,EAAC,GAAG;QAExB,IAAI,CAAA,GAAA,YAAI,EAAE,cAAc,CAAmC,aAAa,SAAS,IAAI,KAAK,CAAA,GAAA,YAAI,EAAE,QAAQ,EACtG,OAAO,IAAI,CAAC,iBAAiB,CAAC;YAC5B,UAAU,SAAS,KAAK,CAAC,QAAQ;mBACjC;QACF;aACK,IAAI,OAAO,aAAa,YAAY;YACzC,IAAI,CAAC,OACH,MAAM,IAAI,MAAM;YAGlB,IAAI,QAAQ;YACZ,KAAK,IAAI,QAAQ,MAAO;gBACtB,OAAO,IAAI,CAAC,WAAW,CAAC;oBACtB,OAAO;2BACP;gBACF,GAAG;oBAAC,UAAU;gBAAQ;gBACtB;YACF;QACF,OAAO;YACL,IAAI,QAAgC,EAAE;YACtC,CAAA,GAAA,YAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAA;gBAC/B,IAAI,OACF,MAAM,IAAI,CAAC;YAEf;YAEA,IAAI,QAAQ;YACZ,KAAK,IAAI,QAAQ,MAAO;gBACtB,IAAI,QAAQ,IAAI,CAAC,WAAW,CAAC;oBAC3B,SAAS;oBACT,OAAO;gBACT,GAAG,CAAC;gBAEJ,KAAK,IAAI,QAAQ,MAAO;oBACtB;oBACA,MAAM;gBACR;YACF;QACF;IACF;IAEQ,OAAO,IAAuC,EAAE,WAA2B,EAAE,KAA6B,EAAE,SAAsB,EAAO;QAC/I,IAAI,KAAK,GAAG,IAAI,MACd,OAAO,KAAK,GAAG;QAGjB,IAAI,YAAY,IAAI,KAAK,UAAU,YAAY,GAAG,IAAI,MACpD,OAAO,GAAG,YAAY,YAAY,GAAG,EAAE;QAGzC,IAAI,IAAI,YAAY,KAAK;QACzB,IAAI,KAAK,MAAM;gBACH;YAAV,IAAI,MAAM,CAAA,SAAA,EAAE,GAAG,cAAL,oBAAA,SAAS,EAAE,EAAE;YACvB,IAAI,OAAO,MACT,MAAM,IAAI,MAAM;YAGlB,OAAO;QACT;QAEA,OAAO,YAAY,GAAG,UAAU,CAAC,EAAE,YAAY,KAAK,EAAE,GAAG,CAAC,EAAE,EAAE,YAAY,KAAK,EAAE;IACnF;IAEQ,cAAc,KAA6B,EAAE,WAA2B,EAAE;QAChF,OAAO;YACL,UAAU,YAAY,QAAQ,IAAI,MAAM,QAAQ;QAClD;IACF;IAEA,CAAS,YAAY,WAA6C,EAAE,KAA6B,EAAE,SAAsB,EAAE,UAAoB,EAAsB;QACnK,IAAI,CAAA,GAAA,YAAI,EAAE,cAAc,CAAmC,YAAY,OAAO,KAAK,YAAY,OAAO,CAAC,IAAI,KAAK,CAAA,GAAA,YAAI,EAAE,QAAQ,EAAE;YAC9H,IAAI,WAAmC,EAAE;YAEzC,CAAA,GAAA,YAAI,EAAE,QAAQ,CAAC,OAAO,CAAC,YAAY,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAA;gBACzD,SAAS,IAAI,CAAC;YAChB;gBAEY;YAAZ,IAAI,QAAQ,CAAA,qBAAA,YAAY,KAAK,cAAjB,gCAAA,qBAAqB;YAEjC,KAAK,MAAM,SAAS,SAClB,OAAO,IAAI,CAAC,WAAW,CAAC;gBACtB,SAAS;gBACT,OAAO;YACT,GAAG,OAAO,WAAW;YAGvB;QACF;QAEA,qGAAqG;QACrG,6CAA6C;QAC7C,IAAI,UAAU,YAAY,OAAO;QACjC,IAAI,CAAC,WAAW,YAAY,KAAK,IAAI,SAAS,MAAM,QAAQ,EAAE;YAC5D,IAAI,SAAS,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,KAAK;YAC7C,IAAI,UAAW,CAAA,CAAC,OAAO,gBAAgB,IAAI,CAAC,OAAO,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAA,GAAI;gBAClF,OAAO,KAAK,GAAG,YAAY,KAAK;gBAChC,OAAO,SAAS,GAAG,aAAa,WAAW,GAAG,GAAG;gBACjD,MAAM;gBACN;YACF;YAEA,UAAU,MAAM,QAAQ,CAAC,YAAY,KAAK;QAC5C;QAEA,wGAAwG;QACxG,0FAA0F;QAC1F,IAAI,CAAA,GAAA,YAAI,EAAE,cAAc,CAAC,UAAU;YACjC,IAAI,OAAO,QAAQ,IAAI;YACvB,IAAI,OAAO,SAAS,cAAc,OAAO,KAAK,iBAAiB,KAAK,YAAY;gBAC9E,IAAI,OAAO,QAAQ,IAAI;gBACvB,MAAM,IAAI,MAAM,CAAC,iBAAiB,EAAE,KAAK,gBAAgB,CAAC;YAC5D;YAEA,IAAI,aAAa,KAAK,iBAAiB,CAAC,QAAQ,KAAK,EAAE,IAAI,CAAC,OAAO;gBACvD;YAAZ,IAAI,QAAQ,CAAA,sBAAA,YAAY,KAAK,cAAjB,iCAAA,sBAAqB;YACjC,IAAI,SAAS,WAAW,IAAI;YAC5B,MAAO,CAAC,OAAO,IAAI,IAAI,OAAO,KAAK,CAAE;gBACnC,IAAI,YAAY,OAAO,KAAK;gBAE5B,YAAY,KAAK,GAAG;oBAEN;gBAAd,IAAI,UAAU,CAAA,iBAAA,UAAU,GAAG,cAAb,4BAAA,iBAAiB;gBAC/B,IAAI,WAAW,MACb,UAAU,UAAU,OAAO,GAAG,OAAO,IAAI,CAAC,MAAM,CAAC,SAA8C,aAAa,OAAO;gBAGrH,IAAI,QAAQ,IAAI,CAAC,WAAW,CAAC;oBAC3B,GAAG,SAAS;oBACZ,KAAK;2BACL;oBACA,SAAS,8BAAQ,YAAY,OAAO,EAAE,UAAU,OAAO;gBACzD,GAAG,IAAI,CAAC,aAAa,CAAC,OAAO,YAAY,YAAY,GAAG,YAAY,QAAQ,GAAG,EAAE,GAAG,QAAQ,GAAG,EAAE;gBAEjG,IAAI,WAAW;uBAAI;iBAAM;gBACzB,KAAK,IAAI,QAAQ,SAAU;wBAEZ,kBAAA;oBADb,oCAAoC;oBACpC,KAAK,KAAK,GAAG,CAAA,OAAA,CAAA,mBAAA,UAAU,KAAK,cAAf,8BAAA,mBAAmB,YAAY,KAAK,cAApC,kBAAA,OAAwC;oBACrD,IAAI,KAAK,KAAK,EACZ,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,KAAK,EAAE;wBAMmD;oBAHhF,6FAA6F;oBAC7F,0EAA0E;oBAC1E,IAAI,YAAY,IAAI,IAAI,KAAK,IAAI,KAAK,YAAY,IAAI,EACpD,MAAM,IAAI,MAAM,CAAC,kBAAkB,EAAE,iCAAW,KAAK,IAAI,EAAE,MAAM,EAAE,iCAAW,CAAA,mBAAA,uBAAA,iCAAA,WAAY,IAAI,cAAhB,8BAAA,mBAAoB,uBAAuB,SAAS,EAAE,iCAAW,YAAY,IAAI,EAAE,eAAe,CAAC;oBAGnL;oBACA,MAAM;gBACR;gBAEA,SAAS,WAAW,IAAI,CAAC;YAC3B;YAEA;QACF;QAEA,0BAA0B;QAC1B,IAAI,YAAY,GAAG,IAAI,QAAQ,YAAY,IAAI,IAAI,MACjD;QAGF,mBAAmB;QACnB,IAAI,UAAU,IAAI;YAMT,oBAII;QATb,IAAI,OAAgB;YAClB,MAAM,YAAY,IAAI;YACtB,OAAO,YAAY,KAAK;YACxB,KAAK,YAAY,GAAG;YACpB,WAAW,aAAa,WAAW,GAAG,GAAG;YACzC,OAAO,CAAA,qBAAA,YAAY,KAAK,cAAjB,gCAAA,qBAAqB;YAC5B,OAAO,aAAa,WAAW,KAAK,GAAG,IAAI;YAC3C,OAAO,YAAY,KAAK;YACxB,UAAU,YAAY,QAAQ;YAC9B,WAAW,CAAA,yBAAA,YAAY,SAAS,cAArB,oCAAA,yBAAyB;YACpC,cAAc,WAAW,CAAC,aAAa;YACvC,SAAS,YAAY,OAAO;YAC5B,kBAAkB,YAAY,gBAAgB;YAC9C,eAAe,YAAY,aAAa,IAAI;YAC5C,YAAY,+BAAS;gBACnB,IAAI,CAAC,YAAY,aAAa,IAAI,CAAC,YAAY,UAAU,EACvD;gBAGF,IAAI,QAAQ;gBACZ,KAAK,IAAI,SAAS,YAAY,UAAU,GAAI;oBAC1C,4EAA4E;oBAC5E,IAAI,MAAM,GAAG,IAAI,MACf,qFAAqF;oBACrF,6FAA6F;oBAC7F,sGAAsG;oBACtG,kCAAkC;oBAClC,MAAM,GAAG,GAAG,GAAG,KAAK,GAAG,GAAG,MAAM,GAAG,EAAE;oBAGvC,IAAI,QAAQ,QAAQ,WAAW,CAAC;wBAAC,GAAG,KAAK;+BAAE;oBAAK,GAAG,QAAQ,aAAa,CAAC,OAAO,QAAQ,KAAK,GAAG,EAAE;oBAClG,KAAK,IAAI,QAAQ,MAAO;wBACtB;wBACA,MAAM;oBACR;gBACF;YACF;QACF;QAEA,MAAM;IACR;;aAtNQ,QAA6B,IAAI;;AAuN3C;AAEA,4EAA4E;AAC5E,SAAS,+BAAY,QAAyC;IAC5D,IAAI,QAAwB,EAAE;IAC9B,IAAI,WAA6C;IACjD,OAAO;QACL,CAAC,CAAC,OAAO,QAAQ,CAAC;YAChB,KAAK,IAAI,QAAQ,MACf,MAAM;YAGR,IAAI,CAAC,UACH,WAAW;YAGb,KAAK,IAAI,QAAQ,SAAU;gBACzB,MAAM,IAAI,CAAC;gBACX,MAAM;YACR;QACF;IACF;AACF;AAGA,SAAS,8BAAQ,KAAqB,EAAE,KAAqB;IAC3D,IAAI,SAAS,OACX,OAAO,CAAC,UAAY,MAAM,MAAMLine truncated
@@ -0,0 +1,969 @@
import * as _reduxjs_toolkit_query from '@reduxjs/toolkit/query';
import { QueryDefinition, TSHelpersId, TSHelpersOverride, QuerySubState, ResultTypeFrom, QueryStatus, QueryArgFrom, SkipToken, SubscriptionOptions, TSHelpersNoInfer, QueryActionCreatorResult, MutationDefinition, MutationResultSelectorResult, MutationActionCreatorResult, InfiniteQueryDefinition, InfiniteQuerySubState, PageParamFrom, InfiniteQueryArgFrom, InfiniteQueryActionCreatorResult, BaseQueryFn, EndpointDefinitions, DefinitionType, QueryKeys, PrefetchOptions, Module, Api, setupListeners } from '@reduxjs/toolkit/query';
export * from '@reduxjs/toolkit/query';
import * as react_redux from 'react-redux';
import { ReactReduxContextValue } from 'react-redux';
import { createSelector } from 'reselect';
import * as React from 'react';
import { Context } from 'react';
type InfiniteData<DataType, PageParam> = {
pages: Array<DataType>;
pageParams: Array<PageParam>;
};
type InfiniteQueryDirection = 'forward' | 'backward';
export declare const UNINITIALIZED_VALUE: unique symbol;
type UninitializedValue = typeof UNINITIALIZED_VALUE;
type QueryHooks<Definition extends QueryDefinition<any, any, any, any, any>> = {
useQuery: UseQuery<Definition>;
useLazyQuery: UseLazyQuery<Definition>;
useQuerySubscription: UseQuerySubscription<Definition>;
useLazyQuerySubscription: UseLazyQuerySubscription<Definition>;
useQueryState: UseQueryState<Definition>;
};
type InfiniteQueryHooks<Definition extends InfiniteQueryDefinition<any, any, any, any, any>> = {
useInfiniteQuery: UseInfiniteQuery<Definition>;
useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>;
useInfiniteQueryState: UseInfiniteQueryState<Definition>;
};
type MutationHooks<Definition extends MutationDefinition<any, any, any, any, any>> = {
useMutation: UseMutation<Definition>;
};
/**
* A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
*
* This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>) => UseQueryHookResult<D, R>;
type TypedUseQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseQueryHookResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>;
/**
* Helper type to manually type the result
* of the `useQuery` hook in userland code.
*/
type TypedUseQueryHookResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> & TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>;
type UseQuerySubscriptionOptions = SubscriptionOptions & {
/**
* Prevents a query from automatically running.
*
* @remarks
* When `skip` is true (or `skipToken` is passed in as `arg`):
*
* - **If the query has cached data:**
* * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```tsx
* // codeblock-meta no-transpile title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
* - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
* - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
* - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*/
refetchOnMountOrArgChange?: boolean | number;
};
/**
* A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
*/
type UseQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (arg: QueryArgFrom<D> | SkipToken, options?: UseQuerySubscriptionOptions) => UseQuerySubscriptionResult<D>;
type TypedUseQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseQuerySubscriptionResult<D extends QueryDefinition<any, any, any, any>> = Pick<QueryActionCreatorResult<D>, 'refetch'>;
/**
* Helper type to manually type the result
* of the `useQuerySubscription` hook in userland code.
*/
type TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQuerySubscriptionResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseLazyQueryLastPromiseInfo<D extends QueryDefinition<any, any, any, any>> = {
lastArg: QueryArgFrom<D>;
};
/**
* A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.
*
* This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).
*
* #### Features
*
* - Manual control over firing a request to retrieve data
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
*
* #### Note
*
* When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists.
*/
type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>) => [
LazyQueryTrigger<D>,
UseLazyQueryStateResult<D, R>,
UseLazyQueryLastPromiseInfo<D>
];
type TypedUseLazyQuery<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type UseLazyQueryStateResult<D extends QueryDefinition<any, any, any, any>, R = UseQueryStateDefaultResult<D>> = UseQueryStateResult<D, R> & {
/**
* Resets the hook state to its initial `uninitialized` state.
* This will also remove the last result from the cache.
*/
reset: () => void;
};
/**
* Helper type to manually type the result
* of the `useLazyQuery` hook in userland code.
*/
type TypedUseLazyQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseLazyQueryStateResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {
/**
* Triggers a lazy query.
*
* By default, this will start a new request even if there is already a value in the cache.
* If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
*
* @remarks
* If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await getUserById(1).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>, preferCacheValue?: boolean): QueryActionCreatorResult<D>;
};
type TypedLazyQueryTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = LazyQueryTrigger<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
/**
* A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).
*
* #### Features
*
* - Manual control over firing a request to retrieve data
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once
*/
type UseLazyQuerySubscription<D extends QueryDefinition<any, any, any, any>> = (options?: SubscriptionOptions) => readonly [
LazyQueryTrigger<D>,
QueryArgFrom<D> | UninitializedValue,
{
reset: () => void;
}
];
type TypedUseLazyQuerySubscription<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseLazyQuerySubscription<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
/**
* @internal
*/
type QueryStateSelector<R extends Record<string, any>, D extends QueryDefinition<any, any, any, any>> = (state: UseQueryStateDefaultResult<D>) => R;
/**
* Provides a way to define a strongly-typed version of
* {@linkcode QueryStateSelector} for use with a specific query.
* This is useful for scenarios where you want to create a "pre-typed"
* {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}
* function.
*
* @example
* <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>
*
* ```tsx
* import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react'
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
*
* type Post = {
* id: number
* title: string
* }
*
* type PostsApiResponse = {
* posts: Post[]
* total: number
* skip: number
* limit: number
* }
*
* type QueryArgument = number | undefined
*
* type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>
*
* type SelectedResult = Pick<PostsApiResponse, 'posts'>
*
* const postsApiSlice = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),
* reducerPath: 'postsApi',
* tagTypes: ['Posts'],
* endpoints: (build) => ({
* getPosts: build.query<PostsApiResponse, QueryArgument>({
* query: (limit = 5) => `?limit=${limit}&select=title`,
* }),
* }),
* })
*
* const { useGetPostsQuery } = postsApiSlice
*
* function PostById({ id }: { id: number }) {
* const { post } = useGetPostsQuery(undefined, {
* selectFromResult: (state) => ({
* post: state.data?.posts.find((post) => post.id === id),
* }),
* })
*
* return <li>{post?.title}</li>
* }
*
* const EMPTY_ARRAY: Post[] = []
*
* const typedSelectFromResult: TypedQueryStateSelector<
* PostsApiResponse,
* QueryArgument,
* BaseQueryFunction,
* SelectedResult
* > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })
*
* function PostsList() {
* const { posts } = useGetPostsQuery(undefined, {
* selectFromResult: typedSelectFromResult,
* })
*
* return (
* <div>
* <ul>
* {posts.map((post) => (
* <PostById key={post.id} id={post.id} />
* ))}
* </ul>
* </div>
* )
* }
* ```
*
* @template ResultType - The type of the result `data` returned by the query.
* @template QueryArgumentType - The type of the argument passed into the query.
* @template BaseQueryFunctionType - The type of the base query function being used.
* @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.
*
* @since 2.3.0
* @public
*/
type TypedQueryStateSelector<ResultType, QueryArgumentType, BaseQueryFunctionType extends BaseQueryFn, SelectedResultType extends Record<string, any> = UseQueryStateDefaultResult<QueryDefinition<QueryArgumentType, BaseQueryFunctionType, string, ResultType, string>>> = QueryStateSelector<SelectedResultType, QueryDefinition<QueryArgumentType, BaseQueryFunctionType, string, ResultType, string>>;
/**
* A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
*
* Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).
*
* #### Features
*
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <R extends Record<string, any> = UseQueryStateDefaultResult<D>>(arg: QueryArgFrom<D> | SkipToken, options?: UseQueryStateOptions<D, R>) => UseQueryStateResult<D, R>;
type TypedUseQueryState<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseQueryState<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
/**
* @internal
*/
type UseQueryStateOptions<D extends QueryDefinition<any, any, any, any>, R extends Record<string, any>> = {
/**
* Prevents a query from automatically running.
*
* @remarks
* When skip is true:
*
* - **If the query has cached data:**
* * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after skipping the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```ts
* // codeblock-meta title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
* When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
* If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
*
* @example
* ```ts
* // codeblock-meta title="Using selectFromResult to extract a single result"
* function PostsList() {
* const { data: posts } = api.useGetPostsQuery();
*
* return (
* <ul>
* {posts?.data?.map((post) => (
* <PostById key={post.id} id={post.id} />
* ))}
* </ul>
* );
* }
*
* function PostById({ id }: { id: number }) {
* // Will select the post with the given id, and will only rerender if the given posts data changes
* const { post } = api.useGetPostsQuery(undefined, {
* selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),
* });
*
* return <li>{post?.name}</li>;
* }
* ```
*/
selectFromResult?: QueryStateSelector<R, D>;
};
/**
* Provides a way to define a "pre-typed" version of
* {@linkcode UseQueryStateOptions} with specific options for a given query.
* This is particularly useful for setting default query behaviors such as
* refetching strategies, which can be overridden as needed.
*
* @example
* <caption>#### __Create a `useQuery` hook with default options__</caption>
*
* ```ts
* import type {
* SubscriptionOptions,
* TypedUseQueryStateOptions,
* } from '@reduxjs/toolkit/query/react'
* import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
*
* type Post = {
* id: number
* name: string
* }
*
* const api = createApi({
* baseQuery: fetchBaseQuery({ baseUrl: '/' }),
* tagTypes: ['Post'],
* endpoints: (build) => ({
* getPosts: build.query<Post[], void>({
* query: () => 'posts',
* }),
* }),
* })
*
* const { useGetPostsQuery } = api
*
* export const useGetPostsQueryWithDefaults = <
* SelectedResult extends Record<string, any>,
* >(
* overrideOptions: TypedUseQueryStateOptions<
* Post[],
* void,
* ReturnType<typeof fetchBaseQuery>,
* SelectedResult
* > &
* SubscriptionOptions,
* ) =>
* useGetPostsQuery(undefined, {
* // Insert default options here
*
* refetchOnMountOrArgChange: true,
* refetchOnFocus: true,
* ...overrideOptions,
* })
* ```
*
* @template ResultType - The type of the result `data` returned by the query.
* @template QueryArg - The type of the argument passed into the query.
* @template BaseQuery - The type of the base query function being used.
* @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.
*
* @since 2.2.8
* @public
*/
type TypedUseQueryStateOptions<ResultType, QueryArg, BaseQuery extends BaseQueryFn, SelectedResult extends Record<string, any> = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseQueryStateOptions<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>, SelectedResult>;
type UseQueryStateResult<_ extends QueryDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R>;
/**
* Helper type to manually type the result
* of the `useQueryState` hook in userland code.
*/
type TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = UseQueryStateDefaultResult<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = TSHelpersNoInfer<R>;
type UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> = QuerySubState<D> & {
/**
* Where `data` tries to hold data as much as possible, also re-using
* data from the last arguments passed into the hook, this property
* will always contain the received data from the query, for the current query arguments.
*/
currentData?: ResultTypeFrom<D>;
/**
* Query has not started yet.
*/
isUninitialized: false;
/**
* Query is currently loading for the first time. No data yet.
*/
isLoading: false;
/**
* Query is currently fetching, but might have data from an earlier request.
*/
isFetching: false;
/**
* Query has data from a successful load.
*/
isSuccess: false;
/**
* Query is currently in "error" state.
*/
isError: false;
};
type UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<Extract<UseQueryStateBaseResult<D>, {
status: QueryStatus.uninitialized;
}>, {
isUninitialized: true;
}>;
type UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {
isLoading: true;
isFetching: boolean;
data: undefined;
}>;
type UseQueryStateSuccessFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {
isSuccess: true;
isFetching: true;
error: undefined;
} & {
data: ResultTypeFrom<D>;
} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;
type UseQueryStateSuccessNotFetching<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {
isSuccess: true;
isFetching: false;
error: undefined;
} & {
data: ResultTypeFrom<D>;
currentData: ResultTypeFrom<D>;
} & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>>;
type UseQueryStateError<D extends QueryDefinition<any, any, any, any>> = TSHelpersOverride<UseQueryStateBaseResult<D>, {
isError: true;
} & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>>;
type UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> = TSHelpersId<UseQueryStateUninitialized<D> | UseQueryStateLoading<D> | UseQueryStateSuccessFetching<D> | UseQueryStateSuccessNotFetching<D> | UseQueryStateError<D>> & {
/**
* @deprecated Included for completeness, but discouraged.
* Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
* and `isUninitialized` flags instead
*/
status: QueryStatus;
};
type LazyInfiniteQueryTrigger<D extends InfiniteQueryDefinition<any, any, any, any, any>> = {
/**
* Triggers a lazy query.
*
* By default, this will start a new request even if there is already a value in the cache.
* If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.
*
* @remarks
* If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await getUserById(1).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>, direction: InfiniteQueryDirection): InfiniteQueryActionCreatorResult<D>;
};
type TypedLazyInfiniteQueryTrigger<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = LazyInfiniteQueryTrigger<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
type UseInfiniteQuerySubscriptionOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>> = SubscriptionOptions & {
/**
* Prevents a query from automatically running.
*
* @remarks
* When `skip` is true (or `skipToken` is passed in as `arg`):
*
* - **If the query has cached data:**
* * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```tsx
* // codeblock-meta no-transpile title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.
* - `false` - Will not cause a query to be performed _unless_ it does not exist yet.
* - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.
* - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.
*
* If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.
*/
refetchOnMountOrArgChange?: boolean | number;
initialPageParam?: PageParamFrom<D>;
};
type TypedUseInfiniteQuerySubscription<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscription<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
type UseInfiniteQuerySubscriptionResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = Pick<InfiniteQueryActionCreatorResult<D>, 'refetch'> & {
trigger: LazyInfiniteQueryTrigger<D>;
fetchNextPage: () => InfiniteQueryActionCreatorResult<D>;
fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>;
};
/**
* Helper type to manually type the result
* of the `useQuerySubscription` hook in userland code.
*/
type TypedUseInfiniteQuerySubscriptionResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuerySubscriptionResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
type InfiniteQueryStateSelector<R extends Record<string, any>, D extends InfiniteQueryDefinition<any, any, any, any, any>> = (state: UseInfiniteQueryStateDefaultResult<D>) => R;
type TypedInfiniteQueryStateSelector<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, SelectedResult extends Record<string, any> = UseInfiniteQueryStateDefaultResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>> = InfiniteQueryStateSelector<SelectedResult, InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
/**
* A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available. Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.
*
* The `data` field will be a `{pages: Data[], pageParams: PageParam[]}` structure containing all fetched page responses and the corresponding page param values for each page. You may use this to render individual pages, combine all pages into a single infinite list, or other display logic as needed.
*
* This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.
*
* As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.
*
* By default, the initial request will use the `initialPageParam` value that was defined on the infinite query endpoint. If you want to start from a different value, you can pass `initialPageParam` as part of the hook options to override that initial request value.
*
* Use the returned `fetchNextPage` and `fetchPreviousPage` methods on the hook result object to trigger fetches forwards and backwards. These will always calculate the next or previous page param based on the current cached pages and the provided `getNext/PreviousPageParam` callbacks defined in the endpoint.
*
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseInfiniteQuery<D extends InfiniteQueryDefinition<any, any, any, any, any>> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D> & UseInfiniteQueryStateOptions<D, R>) => UseInfiniteQueryHookResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'fetchNextPage' | 'fetchPreviousPage'>;
type TypedUseInfiniteQuery<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQuery<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
/**
* A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.
*
* Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).
*
* #### Features
*
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseInfiniteQueryState<D extends InfiniteQueryDefinition<any, any, any, any, any>> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQueryStateOptions<D, R>) => UseInfiniteQueryStateResult<D, R>;
type TypedUseInfiniteQueryState<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn> = UseInfiniteQueryState<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>;
/**
* A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data. Additionally, it will cache multiple "pages" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.
*
* The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.
*
* Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).
*
* #### Features
*
* - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards
* - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met
*/
type UseInfiniteQuerySubscription<D extends InfiniteQueryDefinition<any, any, any, any, any>> = (arg: InfiniteQueryArgFrom<D> | SkipToken, options?: UseInfiniteQuerySubscriptionOptions<D>) => UseInfiniteQuerySubscriptionResult<D>;
type UseInfiniteQueryHookResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = UseInfiniteQueryStateResult<D, R> & Pick<UseInfiniteQuerySubscriptionResult<D>, 'refetch'>;
type TypedUseInfiniteQueryHookResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>> = UseInfiniteQueryHookResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>, R>;
type UseInfiniteQueryStateOptions<D extends InfiniteQueryDefinition<any, any, any, any, any>, R extends Record<string, any>> = {
/**
* Prevents a query from automatically running.
*
* @remarks
* When skip is true:
*
* - **If the query has cached data:**
* * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed
* * The query will have a status of `uninitialized`
* * If `skip: false` is set after skipping the initial load, the cached result will be used
* - **If the query does not have cached data:**
* * The query will have a status of `uninitialized`
* * The query will not exist in the state when viewed with the dev tools
* * The query will not automatically fetch on mount
* * The query will not automatically run when additional components with the same query are added that do run
*
* @example
* ```ts
* // codeblock-meta title="Skip example"
* const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {
* const { data, error, status } = useGetPokemonByNameQuery(name, {
* skip,
* });
*
* return (
* <div>
* {name} - {status}
* </div>
* );
* };
* ```
*/
skip?: boolean;
/**
* `selectFromResult` allows you to get a specific segment from a query result in a performant manner.
* When using this feature, the component will not rerender unless the underlying data of the selected item has changed.
* If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.
* Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.
*
* @example
* ```ts
* // codeblock-meta title="Using selectFromResult to extract a single result"
* function PostsList() {
* const { data: posts } = api.useGetPostsQuery();
*
* return (
* <ul>
* {posts?.data?.map((post) => (
* <PostById key={post.id} id={post.id} />
* ))}
* </ul>
* );
* }
*
* function PostById({ id }: { id: number }) {
* // Will select the post with the given id, and will only rerender if the given posts data changes
* const { post } = api.useGetPostsQuery(undefined, {
* selectFromResult: ({ data }) => ({ post: data?.find((post) => post.id === id) }),
* });
*
* return <li>{post?.name}</li>;
* }
* ```
*/
selectFromResult?: InfiniteQueryStateSelector<R, D>;
};
type TypedUseInfiniteQueryStateOptions<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, SelectedResult extends Record<string, any> = UseInfiniteQueryStateDefaultResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>> = UseInfiniteQueryStateOptions<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>, SelectedResult>;
type UseInfiniteQueryStateResult<D extends InfiniteQueryDefinition<any, any, any, any, any>, R = UseInfiniteQueryStateDefaultResult<D>> = TSHelpersNoInfer<R>;
type TypedUseInfiniteQueryStateResult<ResultType, QueryArg, PageParam, BaseQuery extends BaseQueryFn, R = UseInfiniteQueryStateDefaultResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>>> = UseInfiniteQueryStateResult<InfiniteQueryDefinition<QueryArg, PageParam, BaseQuery, string, ResultType, string>, R>;
type UseInfiniteQueryStateBaseResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = InfiniteQuerySubState<D> & {
/**
* Where `data` tries to hold data as much as possible, also re-using
* data from the last arguments passed into the hook, this property
* will always contain the received data from the query, for the current query arguments.
*/
currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>;
/**
* Query has not started yet.
*/
isUninitialized: false;
/**
* Query is currently loading for the first time. No data yet.
*/
isLoading: false;
/**
* Query is currently fetching, but might have data from an earlier request.
*/
isFetching: false;
/**
* Query has data from a successful load.
*/
isSuccess: false;
/**
* Query is currently in "error" state.
*/
isError: false;
hasNextPage: boolean;
hasPreviousPage: boolean;
isFetchingNextPage: boolean;
isFetchingPreviousPage: boolean;
};
type UseInfiniteQueryStateDefaultResult<D extends InfiniteQueryDefinition<any, any, any, any, any>> = TSHelpersId<TSHelpersOverride<Extract<UseInfiniteQueryStateBaseResult<D>, {
status: QueryStatus.uninitialized;
}>, {
isUninitialized: true;
}> | TSHelpersOverride<UseInfiniteQueryStateBaseResult<D>, {
isLoading: true;
isFetching: boolean;
data: undefined;
} | ({
isSuccess: true;
isFetching: true;
error: undefined;
} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp'>>) | ({
isSuccess: true;
isFetching: false;
error: undefined;
} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'data' | 'fulfilledTimeStamp' | 'currentData'>>) | ({
isError: true;
} & Required<Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>>)>> & {
/**
* @deprecated Included for completeness, but discouraged.
* Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`
* and `isUninitialized` flags instead
*/
status: QueryStatus;
};
type MutationStateSelector<R extends Record<string, any>, D extends MutationDefinition<any, any, any, any>> = (state: MutationResultSelectorResult<D>) => R;
type UseMutationStateOptions<D extends MutationDefinition<any, any, any, any>, R extends Record<string, any>> = {
selectFromResult?: MutationStateSelector<R, D>;
fixedCacheKey?: string;
};
type UseMutationStateResult<D extends MutationDefinition<any, any, any, any>, R> = TSHelpersNoInfer<R> & {
originalArgs?: QueryArgFrom<D>;
/**
* Resets the hook state to its initial `uninitialized` state.
* This will also remove the last result from the cache.
*/
reset: () => void;
};
/**
* Helper type to manually type the result
* of the `useMutation` hook in userland code.
*/
type TypedUseMutationResult<ResultType, QueryArg, BaseQuery extends BaseQueryFn, R = MutationResultSelectorResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>> = UseMutationStateResult<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>, R>;
/**
* A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.
*
* #### Features
*
* - Manual control over firing a request to alter data on the server or possibly invalidate the cache
* - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts
* - Returns the latest request status and cached data from the Redux store
* - Re-renders as the request status changes and data becomes available
*/
type UseMutation<D extends MutationDefinition<any, any, any, any>> = <R extends Record<string, any> = MutationResultSelectorResult<D>>(options?: UseMutationStateOptions<D, R>) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>];
type TypedUseMutation<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = UseMutation<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type MutationTrigger<D extends MutationDefinition<any, any, any, any>> = {
/**
* Triggers the mutation and returns a Promise.
* @remarks
* If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
*
* @example
* ```ts
* // codeblock-meta title="Using .unwrap with async await"
* try {
* const payload = await addPost({ id: 1, name: 'Example' }).unwrap();
* console.log('fulfilled', payload)
* } catch (error) {
* console.error('rejected', error);
* }
* ```
*/
(arg: QueryArgFrom<D>): MutationActionCreatorResult<D>;
};
type TypedMutationTrigger<ResultType, QueryArg, BaseQuery extends BaseQueryFn> = MutationTrigger<MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>>;
type QueryHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.query;
} ? `use${Capitalize<K & string>}Query` : never]: UseQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
};
type LazyQueryHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.query;
} ? `useLazy${Capitalize<K & string>}Query` : never]: UseLazyQuery<Extract<Definitions[K], QueryDefinition<any, any, any, any>>>;
};
type InfiniteQueryHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.infinitequery;
} ? `use${Capitalize<K & string>}InfiniteQuery` : never]: UseInfiniteQuery<Extract<Definitions[K], InfiniteQueryDefinition<any, any, any, any, any>>>;
};
type MutationHookNames<Definitions extends EndpointDefinitions> = {
[K in keyof Definitions as Definitions[K] extends {
type: DefinitionType.mutation;
} ? `use${Capitalize<K & string>}Mutation` : never]: UseMutation<Extract<Definitions[K], MutationDefinition<any, any, any, any>>>;
};
type HooksWithUniqueNames<Definitions extends EndpointDefinitions> = QueryHookNames<Definitions> & LazyQueryHookNames<Definitions> & InfiniteQueryHookNames<Definitions> & MutationHookNames<Definitions>;
export declare const reactHooksModuleName: unique symbol;
type ReactHooksModule = typeof reactHooksModuleName;
declare module '@reduxjs/toolkit/query' {
interface ApiModules<BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string> {
[reactHooksModuleName]: {
/**
* Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.
*/
endpoints: {
[K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? QueryHooks<Definitions[K]> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? MutationHooks<Definitions[K]> : Definitions[K] extends InfiniteQueryDefinition<any, any, any, any, any> ? InfiniteQueryHooks<Definitions[K]> : never;
};
/**
* A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.
*/
usePrefetch<EndpointName extends QueryKeys<Definitions>>(endpointName: EndpointName, options?: PrefetchOptions): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;
} & HooksWithUniqueNames<Definitions>;
}
}
type RR = typeof react_redux;
interface ReactHooksModuleOptions {
/**
* The hooks from React Redux to be used
*/
hooks?: {
/**
* The version of the `useDispatch` hook to be used
*/
useDispatch: RR['useDispatch'];
/**
* The version of the `useSelector` hook to be used
*/
useSelector: RR['useSelector'];
/**
* The version of the `useStore` hook to be used
*/
useStore: RR['useStore'];
};
/**
* The version of the `batchedUpdates` function to be used
*/
batch?: RR['batch'];
/**
* Enables performing asynchronous tasks immediately within a render.
*
* @example
*
* ```ts
* import {
* buildCreateApi,
* coreModule,
* reactHooksModule
* } from '@reduxjs/toolkit/query/react'
*
* const createApi = buildCreateApi(
* coreModule(),
* reactHooksModule({ unstable__sideEffectsInRender: true })
* )
* ```
*/
unstable__sideEffectsInRender?: boolean;
/**
* A selector creator (usually from `reselect`, or matching the same signature)
*/
createSelector?: typeof createSelector;
}
/**
* Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.
*
* @example
* ```ts
* const MyContext = React.createContext<ReactReduxContextValue | null>(null);
* const customCreateApi = buildCreateApi(
* coreModule(),
* reactHooksModule({
* hooks: {
* useDispatch: createDispatchHook(MyContext),
* useSelector: createSelectorHook(MyContext),
* useStore: createStoreHook(MyContext)
* }
* })
* );
* ```
*
* @returns A module for use with `buildCreateApi`
*/
declare const reactHooksModule: ({ batch, hooks, createSelector, unstable__sideEffectsInRender, ...rest }?: ReactHooksModuleOptions) => Module<ReactHooksModule>;
/**
* Can be used as a `Provider` if you **do not already have a Redux store**.
*
* @example
* ```tsx
* // codeblock-meta no-transpile title="Basic usage - wrap your App with ApiProvider"
* import * as React from 'react';
* import { ApiProvider } from '@reduxjs/toolkit/query/react';
* import { Pokemon } from './features/Pokemon';
*
* function App() {
* return (
* <ApiProvider api={api}>
* <Pokemon />
* </ApiProvider>
* );
* }
* ```
*
* @remarks
* Using this together with an existing redux store, both will
* conflict with each other - please use the traditional redux setup
* in that case.
*/
declare function ApiProvider(props: {
children: any;
api: Api<any, {}, any, any>;
setupListeners?: Parameters<typeof setupListeners>[1] | false;
context?: Context<ReactReduxContextValue | null>;
}): React.JSX.Element;
declare const createApi: _reduxjs_toolkit_query.CreateApi<typeof _reduxjs_toolkit_query.coreModuleName | typeof reactHooksModuleName>;
export { ApiProvider, type TypedInfiniteQueryStateSelector, type TypedLazyInfiniteQueryTrigger, type TypedLazyQueryTrigger, type TypedMutationTrigger, type TypedQueryStateSelector, type TypedUseInfiniteQuery, type TypedUseInfiniteQueryHookResult, type TypedUseInfiniteQueryState, type TypedUseInfiniteQueryStateOptions, type TypedUseInfiniteQueryStateResult, type TypedUseInfiniteQuerySubscription, type TypedUseInfiniteQuerySubscriptionResult, type TypedUseLazyQuery, type TypedUseLazyQueryStateResult, type TypedUseLazyQuerySubscription, type TypedUseMutation, type TypedUseMutationResult, type TypedUseQuery, type TypedUseQueryHookResult, type TypedUseQueryState, type TypedUseQueryStateOptions, type TypedUseQueryStateResult, type TypedUseQuerySubscription, type TypedUseQuerySubscriptionResult, createApi, reactHooksModule };
@@ -0,0 +1,553 @@
var openParentheses = "(".charCodeAt(0);
var closeParentheses = ")".charCodeAt(0);
var singleQuote = "'".charCodeAt(0);
var doubleQuote = '"'.charCodeAt(0);
var backslash = "\\".charCodeAt(0);
var slash = "/".charCodeAt(0);
var comma = ",".charCodeAt(0);
var colon = ":".charCodeAt(0);
var star = "*".charCodeAt(0);
var uLower = "u".charCodeAt(0);
var uUpper = "U".charCodeAt(0);
var plus = "+".charCodeAt(0);
var isUnicodeRange = /^[a-f0-9?-]+$/i;
var parse$1 = function(input) {
var tokens = [];
var value = input;
var next,
quote,
prev,
token,
escape,
escapePos,
whitespacePos,
parenthesesOpenPos;
var pos = 0;
var code = value.charCodeAt(pos);
var max = value.length;
var stack = [{ nodes: tokens }];
var balanced = 0;
var parent;
var name = "";
var before = "";
var after = "";
while (pos < max) {
// Whitespaces
if (code <= 32) {
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
token = value.slice(pos, next);
prev = tokens[tokens.length - 1];
if (code === closeParentheses && balanced) {
after = token;
} else if (prev && prev.type === "div") {
prev.after = token;
prev.sourceEndIndex += token.length;
} else if (
code === comma ||
code === colon ||
(code === slash &&
value.charCodeAt(next + 1) !== star &&
(!parent ||
(parent && parent.type === "function" && parent.value !== "calc")))
) {
before = token;
} else {
tokens.push({
type: "space",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
}
pos = next;
// Quotes
} else if (code === singleQuote || code === doubleQuote) {
next = pos;
quote = code === singleQuote ? "'" : '"';
token = {
type: "string",
sourceIndex: pos,
quote: quote
};
do {
escape = false;
next = value.indexOf(quote, next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += quote;
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
token.value = value.slice(pos + 1, next);
token.sourceEndIndex = token.unclosed ? next : next + 1;
tokens.push(token);
pos = next + 1;
code = value.charCodeAt(pos);
// Comments
} else if (code === slash && value.charCodeAt(pos + 1) === star) {
next = value.indexOf("*/", pos);
token = {
type: "comment",
sourceIndex: pos,
sourceEndIndex: next + 2
};
if (next === -1) {
token.unclosed = true;
next = value.length;
token.sourceEndIndex = next;
}
token.value = value.slice(pos + 2, next);
tokens.push(token);
pos = next + 2;
code = value.charCodeAt(pos);
// Operation within calc
} else if (
(code === slash || code === star) &&
parent &&
parent.type === "function" &&
parent.value === "calc"
) {
token = value[pos];
tokens.push({
type: "word",
sourceIndex: pos - before.length,
sourceEndIndex: pos + token.length,
value: token
});
pos += 1;
code = value.charCodeAt(pos);
// Dividers
} else if (code === slash || code === comma || code === colon) {
token = value[pos];
tokens.push({
type: "div",
sourceIndex: pos - before.length,
sourceEndIndex: pos + token.length,
value: token,
before: before,
after: ""
});
before = "";
pos += 1;
code = value.charCodeAt(pos);
// Open parentheses
} else if (openParentheses === code) {
// Whitespaces after open parentheses
next = pos;
do {
next += 1;
code = value.charCodeAt(next);
} while (code <= 32);
parenthesesOpenPos = pos;
token = {
type: "function",
sourceIndex: pos - name.length,
value: name,
before: value.slice(parenthesesOpenPos + 1, next)
};
pos = next;
if (name === "url" && code !== singleQuote && code !== doubleQuote) {
next -= 1;
do {
escape = false;
next = value.indexOf(")", next + 1);
if (~next) {
escapePos = next;
while (value.charCodeAt(escapePos - 1) === backslash) {
escapePos -= 1;
escape = !escape;
}
} else {
value += ")";
next = value.length - 1;
token.unclosed = true;
}
} while (escape);
// Whitespaces before closed
whitespacePos = next;
do {
whitespacePos -= 1;
code = value.charCodeAt(whitespacePos);
} while (code <= 32);
if (parenthesesOpenPos < whitespacePos) {
if (pos !== whitespacePos + 1) {
token.nodes = [
{
type: "word",
sourceIndex: pos,
sourceEndIndex: whitespacePos + 1,
value: value.slice(pos, whitespacePos + 1)
}
];
} else {
token.nodes = [];
}
if (token.unclosed && whitespacePos + 1 !== next) {
token.after = "";
token.nodes.push({
type: "space",
sourceIndex: whitespacePos + 1,
sourceEndIndex: next,
value: value.slice(whitespacePos + 1, next)
});
} else {
token.after = value.slice(whitespacePos + 1, next);
token.sourceEndIndex = next;
}
} else {
token.after = "";
token.nodes = [];
}
pos = next + 1;
token.sourceEndIndex = token.unclosed ? next : pos;
code = value.charCodeAt(pos);
tokens.push(token);
} else {
balanced += 1;
token.after = "";
token.sourceEndIndex = pos + 1;
tokens.push(token);
stack.push(token);
tokens = token.nodes = [];
parent = token;
}
name = "";
// Close parentheses
} else if (closeParentheses === code && balanced) {
pos += 1;
code = value.charCodeAt(pos);
parent.after = after;
parent.sourceEndIndex += after.length;
after = "";
balanced -= 1;
stack[stack.length - 1].sourceEndIndex = pos;
stack.pop();
parent = stack[balanced];
tokens = parent.nodes;
// Words
} else {
next = pos;
do {
if (code === backslash) {
next += 1;
}
next += 1;
code = value.charCodeAt(next);
} while (
next < max &&
!(
code <= 32 ||
code === singleQuote ||
code === doubleQuote ||
code === comma ||
code === colon ||
code === slash ||
code === openParentheses ||
(code === star &&
parent &&
parent.type === "function" &&
parent.value === "calc") ||
(code === slash &&
parent.type === "function" &&
parent.value === "calc") ||
(code === closeParentheses && balanced)
)
);
token = value.slice(pos, next);
if (openParentheses === code) {
name = token;
} else if (
(uLower === token.charCodeAt(0) || uUpper === token.charCodeAt(0)) &&
plus === token.charCodeAt(1) &&
isUnicodeRange.test(token.slice(2))
) {
tokens.push({
type: "unicode-range",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
} else {
tokens.push({
type: "word",
sourceIndex: pos,
sourceEndIndex: next,
value: token
});
}
pos = next;
}
}
for (pos = stack.length - 1; pos; pos -= 1) {
stack[pos].unclosed = true;
stack[pos].sourceEndIndex = value.length;
}
return stack[0].nodes;
};
var walk$1 = function walk(nodes, cb, bubble) {
var i, max, node, result;
for (i = 0, max = nodes.length; i < max; i += 1) {
node = nodes[i];
if (!bubble) {
result = cb(node, i, nodes);
}
if (
result !== false &&
node.type === "function" &&
Array.isArray(node.nodes)
) {
walk(node.nodes, cb, bubble);
}
if (bubble) {
cb(node, i, nodes);
}
}
};
function stringifyNode(node, custom) {
var type = node.type;
var value = node.value;
var buf;
var customResult;
if (custom && (customResult = custom(node)) !== undefined) {
return customResult;
} else if (type === "word" || type === "space") {
return value;
} else if (type === "string") {
buf = node.quote || "";
return buf + value + (node.unclosed ? "" : buf);
} else if (type === "comment") {
return "/*" + value + (node.unclosed ? "" : "*/");
} else if (type === "div") {
return (node.before || "") + value + (node.after || "");
} else if (Array.isArray(node.nodes)) {
buf = stringify$1(node.nodes, custom);
if (type !== "function") {
return buf;
}
return (
value +
"(" +
(node.before || "") +
buf +
(node.after || "") +
(node.unclosed ? "" : ")")
);
}
return value;
}
function stringify$1(nodes, custom) {
var result, i;
if (Array.isArray(nodes)) {
result = "";
for (i = nodes.length - 1; ~i; i -= 1) {
result = stringifyNode(nodes[i], custom) + result;
}
return result;
}
return stringifyNode(nodes, custom);
}
var stringify_1 = stringify$1;
var unit;
var hasRequiredUnit;
function requireUnit () {
if (hasRequiredUnit) return unit;
hasRequiredUnit = 1;
var minus = "-".charCodeAt(0);
var plus = "+".charCodeAt(0);
var dot = ".".charCodeAt(0);
var exp = "e".charCodeAt(0);
var EXP = "E".charCodeAt(0);
// Check if three code points would start a number
// https://www.w3.org/TR/css-syntax-3/#starts-with-a-number
function likeNumber(value) {
var code = value.charCodeAt(0);
var nextCode;
if (code === plus || code === minus) {
nextCode = value.charCodeAt(1);
if (nextCode >= 48 && nextCode <= 57) {
return true;
}
var nextNextCode = value.charCodeAt(2);
if (nextCode === dot && nextNextCode >= 48 && nextNextCode <= 57) {
return true;
}
return false;
}
if (code === dot) {
nextCode = value.charCodeAt(1);
if (nextCode >= 48 && nextCode <= 57) {
return true;
}
return false;
}
if (code >= 48 && code <= 57) {
return true;
}
return false;
}
// Consume a number
// https://www.w3.org/TR/css-syntax-3/#consume-number
unit = function(value) {
var pos = 0;
var length = value.length;
var code;
var nextCode;
var nextNextCode;
if (length === 0 || !likeNumber(value)) {
return false;
}
code = value.charCodeAt(pos);
if (code === plus || code === minus) {
pos++;
}
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
code = value.charCodeAt(pos);
nextCode = value.charCodeAt(pos + 1);
if (code === dot && nextCode >= 48 && nextCode <= 57) {
pos += 2;
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
}
code = value.charCodeAt(pos);
nextCode = value.charCodeAt(pos + 1);
nextNextCode = value.charCodeAt(pos + 2);
if (
(code === exp || code === EXP) &&
((nextCode >= 48 && nextCode <= 57) ||
((nextCode === plus || nextCode === minus) &&
nextNextCode >= 48 &&
nextNextCode <= 57))
) {
pos += nextCode === plus || nextCode === minus ? 3 : 2;
while (pos < length) {
code = value.charCodeAt(pos);
if (code < 48 || code > 57) {
break;
}
pos += 1;
}
}
return {
number: value.slice(0, pos),
unit: value.slice(pos)
};
};
return unit;
}
var parse = parse$1;
var walk = walk$1;
var stringify = stringify_1;
function ValueParser(value) {
if (this instanceof ValueParser) {
this.nodes = parse(value);
return this;
}
return new ValueParser(value);
}
ValueParser.prototype.toString = function() {
return Array.isArray(this.nodes) ? stringify(this.nodes) : "";
};
ValueParser.prototype.walk = function(cb, bubble) {
walk(this.nodes, cb, bubble);
return this;
};
ValueParser.unit = requireUnit();
ValueParser.walk = walk;
ValueParser.stringify = stringify;
var lib = ValueParser;
export { lib as l };
@@ -0,0 +1,7 @@
export declare const COMMON_MIME_TYPES: Map<string, string>;
export declare function toFileWithPath(file: FileWithPath, path?: string, h?: FileSystemHandle): FileWithPath;
export interface FileWithPath extends File {
readonly path?: string;
readonly handle?: FileSystemFileHandle;
readonly relativePath?: string;
}
@@ -0,0 +1,246 @@
/**
* @fileoverview Rule to check the spacing around the * in generator functions.
* @author Jamund Ferguson
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const OVERRIDE_SCHEMA = {
oneOf: [
{
enum: ["before", "after", "both", "neither"],
},
{
type: "object",
properties: {
before: { type: "boolean" },
after: { type: "boolean" },
},
additionalProperties: false,
},
],
};
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "11.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin",
url: "https://eslint.style",
},
rule: {
name: "generator-star-spacing",
url: "https://eslint.style/rules/generator-star-spacing",
},
},
],
},
type: "layout",
docs: {
description:
"Enforce consistent spacing around `*` operators in generator functions",
recommended: false,
url: "https://eslint.org/docs/latest/rules/generator-star-spacing",
},
fixable: "whitespace",
schema: [
{
oneOf: [
{
enum: ["before", "after", "both", "neither"],
},
{
type: "object",
properties: {
before: { type: "boolean" },
after: { type: "boolean" },
named: OVERRIDE_SCHEMA,
anonymous: OVERRIDE_SCHEMA,
method: OVERRIDE_SCHEMA,
},
additionalProperties: false,
},
],
},
],
messages: {
missingBefore: "Missing space before *.",
missingAfter: "Missing space after *.",
unexpectedBefore: "Unexpected space before *.",
unexpectedAfter: "Unexpected space after *.",
},
},
create(context) {
const optionDefinitions = {
before: { before: true, after: false },
after: { before: false, after: true },
both: { before: true, after: true },
neither: { before: false, after: false },
};
/**
* Returns resolved option definitions based on an option and defaults
* @param {any} option The option object or string value
* @param {Object} defaults The defaults to use if options are not present
* @returns {Object} the resolved object definition
*/
function optionToDefinition(option, defaults) {
if (!option) {
return defaults;
}
return typeof option === "string"
? optionDefinitions[option]
: Object.assign({}, defaults, option);
}
const modes = (function (option) {
const defaults = optionToDefinition(
option,
optionDefinitions.before,
);
return {
named: optionToDefinition(option.named, defaults),
anonymous: optionToDefinition(option.anonymous, defaults),
method: optionToDefinition(option.method, defaults),
};
})(context.options[0] || {});
const sourceCode = context.sourceCode;
/**
* Checks if the given token is a star token or not.
* @param {Token} token The token to check.
* @returns {boolean} `true` if the token is a star token.
*/
function isStarToken(token) {
return token.value === "*" && token.type === "Punctuator";
}
/**
* Gets the generator star token of the given function node.
* @param {ASTNode} node The function node to get.
* @returns {Token} Found star token.
*/
function getStarToken(node) {
return sourceCode.getFirstToken(
node.parent.method || node.parent.type === "MethodDefinition"
? node.parent
: node,
isStarToken,
);
}
/**
* capitalize a given string.
* @param {string} str the given string.
* @returns {string} the capitalized string.
*/
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
/**
* Checks the spacing between two tokens before or after the star token.
* @param {string} kind Either "named", "anonymous", or "method"
* @param {string} side Either "before" or "after".
* @param {Token} leftToken `function` keyword token if side is "before", or
* star token if side is "after".
* @param {Token} rightToken Star token if side is "before", or identifier
* token if side is "after".
* @returns {void}
*/
function checkSpacing(kind, side, leftToken, rightToken) {
if (
!!(rightToken.range[0] - leftToken.range[1]) !==
modes[kind][side]
) {
const after = leftToken.value === "*";
const spaceRequired = modes[kind][side];
const node = after ? leftToken : rightToken;
const messageId = `${spaceRequired ? "missing" : "unexpected"}${capitalize(side)}`;
context.report({
node,
messageId,
fix(fixer) {
if (spaceRequired) {
if (after) {
return fixer.insertTextAfter(node, " ");
}
return fixer.insertTextBefore(node, " ");
}
return fixer.removeRange([
leftToken.range[1],
rightToken.range[0],
]);
},
});
}
}
/**
* Enforces the spacing around the star if node is a generator function.
* @param {ASTNode} node A function expression or declaration node.
* @returns {void}
*/
function checkFunction(node) {
if (!node.generator) {
return;
}
const starToken = getStarToken(node);
const prevToken = sourceCode.getTokenBefore(starToken);
const nextToken = sourceCode.getTokenAfter(starToken);
let kind = "named";
if (
node.parent.type === "MethodDefinition" ||
(node.parent.type === "Property" && node.parent.method)
) {
kind = "method";
} else if (!node.id) {
kind = "anonymous";
}
// Only check before when preceded by `function`|`static` keyword
if (
!(
kind === "method" &&
starToken === sourceCode.getFirstToken(node.parent)
)
) {
checkSpacing(kind, "before", prevToken, starToken);
}
checkSpacing(kind, "after", starToken, nextToken);
}
return {
FunctionDeclaration: checkFunction,
FunctionExpression: checkFunction,
};
},
};
@@ -0,0 +1,2 @@
export function track(info: import("../types.js").TrackFields): import("../types.js").Tracker;
//# sourceMappingURL=track.d.ts.map
@@ -0,0 +1,13 @@
'use strict';
var $TypeError = require('es-errors/type');
// https://262.ecma-international.org/11.0/#sec-numeric-types-bigint-unsignedRightShift
module.exports = function BigIntUnsignedRightShift(x, y) {
if (typeof x !== 'bigint' || typeof y !== 'bigint') {
throw new $TypeError('Assertion failed: `x` and `y` arguments must be BigInts');
}
throw new $TypeError('BigInts have no unsigned right shift, use >> instead');
};
@@ -0,0 +1,146 @@
{
"name": "framer-motion",
"version": "12.23.24",
"description": "A simple and powerful JavaScript animation library",
"main": "dist/cjs/index.js",
"module": "dist/es/index.mjs",
"exports": {
".": {
"types": "./dist/types/index.d.ts",
"require": "./dist/cjs/index.js",
"import": "./dist/es/index.mjs",
"default": "./dist/cjs/index.js"
},
"./debug": {
"types": "./dist/debug.d.ts",
"require": "./dist/cjs/debug.js",
"import": "./dist/es/debug.mjs",
"default": "./dist/cjs/debug.js"
},
"./dom/mini": {
"types": "./dist/dom-mini.d.ts",
"require": "./dist/cjs/dom-mini.js",
"import": "./dist/es/dom-mini.mjs",
"default": "./dist/cjs/dom-mini.js"
},
"./dom": {
"types": "./dist/dom.d.ts",
"require": "./dist/cjs/dom.js",
"import": "./dist/es/dom.mjs",
"default": "./dist/cjs/dom.js"
},
"./client": {
"types": "./dist/types/client.d.ts",
"require": "./dist/cjs/client.js",
"import": "./dist/es/client.mjs",
"default": "./dist/cjs/client.js"
},
"./m": {
"types": "./dist/m.d.ts",
"require": "./dist/cjs/m.js",
"import": "./dist/es/m.mjs",
"default": "./dist/cjs/m.js"
},
"./mini": {
"types": "./dist/mini.d.ts",
"require": "./dist/cjs/mini.js",
"import": "./dist/es/mini.mjs",
"default": "./dist/cjs/mini.js"
},
"./projection": {
"import": "./dist/es/projection.mjs",
"default": "./dist/es/projection.mjs"
},
"./package.json": "./package.json"
},
"types": "dist/types/index.d.ts",
"author": "Matt Perry",
"license": "MIT",
"repository": "https://github.com/motiondivision/motion/",
"sideEffects": false,
"keywords": [
"react animation",
"react",
"pose",
"react pose",
"animation",
"gestures",
"drag",
"spring",
"popmotion",
"framer",
"waapi"
],
"scripts": {
"eslint": "yarn run lint",
"lint": "yarn eslint src/**/*.ts",
"build": "yarn clean && tsc --noEmitOnError -p . && rollup -c && node ./scripts/check-bundle.js",
"dev": "yarn watch",
"clean": "rm -rf types dist lib",
"test": "yarn test-server && yarn test-client",
"test-client": "jest --config jest.config.json --max-workers=2",
"test-server": "jest --config jest.config.ssr.json",
"prettier": "prettier ./src/* --write",
"watch": "concurrently -c blue,red -n tsc --noEmitOnError ,rollup --kill-others \"tsc --noEmitOnError --watch -p . --preserveWatchOutput\" \"rollup --config --watch --no-watch.clearScreen\"",
"prepack": "yarn build && yarn measure",
"postpublish": "git push --tags",
"measure": "rollup -c ./rollup.size.config.mjs"
},
"dependencies": {
"motion-dom": "^12.23.23",
"motion-utils": "^12.23.6",
"tslib": "^2.4.0"
},
"devDependencies": {
"@thednp/dommatrix": "^2.0.11",
"@types/three": "0.137.0",
"three": "0.137.0"
},
"peerDependencies": {
"@emotion/is-prop-valid": "*",
"react": "^18.0.0 || ^19.0.0",
"react-dom": "^18.0.0 || ^19.0.0"
},
"peerDependenciesMeta": {
"@emotion/is-prop-valid": {
"optional": true
},
"react": {
"optional": true
},
"react-dom": {
"optional": true
}
},
"bundlesize": [
{
"path": "./dist/size-rollup-motion.js",
"maxSize": "34.9 kB"
},
{
"path": "./dist/size-rollup-m.js",
"maxSize": "6 kB"
},
{
"path": "./dist/size-rollup-dom-animation.js",
"maxSize": "17.85 kB"
},
{
"path": "./dist/size-rollup-dom-max.js",
"maxSize": "29.8 kB"
},
{
"path": "./dist/size-rollup-animate.js",
"maxSize": "19.1 kB"
},
{
"path": "./dist/size-rollup-scroll.js",
"maxSize": "5.2 kB"
},
{
"path": "./dist/size-rollup-waapi-animate.js",
"maxSize": "2.26 kB"
}
],
"gitHead": "b5df740a4649ee64a07523fc9f362c56f240eb3f"
}
@@ -0,0 +1,22 @@
export declare class TimeoutLatch {
private timeLeftMS;
private timeoutMS;
private isCancelled;
private isTimeExhausted;
private callbacks;
constructor(callback: Function, timeoutMS: number);
tick(): void;
cancel(): void;
reset(): void;
get isDone(): boolean;
}
declare class Scheduler {
private interval;
private latches;
add(latch: TimeoutLatch): void;
remove(latch: TimeoutLatch): void;
private start;
private stop;
}
export declare const getScheduler: () => Scheduler;
export {};
@@ -0,0 +1,130 @@
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {DisabledBehavior, FocusStrategy, Key, MultipleSelection, SelectionBehavior, SelectionMode} from '@react-types/shared';
import {MultipleSelectionState} from './types';
import {Selection} from './Selection';
import {useControlledState} from '@react-stately/utils';
import {useEffect, useMemo, useRef, useState} from 'react';
function equalSets(setA, setB) {
if (setA.size !== setB.size) {
return false;
}
for (let item of setA) {
if (!setB.has(item)) {
return false;
}
}
return true;
}
export interface MultipleSelectionStateProps extends MultipleSelection {
/** How multiple selection should behave in the collection. */
selectionBehavior?: SelectionBehavior,
/** Whether onSelectionChange should fire even if the new set of keys is the same as the last. */
allowDuplicateSelectionEvents?: boolean,
/** Whether `disabledKeys` applies to all interactions, or only selection. */
disabledBehavior?: DisabledBehavior
}
/**
* Manages state for multiple selection and focus in a collection.
*/
export function useMultipleSelectionState(props: MultipleSelectionStateProps): MultipleSelectionState {
let {
selectionMode = 'none' as SelectionMode,
disallowEmptySelection = false,
allowDuplicateSelectionEvents,
selectionBehavior: selectionBehaviorProp = 'toggle',
disabledBehavior = 'all'
} = props;
// We want synchronous updates to `isFocused` and `focusedKey` after their setters are called.
// But we also need to trigger a react re-render. So, we have both a ref (sync) and state (async).
let isFocusedRef = useRef(false);
let [, setFocused] = useState(false);
let focusedKeyRef = useRef<Key | null>(null);
let childFocusStrategyRef = useRef<FocusStrategy | null>(null);
let [, setFocusedKey] = useState<Key | null>(null);
let selectedKeysProp = useMemo(() => convertSelection(props.selectedKeys), [props.selectedKeys]);
let defaultSelectedKeys = useMemo(() => convertSelection(props.defaultSelectedKeys, new Selection()), [props.defaultSelectedKeys]);
let [selectedKeys, setSelectedKeys] = useControlledState(
selectedKeysProp,
defaultSelectedKeys!,
props.onSelectionChange
);
let disabledKeysProp = useMemo(() =>
props.disabledKeys ? new Set(props.disabledKeys) : new Set<Key>()
, [props.disabledKeys]);
let [selectionBehavior, setSelectionBehavior] = useState(selectionBehaviorProp);
// If the selectionBehavior prop is set to replace, but the current state is toggle (e.g. due to long press
// to enter selection mode on touch), and the selection becomes empty, reset the selection behavior.
if (selectionBehaviorProp === 'replace' && selectionBehavior === 'toggle' && typeof selectedKeys === 'object' && selectedKeys.size === 0) {
setSelectionBehavior('replace');
}
// If the selectionBehavior prop changes, update the state as well.
let lastSelectionBehavior = useRef(selectionBehaviorProp);
useEffect(() => {
if (selectionBehaviorProp !== lastSelectionBehavior.current) {
setSelectionBehavior(selectionBehaviorProp);
lastSelectionBehavior.current = selectionBehaviorProp;
}
}, [selectionBehaviorProp]);
return {
selectionMode,
disallowEmptySelection,
selectionBehavior,
setSelectionBehavior,
get isFocused() {
return isFocusedRef.current;
},
setFocused(f) {
isFocusedRef.current = f;
setFocused(f);
},
get focusedKey() {
return focusedKeyRef.current;
},
get childFocusStrategy() {
return childFocusStrategyRef.current;
},
setFocusedKey(k, childFocusStrategy = 'first') {
focusedKeyRef.current = k;
childFocusStrategyRef.current = childFocusStrategy;
setFocusedKey(k);
},
selectedKeys,
setSelectedKeys(keys) {
if (allowDuplicateSelectionEvents || !equalSets(keys, selectedKeys)) {
setSelectedKeys(keys);
}
},
disabledKeys: disabledKeysProp,
disabledBehavior
};
}
function convertSelection(selection: 'all' | Iterable<Key> | null | undefined, defaultValue?: Selection): 'all' | Set<Key> | undefined {
if (!selection) {
return defaultValue;
}
return selection === 'all'
? 'all'
: new Selection(selection);
}
@@ -0,0 +1,43 @@
{
"name": "@types/babel__generator",
"version": "7.27.0",
"description": "TypeScript definitions for @babel/generator",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__generator",
"license": "MIT",
"contributors": [
{
"name": "Troy Gerwien",
"githubUsername": "yortus",
"url": "https://github.com/yortus"
},
{
"name": "Melvin Groenhoff",
"githubUsername": "mgroenhoff",
"url": "https://github.com/mgroenhoff"
},
{
"name": "Cameron Yan",
"githubUsername": "khell",
"url": "https://github.com/khell"
},
{
"name": "Lyanbin",
"githubUsername": "Lyanbin",
"url": "https://github.com/Lyanbin"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/babel__generator"
},
"scripts": {},
"dependencies": {
"@babel/types": "^7.0.0"
},
"peerDependencies": {},
"typesPublisherContentHash": "b5c7deac65dbd6ab9b313d1d71c86afe4383b881dcb4e3b3ac51dab07b8f95fb",
"typeScriptVersion": "5.1"
}
@@ -0,0 +1,162 @@
import { Static } from '../parser/index';
import * as T from '../type/index';
import * as S from './mapping';
export type TGenericReferenceParameterList_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = (TType<Input, Context> extends [infer _0, infer Input extends string] ? (Static.Token.Const<',', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0, infer Input extends string] ? TGenericReferenceParameterList_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TGenericReferenceParameterList<Input extends string, Context extends T.TProperties = {}> = (TGenericReferenceParameterList_0<Input, Context> extends [infer _0, infer Input extends string] ? ((TType<Input, Context> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : [] : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TGenericReferenceParameterListMapping<_0, Context>, Input] : [];
export type TGenericReference<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Ident<Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TGenericReferenceParameterList<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TGenericReferenceMapping<_0, Context>, Input] : [];
export type TGenericArgumentsList_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = (Static.Token.Ident<Input> extends [infer _0, infer Input extends string] ? (Static.Token.Const<',', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0, infer Input extends string] ? TGenericArgumentsList_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TGenericArgumentsList<Input extends string, Context extends T.TProperties = {}> = (TGenericArgumentsList_0<Input, Context> extends [infer _0, infer Input extends string] ? ((Static.Token.Ident<Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : [] : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TGenericArgumentsListMapping<_0, Context>, Input] : [];
export type TGenericArguments<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'<', Input> extends [infer _0, infer Input extends string] ? TGenericArgumentsList<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown], infer Input extends string] ? [S.TGenericArgumentsMapping<_0, Context>, Input] : [];
export type TKeywordString<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'string', Input> extends [infer _0 extends 'string', infer Input extends string] ? [S.TKeywordStringMapping<_0, Context>, Input] : [];
export type TKeywordNumber<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'number', Input> extends [infer _0 extends 'number', infer Input extends string] ? [S.TKeywordNumberMapping<_0, Context>, Input] : [];
export type TKeywordBoolean<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'boolean', Input> extends [infer _0 extends 'boolean', infer Input extends string] ? [S.TKeywordBooleanMapping<_0, Context>, Input] : [];
export type TKeywordUndefined<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'undefined', Input> extends [infer _0 extends 'undefined', infer Input extends string] ? [S.TKeywordUndefinedMapping<_0, Context>, Input] : [];
export type TKeywordNull<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'null', Input> extends [infer _0 extends 'null', infer Input extends string] ? [S.TKeywordNullMapping<_0, Context>, Input] : [];
export type TKeywordInteger<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'integer', Input> extends [infer _0 extends 'integer', infer Input extends string] ? [S.TKeywordIntegerMapping<_0, Context>, Input] : [];
export type TKeywordBigInt<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'bigint', Input> extends [infer _0 extends 'bigint', infer Input extends string] ? [S.TKeywordBigIntMapping<_0, Context>, Input] : [];
export type TKeywordUnknown<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'unknown', Input> extends [infer _0 extends 'unknown', infer Input extends string] ? [S.TKeywordUnknownMapping<_0, Context>, Input] : [];
export type TKeywordAny<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'any', Input> extends [infer _0 extends 'any', infer Input extends string] ? [S.TKeywordAnyMapping<_0, Context>, Input] : [];
export type TKeywordNever<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'never', Input> extends [infer _0 extends 'never', infer Input extends string] ? [S.TKeywordNeverMapping<_0, Context>, Input] : [];
export type TKeywordSymbol<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'symbol', Input> extends [infer _0 extends 'symbol', infer Input extends string] ? [S.TKeywordSymbolMapping<_0, Context>, Input] : [];
export type TKeywordVoid<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'void', Input> extends [infer _0 extends 'void', infer Input extends string] ? [S.TKeywordVoidMapping<_0, Context>, Input] : [];
export type TKeyword<Input extends string, Context extends T.TProperties = {}> = (TKeywordString<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordNumber<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordBoolean<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordUndefined<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordNull<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordInteger<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordBigInt<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordUnknown<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordAny<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordNever<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordSymbol<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TKeywordVoid<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends unknown, infer Input extends string] ? [S.TKeywordMapping<_0, Context>, Input] : [];
export type TLiteralString<Input extends string, Context extends T.TProperties = {}> = Static.Token.String<["'", '"', '`'], Input> extends [infer _0 extends string, infer Input extends string] ? [S.TLiteralStringMapping<_0, Context>, Input] : [];
export type TLiteralNumber<Input extends string, Context extends T.TProperties = {}> = Static.Token.Number<Input> extends [infer _0 extends string, infer Input extends string] ? [S.TLiteralNumberMapping<_0, Context>, Input] : [];
export type TLiteralBoolean<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'true', Input> extends [infer _0, infer Input extends string] ? [_0, Input] : Static.Token.Const<'false', Input> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends 'true' | 'false', infer Input extends string] ? [S.TLiteralBooleanMapping<_0, Context>, Input] : [];
export type TLiteral<Input extends string, Context extends T.TProperties = {}> = (TLiteralBoolean<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TLiteralNumber<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TLiteralString<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends unknown, infer Input extends string] ? [S.TLiteralMapping<_0, Context>, Input] : [];
export type TKeyOf<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'keyof', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown] | [], infer Input extends string] ? [S.TKeyOfMapping<_0, Context>, Input] : [];
export type TIndexArray_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = ((Static.Token.Const<'[', Input> extends [infer _0, infer Input extends string] ? TType<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<']', Input> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : (Static.Token.Const<'[', Input> extends [infer _0, infer Input extends string] ? (Static.Token.Const<']', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [
infer _0,
infer Input extends string
] ? [_0, Input] : []) extends [infer _0, infer Input extends string] ? TIndexArray_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TIndexArray<Input extends string, Context extends T.TProperties = {}> = TIndexArray_0<Input, Context> extends [infer _0 extends ([unknown, unknown, unknown] | [unknown, unknown])[], infer Input extends string] ? [S.TIndexArrayMapping<_0, Context>, Input] : [];
export type TExtends<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'extends', Input> extends [infer _0, infer Input extends string] ? TType<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<'?', Input> extends [infer _2, infer Input extends string] ? TType<Input, Context> extends [infer _3, infer Input extends string] ? Static.Token.Const<':', Input> extends [infer _4, infer Input extends string] ? TType<Input, Context> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown] | [], infer Input extends string] ? [S.TExtendsMapping<_0, Context>, Input] : [];
export type TBase<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'(', Input> extends [infer _0, infer Input extends string] ? TType<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<')', Input> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : TKeyword<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TObject<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TTuple<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TLiteral<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TConstructor<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TFunction<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TMapped<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TAsyncIterator<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TIterator<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TConstructorParameters<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TFunctionParameters<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TInstanceType<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TReturnType<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TArgument<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TAwaited<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TArray<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TRecord<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TPromise<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TPartial<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TRequired<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TPick<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TOmit<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TExclude<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TExtract<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TUppercase<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TLowercase<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TCapitalize<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TUncapitalize<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TDate<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TUint8Array<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TGenericReference<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : TReference<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown, unknown, unknown] | unknown, infer Input extends string] ? [S.TBaseMapping<_0, Context>, Input] : [];
export type TFactor<Input extends string, Context extends T.TProperties = {}> = (TKeyOf<Input, Context> extends [infer _0, infer Input extends string] ? TBase<Input, Context> extends [infer _1, infer Input extends string] ? TIndexArray<Input, Context> extends [infer _2, infer Input extends string] ? TExtends<Input, Context> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TFactorMapping<_0, Context>, Input] : [];
export type TExprTermTail<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'&', Input> extends [infer _0, infer Input extends string] ? TFactor<Input, Context> extends [infer _1, infer Input extends string] ? TExprTermTail<Input, Context> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown, unknown, unknown] | [], infer Input extends string] ? [S.TExprTermTailMapping<_0, Context>, Input] : [];
export type TExprTerm<Input extends string, Context extends T.TProperties = {}> = (TFactor<Input, Context> extends [infer _0, infer Input extends string] ? (TExprTermTail<Input, Context> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TExprTermMapping<_0, Context>, Input] : [];
export type TExprTail<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'|', Input> extends [infer _0, infer Input extends string] ? TExprTerm<Input, Context> extends [infer _1, infer Input extends string] ? TExprTail<Input, Context> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown, unknown, unknown] | [], infer Input extends string] ? [S.TExprTailMapping<_0, Context>, Input] : [];
export type TExpr<Input extends string, Context extends T.TProperties = {}> = (TExprTerm<Input, Context> extends [infer _0, infer Input extends string] ? (TExprTail<Input, Context> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TExprMapping<_0, Context>, Input] : [];
export type TType<Input extends string, Context extends T.TProperties = {}> = (TGenericArguments<Input, Context> extends [infer _0 extends T.TProperties, infer Input extends string] ? TExpr<Input, _0> : [] extends [infer _0, infer Input extends string] ? [_0, Input] : TExpr<Input, Context> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends unknown, infer Input extends string] ? [S.TTypeMapping<_0, Context>, Input] : [];
export type TPropertyKey<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Ident<Input> extends [infer _0, infer Input extends string] ? [_0, Input] : Static.Token.String<["'", '"'], Input> extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends string, infer Input extends string] ? [S.TPropertyKeyMapping<_0, Context>, Input] : [];
export type TReadonly<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'readonly', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown] | [], infer Input extends string] ? [S.TReadonlyMapping<_0, Context>, Input] : [];
export type TOptional<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<'?', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown] | [], infer Input extends string] ? [S.TOptionalMapping<_0, Context>, Input] : [];
export type TProperty<Input extends string, Context extends T.TProperties = {}> = (TReadonly<Input, Context> extends [infer _0, infer Input extends string] ? TPropertyKey<Input, Context> extends [infer _1, infer Input extends string] ? TOptional<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<':', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? [[_0, _1, _2, _3, _4], Input] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TPropertyMapping<_0, Context>, Input] : [];
export type TPropertyDelimiter<Input extends string, Context extends T.TProperties = {}> = ((Static.Token.Const<',', Input> extends [infer _0, infer Input extends string] ? (Static.Token.Const<'\n', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [
infer _0,
infer Input extends string
] ? [_0, Input] : (Static.Token.Const<';', Input> extends [infer _0, infer Input extends string] ? (Static.Token.Const<'\n', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [
infer _0,
infer Input extends string
] ? [_0, Input] : (Static.Token.Const<',', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : (Static.Token.Const<';', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : (Static.Token.Const<'\n', Input> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _0 extends [unknown, unknown] | [unknown], infer Input extends string] ? [S.TPropertyDelimiterMapping<_0, Context>, Input] : [];
export type TPropertyList_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = (TProperty<Input, Context> extends [infer _0, infer Input extends string] ? (TPropertyDelimiter<Input, Context> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0, infer Input extends string] ? TPropertyList_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TPropertyList<Input extends string, Context extends T.TProperties = {}> = (TPropertyList_0<Input, Context> extends [infer _0, infer Input extends string] ? ((TProperty<Input, Context> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : [] : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TPropertyListMapping<_0, Context>, Input] : [];
export type TObject<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'{', Input> extends [infer _0, infer Input extends string] ? TPropertyList<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<'}', Input> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown], infer Input extends string] ? [S.TObjectMapping<_0, Context>, Input] : [];
export type TElementList_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = (TType<Input, Context> extends [infer _0, infer Input extends string] ? (Static.Token.Const<',', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0, infer Input extends string] ? TElementList_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TElementList<Input extends string, Context extends T.TProperties = {}> = (TElementList_0<Input, Context> extends [infer _0, infer Input extends string] ? ((TType<Input, Context> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : [] : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TElementListMapping<_0, Context>, Input] : [];
export type TTuple<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'[', Input> extends [infer _0, infer Input extends string] ? TElementList<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<']', Input> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown], infer Input extends string] ? [S.TTupleMapping<_0, Context>, Input] : [];
export type TParameter<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Ident<Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<':', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? [[_0, _1, _2], Input] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown], infer Input extends string] ? [S.TParameterMapping<_0, Context>, Input] : [];
export type TParameterList_0<Input extends string, Context extends T.TProperties, Result extends unknown[] = []> = (TParameter<Input, Context> extends [infer _0, infer Input extends string] ? (Static.Token.Const<',', Input> extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : []) : []) extends [infer _0, infer Input extends string] ? TParameterList_0<Input, Context, [...Result, _0]> : [Result, Input];
export type TParameterList<Input extends string, Context extends T.TProperties = {}> = (TParameterList_0<Input, Context> extends [infer _0, infer Input extends string] ? ((TParameter<Input, Context> extends [infer _0, infer Input extends string] ? [[_0], Input] : []) extends [infer _0, infer Input extends string] ? [_0, Input] : [[], Input] extends [infer _0, infer Input extends string] ? [_0, Input] : []) extends [infer _1, infer Input extends string] ? [[_0, _1], Input] : [] : []) extends [infer _0 extends [unknown, unknown], infer Input extends string] ? [S.TParameterListMapping<_0, Context>, Input] : [];
export type TFunction<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'(', Input> extends [infer _0, infer Input extends string] ? TParameterList<Input, Context> extends [infer _1, infer Input extends string] ? Static.Token.Const<')', Input> extends [infer _2, infer Input extends string] ? Static.Token.Const<'=>', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? [[_0, _1, _2, _3, _4], Input] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TFunctionMapping<_0, Context>, Input] : [];
export type TConstructor<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'new', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'(', Input> extends [infer _1, infer Input extends string] ? TParameterList<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<')', Input> extends [infer _3, infer Input extends string] ? Static.Token.Const<'=>', Input> extends [infer _4, infer Input extends string] ? TType<Input, Context> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TConstructorMapping<_0, Context>, Input] : [];
export type TMapped<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'{', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'[', Input> extends [infer _1, infer Input extends string] ? Static.Token.Ident<Input> extends [infer _2, infer Input extends string] ? Static.Token.Const<'in', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<']', Input> extends [infer _5, infer Input extends string] ? Static.Token.Const<':', Input> extends [infer _6, infer Input extends string] ? TType<Input, Context> extends [infer _7, infer Input extends string] ? Static.Token.Const<'}', Input> extends [infer _8, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5, _6, _7, _8], Input] : [] : [] : [] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TMappedMapping<_0, Context>, Input] : [];
export type TAsyncIterator<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'AsyncIterator', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TAsyncIteratorMapping<_0, Context>, Input] : [];
export type TIterator<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Iterator', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TIteratorMapping<_0, Context>, Input] : [];
export type TArgument<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Argument', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TArgumentMapping<_0, Context>, Input] : [];
export type TAwaited<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Awaited', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TAwaitedMapping<_0, Context>, Input] : [];
export type TArray<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Array', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TArrayMapping<_0, Context>, Input] : [];
export type TRecord<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Record', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<',', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TRecordMapping<_0, Context>, Input] : [];
export type TPromise<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Promise', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TPromiseMapping<_0, Context>, Input] : [];
export type TConstructorParameters<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'ConstructorParameters', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TConstructorParametersMapping<_0, Context>, Input] : [];
export type TFunctionParameters<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Parameters', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TFunctionParametersMapping<_0, Context>, Input] : [];
export type TInstanceType<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'InstanceType', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TInstanceTypeMapping<_0, Context>, Input] : [];
export type TReturnType<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'ReturnType', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TReturnTypeMapping<_0, Context>, Input] : [];
export type TPartial<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Partial', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TPartialMapping<_0, Context>, Input] : [];
export type TRequired<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Required', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TRequiredMapping<_0, Context>, Input] : [];
export type TPick<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Pick', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<',', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TPickMapping<_0, Context>, Input] : [];
export type TOmit<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Omit', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<',', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TOmitMapping<_0, Context>, Input] : [];
export type TExclude<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Exclude', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<',', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TExcludeMapping<_0, Context>, Input] : [];
export type TExtract<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Extract', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<',', Input> extends [infer _3, infer Input extends string] ? TType<Input, Context> extends [infer _4, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _5, infer Input extends string] ? [[_0, _1, _2, _3, _4, _5], Input] : [] : [] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TExtractMapping<_0, Context>, Input] : [];
export type TUppercase<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Uppercase', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TUppercaseMapping<_0, Context>, Input] : [];
export type TLowercase<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Lowercase', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TLowercaseMapping<_0, Context>, Input] : [];
export type TCapitalize<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Capitalize', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TCapitalizeMapping<_0, Context>, Input] : [];
export type TUncapitalize<Input extends string, Context extends T.TProperties = {}> = (Static.Token.Const<'Uncapitalize', Input> extends [infer _0, infer Input extends string] ? Static.Token.Const<'<', Input> extends [infer _1, infer Input extends string] ? TType<Input, Context> extends [infer _2, infer Input extends string] ? Static.Token.Const<'>', Input> extends [infer _3, infer Input extends string] ? [[_0, _1, _2, _3], Input] : [] : [] : [] : []) extends [infer _0 extends [unknown, unknown, unknown, unknown], infer Input extends string] ? [S.TUncapitalizeMapping<_0, Context>, Input] : [];
export type TDate<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'Date', Input> extends [infer _0 extends 'Date', infer Input extends string] ? [S.TDateMapping<_0, Context>, Input] : [];
export type TUint8Array<Input extends string, Context extends T.TProperties = {}> = Static.Token.Const<'Uint8Array', Input> extends [infer _0 extends 'Uint8Array', infer Input extends string] ? [S.TUint8ArrayMapping<_0, Context>, Input] : [];
export type TReference<Input extends string, Context extends T.TProperties = {}> = Static.Token.Ident<Input> extends [infer _0 extends string, infer Input extends string] ? [S.TReferenceMapping<_0, Context>, Input] : [];
export declare const GenericReferenceParameterList_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const GenericReferenceParameterList: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const GenericReference: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const GenericArgumentsList_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const GenericArgumentsList: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const GenericArguments: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordString: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordNumber: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordBoolean: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordUndefined: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordNull: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordInteger: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordBigInt: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordUnknown: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordAny: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordNever: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordSymbol: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeywordVoid: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Keyword: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const LiteralString: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const LiteralNumber: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const LiteralBoolean: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Literal: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const KeyOf: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const IndexArray_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const IndexArray: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Extends: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Base: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Factor: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ExprTermTail: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ExprTerm: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ExprTail: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Expr: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Type: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const PropertyKey: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Readonly: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Optional: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Property: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const PropertyDelimiter: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const PropertyList_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const PropertyList: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const _Object: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ElementList_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const ElementList: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Tuple: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Parameter: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ParameterList_0: (input: string, context: T.TProperties, result?: unknown[]) => [unknown[], string];
export declare const ParameterList: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Function: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Constructor: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Mapped: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const AsyncIterator: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Iterator: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Argument: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Awaited: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Array: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Record: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Promise: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ConstructorParameters: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const FunctionParameters: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const InstanceType: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const ReturnType: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Partial: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Required: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Pick: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Omit: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Exclude: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Extract: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Uppercase: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Lowercase: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Capitalize: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Uncapitalize: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Date: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Uint8Array: (input: string, context?: T.TProperties) => [unknown, string] | [];
export declare const Reference: (input: string, context?: T.TProperties) => [unknown, string] | [];
@@ -0,0 +1,6 @@
import { BasePlanParams } from './BasePlanParams';
import { PlanServiceNodeParent } from './PlanServiceNodeParent';
export interface SubplanParams extends BasePlanParams {
node: PlanServiceNodeParent;
}
//# sourceMappingURL=SubplanParams.d.ts.map
@@ -0,0 +1,3 @@
declare const Object: ObjectConstructor;
export = Object;
@@ -0,0 +1,56 @@
var path = require('path');
var test = require('tape');
var resolve = require('../');
test('moduleDirectory strings', function (t) {
t.plan(4);
var dir = path.join(__dirname, 'module_dir');
var xopts = {
basedir: dir,
moduleDirectory: 'xmodules'
};
resolve('aaa', xopts, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, '/xmodules/aaa/index.js'));
});
var yopts = {
basedir: dir,
moduleDirectory: 'ymodules'
};
resolve('aaa', yopts, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, '/ymodules/aaa/index.js'));
});
});
test('moduleDirectory array', function (t) {
t.plan(6);
var dir = path.join(__dirname, 'module_dir');
var aopts = {
basedir: dir,
moduleDirectory: ['xmodules', 'ymodules', 'zmodules']
};
resolve('aaa', aopts, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, '/xmodules/aaa/index.js'));
});
var bopts = {
basedir: dir,
moduleDirectory: ['zmodules', 'ymodules', 'xmodules']
};
resolve('aaa', bopts, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, '/ymodules/aaa/index.js'));
});
var copts = {
basedir: dir,
moduleDirectory: ['xmodules', 'ymodules', 'zmodules']
};
resolve('bbb', copts, function (err, res, pkg) {
t.ifError(err);
t.equal(res, path.join(dir, '/zmodules/bbb/main.js'));
});
});
@@ -0,0 +1,51 @@
"use strict";
module.exports = tarjan;
// Adapted from https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm#The_algorithm_in_pseudocode
function tarjan(graph) {
const indices = new Map();
const lowlinks = new Map();
const onStack = new Set();
const stack = [];
const scc = [];
let idx = 0;
function strongConnect(v) {
indices.set(v, idx);
lowlinks.set(v, idx);
idx++;
stack.push(v);
onStack.add(v);
const deps = graph.get(v);
for (const dep of deps) {
if (!indices.has(dep)) {
strongConnect(dep);
lowlinks.set(v, Math.min(lowlinks.get(v), lowlinks.get(dep)));
} else if (onStack.has(dep)) {
lowlinks.set(v, Math.min(lowlinks.get(v), indices.get(dep)));
}
}
if (lowlinks.get(v) === indices.get(v)) {
const vertices = new Set();
let w = null;
while (v !== w) {
w = stack.pop();
onStack.delete(w);
vertices.add(w);
}
scc.push(vertices);
}
}
for (const v of graph.keys()) {
if (!indices.has(v)) {
strongConnect(v);
}
}
return scc;
}
@@ -0,0 +1 @@
{"version":3,"names":["_index","require","buildUndefinedNode","unaryExpression","numericLiteral"],"sources":["../../src/builders/productions.ts"],"sourcesContent":["import { numericLiteral, unaryExpression } from \"./generated/index.ts\";\n\nexport function buildUndefinedNode() {\n return unaryExpression(\"void\", numericLiteral(0), true);\n}\n"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAEO,SAASC,kBAAkBA,CAAA,EAAG;EACnC,OAAO,IAAAC,sBAAe,EAAC,MAAM,EAAE,IAAAC,qBAAc,EAAC,CAAC,CAAC,EAAE,IAAI,CAAC;AACzD","ignoreList":[]}
@@ -0,0 +1,38 @@
# Developer's Certificate of Origin 1.1
By making a contribution to this project, I certify that:
* (a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or
* (b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or
* (c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it.
* (d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
## Moderation Policy
The [Node.js Moderation Policy] applies to this WG.
## Code of Conduct
The [Node.js Code of Conduct][] applies to this WG.
[Node.js Code of Conduct]:
https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md
[Node.js Moderation Policy]:
https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md
@@ -0,0 +1,5 @@
var convert = require('./convert'),
func = convert('isFunction', require('../isFunction'), require('./_falseOptions'));
func.placeholder = require('./placeholder');
module.exports = func;
@@ -0,0 +1 @@
{"name":"why-is-node-running","version":"2.3.0","requiresBuild":false,"files":{"LICENSE":{"checkedAt":1794532092419,"integrity":"sha512-BXo3lvPVbhYP6tnak9LFlEzrz22vZw6CDexP++oggKNsUej1H1tt/Y9o8CdgHbK0+LachBAe7/K5Bxdo2ob7cA==","mode":420,"size":1079},"cli.js":{"checkedAt":1794532092419,"integrity":"sha512-0SkiLD9THlaVi54cm9e/8ueqi+ndVdOGDAd2QSjGnw32I7swc14X5YFs3VtcQJYn+yPbZ/iDGTTmL1Ik/eQskg==","mode":493,"size":441},"example.js":{"checkedAt":1794532092419,"integrity":"sha512-NZLmOseIEh+CACuLtqqbE5fTUzfAv6arETmG/mDCyoFmDaDCsR5nh3Ta3QXnohQJ/j4zXnO0TD25oO1t7beg6w==","mode":420,"size":241},"include.js":{"checkedAt":1794532092419,"integrity":"sha512-sPbd2TfJT6HhCWBJAscZr+ktw7GDXVlwHvL4bjFWIFiQ/fzC+vsqzzZZgrqcMcZZVzJ01TEiuXBkkRfR8baI3A==","mode":420,"size":55},"index.js":{"checkedAt":1794532092420,"integrity":"sha512-9LS1A53/KpG0Qea40Z/l3DoDDxVJ+aBK3coYk8rm/TOcMiyMmkMzGWSUGT27KJsMyogRluuDkgqyoZ1MVt4Fsw==","mode":420,"size":2073},"package.json":{"checkedAt":1794532092420,"integrity":"sha512-YJTCmEQCVpI8Bbaha4zYftuMtY7k7n0Wjwm+3vOjGK/jX3xxCH8KCgkRAotENvNfmZER9On3IZvdmk0RieULuw==","mode":420,"size":855},"README.md":{"checkedAt":1794532092420,"integrity":"sha512-l1xiXsoclj6Bj68lHl4hyjb1sDeDj6Prsi/LASPszadYH3D+Sb79oV8IKffRF2Z/r1BfRXGuRmemH3heFJGi0A==","mode":420,"size":2534},".github/FUNDING.yml":{"checkedAt":1794532092420,"integrity":"sha512-lJUE8HdigKhkMC1Li3oVuDteUdukEY4tPMAeinbiszyH2U9nYZE5FyX/PJB98B5DtJSX61oKogl39Jna5Vo3nw==","mode":420,"size":18}}}
@@ -0,0 +1,26 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2023" />
/// <reference lib="es2024.arraybuffer" />
/// <reference lib="es2024.collection" />
/// <reference lib="es2024.object" />
/// <reference lib="es2024.promise" />
/// <reference lib="es2024.regexp" />
/// <reference lib="es2024.sharedmemory" />
/// <reference lib="es2024.string" />
@@ -0,0 +1,49 @@
import { OB11MessageMixType } from '../../types';
import { ReturnDataType, SendMsgBase, SendMsgPayload } from '../../action/msg/SendMsg';
type GoCQHTTPSendForwardMsgPayload = SendMsgPayload & {
messages?: OB11MessageMixType;
};
export declare class GoCQHTTPSendForwardMsgBase extends SendMsgBase {
protected check(payload: GoCQHTTPSendForwardMsgPayload): Promise<import("../../action/router").BaseCheckResult>;
}
export declare class GoCQHTTPSendForwardMsg extends GoCQHTTPSendForwardMsgBase {
actionName: "send_forward_msg";
actionSummary: string;
actionDescription: string;
actionTags: string[];
payloadExample: {
group_id: string;
messages: never[];
};
returnExample: {
message_id: number;
};
protected check(payload: GoCQHTTPSendForwardMsgPayload): Promise<import("../../action/router").BaseCheckResult>;
}
export declare class GoCQHTTPSendPrivateForwardMsg extends GoCQHTTPSendForwardMsgBase {
actionName: "send_private_forward_msg";
actionSummary: string;
actionTags: string[];
payloadExample: {
user_id: string;
messages: never[];
};
returnExample: {
message_id: number;
};
_handle(payload: GoCQHTTPSendForwardMsgPayload): Promise<ReturnDataType>;
}
export declare class GoCQHTTPSendGroupForwardMsg extends GoCQHTTPSendForwardMsgBase {
actionName: "send_group_forward_msg";
actionSummary: string;
actionTags: string[];
payloadExample: {
group_id: string;
messages: never[];
};
returnExample: {
message_id: number;
};
_handle(payload: GoCQHTTPSendForwardMsgPayload): Promise<ReturnDataType>;
}
export {};
@@ -0,0 +1,68 @@
declare module "ipaddr.js" {
type IPv4Range = 'unicast' | 'unspecified' | 'broadcast' | 'multicast' | 'linkLocal' | 'loopback' | 'carrierGradeNat' | 'private' | 'reserved';
type IPv6Range = 'unicast' | 'unspecified' | 'linkLocal' | 'multicast' | 'loopback' | 'uniqueLocal' | 'ipv4Mapped' | 'rfc6145' | 'rfc6052' | '6to4' | 'teredo' | 'reserved';
interface RangeList<T> {
[name: string]: [T, number] | [T, number][];
}
// Common methods/properties for IPv4 and IPv6 classes.
class IP {
prefixLengthFromSubnetMask(): number | null;
toByteArray(): number[];
toNormalizedString(): string;
toString(): string;
}
namespace Address {
export function isValid(addr: string): boolean;
export function fromByteArray(bytes: number[]): IPv4 | IPv6;
export function parse(addr: string): IPv4 | IPv6;
export function parseCIDR(mask: string): [IPv4 | IPv6, number];
export function process(addr: string): IPv4 | IPv6;
export function subnetMatch(addr: IPv4, rangeList: RangeList<IPv4>, defaultName?: string): string;
export function subnetMatch(addr: IPv6, rangeList: RangeList<IPv6>, defaultName?: string): string;
export class IPv4 extends IP {
static broadcastAddressFromCIDR(addr: string): IPv4;
static isIPv4(addr: string): boolean;
static isValidFourPartDecimal(addr: string): boolean;
static isValid(addr: string): boolean;
static networkAddressFromCIDR(addr: string): IPv4;
static parse(addr: string): IPv4;
static parseCIDR(addr: string): [IPv4, number];
static subnetMaskFromPrefixLength(prefix: number): IPv4;
constructor(octets: number[]);
octets: number[]
kind(): 'ipv4';
match(addr: IPv4, bits: number): boolean;
match(mask: [IPv4, number]): boolean;
range(): IPv4Range;
subnetMatch(rangeList: RangeList<IPv4>, defaultName?: string): string;
toIPv4MappedAddress(): IPv6;
}
export class IPv6 extends IP {
static broadcastAddressFromCIDR(addr: string): IPv6;
static isIPv6(addr: string): boolean;
static isValid(addr: string): boolean;
static parse(addr: string): IPv6;
static parseCIDR(addr: string): [IPv6, number];
static subnetMaskFromPrefixLength(prefix: number): IPv6;
constructor(parts: number[]);
parts: number[]
zoneId?: string
isIPv4MappedAddress(): boolean;
kind(): 'ipv6';
match(addr: IPv6, bits: number): boolean;
match(mask: [IPv6, number]): boolean;
range(): IPv6Range;
subnetMatch(rangeList: RangeList<IPv6>, defaultName?: string): string;
toIPv4Address(): IPv4;
}
}
export = Address;
}
@@ -0,0 +1,38 @@
declare namespace deepEqual {
/**
* Memoization class used to speed up comparison.
*/
class MemoizeMap extends WeakMap<object, MemoizeMap | boolean> {}
interface DeepEqualOptions<T1 = unknown, T2 = unknown> {
/**
* Override default algorithm, determining custom equality.
*/
comparator?: (leftHandOperand: T1, rightHandOperand: T2) => boolean | null;
/**
* Provide a custom memoization object which will cache the results of
* complex objects for a speed boost.
*
* By passing `false` you can disable memoization, but this will cause circular
* references to blow the stack.
*/
memoize?: MemoizeMap | false;
}
}
/**
* Assert deeply nested sameValue equality between two objects of any type.
*
* @param leftHandOperand
* @param rightHandOperand
* @param [options] Additional options
* @return equal match
*/
declare function deepEqual<T1, T2>(
leftHandOperand: T1,
rightHandOperand: T2,
options?: deepEqual.DeepEqualOptions<T1, T2>,
): boolean;
export = deepEqual;
@@ -0,0 +1 @@
{"version":3,"file":"getExtendedConstructorArguments.spec.d.ts","sourceRoot":"","sources":["../../../../src/metadata/calculations/getExtendedConstructorArguments.spec.ts"],"names":[],"mappings":""}
@@ -0,0 +1,47 @@
import { PacketHighwayClient } from '../../packet/highway/client';
import { PacketLogger } from '../../packet/context/loggerContext';
import { PacketMsgFileElement, PacketMsgPicElement, PacketMsgPttElement, PacketMsgVideoElement } from '../../packet/message/element';
import { Peer } from '../../index';
import { NapCoreContext } from '../../packet/context/napCoreContext';
import { PacketClientContext } from '../../packet/context/clientContext';
export declare const BlockSize: number;
interface HighwayServerAddr {
ip: string;
port: number;
}
export interface PacketHighwaySig {
uin: string;
uid: string;
sigSession: Uint8Array | null;
sessionKey: Uint8Array | null;
serverAddr: HighwayServerAddr[];
}
export declare class PacketHighwayContext {
private readonly napcore;
private readonly client;
protected sig: PacketHighwaySig;
protected logger: PacketLogger;
protected hwClient: PacketHighwayClient;
private cachedPrepareReq;
constructor(napcore: NapCoreContext, logger: PacketLogger, client: PacketClientContext);
private checkAvailable;
private prepareUpload;
uploadImage(peer: Peer, img: PacketMsgPicElement): Promise<void>;
uploadVideo(peer: Peer, video: PacketMsgVideoElement): Promise<void>;
/**
* 确保视频缩略图存在,如果不存在则自动生成
* @returns 生成的临时缩略图路径,用于后续清理
*/
private ensureVideoThumb;
uploadPtt(peer: Peer, ptt: PacketMsgPttElement): Promise<void>;
uploadFile(peer: Peer, file: PacketMsgFileElement): Promise<void>;
private uploadGroupImage;
private uploadC2CImage;
private uploadGroupVideo;
private uploadC2CVideo;
private uploadGroupPtt;
private uploadC2CPtt;
private uploadGroupFile;
private uploadC2CFile;
}
export {};
@@ -0,0 +1,35 @@
import crypto from 'crypto'
import { urlAlphabet } from '../url-alphabet/index.js'
let random = bytes =>
new Promise((resolve, reject) => {
crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
if (err) {
reject(err)
} else {
resolve(buf)
}
})
})
let customAlphabet = (alphabet, defaultSize = 21) => {
let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
let tick = (id, size = defaultSize) =>
random(step).then(bytes => {
let i = step
while (i--) {
id += alphabet[bytes[i] & mask] || ''
if (id.length >= size) return id
}
return tick(id, size)
})
return size => tick('', size)
}
let nanoid = (size = 21) =>
random((size |= 0)).then(bytes => {
let id = ''
while (size--) {
id += urlAlphabet[bytes[size] & 63]
}
return id
})
export { nanoid, customAlphabet, random }
@@ -0,0 +1,8 @@
// on windows, either \ or / are valid directory separators.
// on unix, \ is a valid character in filenames.
// so, on windows, and only on windows, we replace all \ chars with /,
// so that we can use / as our one and only directory separator char.
const platform = process.env.TESTING_TAR_FAKE_PLATFORM || process.platform
module.exports = platform !== 'win32' ? p => p
: p => p && p.replace(/\\/g, '/')
@@ -0,0 +1,53 @@
/**
* Copyright (c) 2019 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { ITerminalAddon, IDisposable, Terminal } from '@xterm/xterm';
export interface ILoadedAddon {
instance: ITerminalAddon;
dispose: () => void;
isDisposed: boolean;
}
export class AddonManager implements IDisposable {
protected _addons: ILoadedAddon[] = [];
public dispose(): void {
for (let i = this._addons.length - 1; i >= 0; i--) {
this._addons[i].instance.dispose();
}
}
public loadAddon(terminal: Terminal, instance: ITerminalAddon): void {
const loadedAddon: ILoadedAddon = {
instance,
dispose: instance.dispose,
isDisposed: false
};
this._addons.push(loadedAddon);
instance.dispose = () => this._wrappedAddonDispose(loadedAddon);
instance.activate(terminal as any);
}
private _wrappedAddonDispose(loadedAddon: ILoadedAddon): void {
if (loadedAddon.isDisposed) {
// Do nothing if already disposed
return;
}
let index = -1;
for (let i = 0; i < this._addons.length; i++) {
if (this._addons[i] === loadedAddon) {
index = i;
break;
}
}
if (index === -1) {
throw new Error('Could not dispose an addon that has not been loaded');
}
loadedAddon.isDisposed = true;
loadedAddon.dispose.apply(loadedAddon.instance);
this._addons.splice(index, 1);
}
}
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E wC","132":"A B","388":"F"},B:{"1":"0 1 2 3 4 5 Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I","132":"C L M G N O P"},C:{"1":"0 1 2 3 4 5 wB xB yB zB 0B 1B 2B 3B UC 4B VC 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R WC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I XC MC YC yC zC","16":"xC TC 0C 1C","132":"6 7 8 9 K D E F A B C L M G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB","388":"J ZB"},D:{"1":"0 1 2 3 4 5 kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B UC 4B VC 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I XC MC YC","16":"J ZB K D E F A B C L M","132":"6 7 8 9 G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB"},E:{"1":"B C L M G aC NC OC 7C 8C 9C bC cC PC AD QC dC eC fC gC hC BD RC iC jC kC lC mC CD SC nC oC pC qC rC sC tC DD ED","16":"J ZB K 2C ZC","132":"D E F A 4C 5C 6C","388":"3C"},F:{"1":"0 1 2 3 4 5 CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R WC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z","16":"F B FD GD HD ID NC uC","132":"6 7 8 9 G N O P aB AB BB","516":"C JD OC"},G:{"1":"SD TD UD VD WD XD YD ZD aD bD cD dD bC cC PC eD QC dC eC fC gC hC fD RC iC jC kC lC mC gD SC nC oC pC qC rC sC tC","16":"ZC KD vC LD MD","132":"E ND OD PD QD RD"},H:{"516":"hD"},I:{"1":"I","16":"TC iD jD kD nD","132":"mD","388":"J lD vC"},J:{"16":"D","132":"A"},K:{"1":"H","16":"A B C NC uC","516":"OC"},L:{"1":"I"},M:{"1":"MC"},N:{"132":"A B"},O:{"1":"PC"},P:{"1":"6 7 8 9 J AB BB CB DB EB FB oD pD qD rD sD aC tD uD vD wD xD QC RC SC yD"},Q:{"1":"zD"},R:{"1":"0D"},S:{"1":"2D","132":"1D"}},B:5,C:":indeterminate CSS pseudo-class",D:true};
@@ -0,0 +1,66 @@
import { LogWrapper } from '../../../napcat-core/helper/log';
import { PluginModule, PluginEntry, PluginStatusConfig } from './types';
/**
* 插件加载器
* 负责扫描、加载和导入插件模块
*/
export declare class PluginLoader {
private readonly pluginPath;
private readonly configPath;
private readonly logger;
constructor(pluginPath: string, configPath: string, logger: LogWrapper);
/**
* 加载插件状态配置
*/
loadPluginStatusConfig(): PluginStatusConfig;
/**
* 保存插件状态配置
*/
savePluginStatusConfig(config: PluginStatusConfig): void;
/**
* 扫描插件目录,收集所有有效插件条目(异步版本,验证模块有效性)
* 只有包含有效 plugin_init 函数的插件才会被收集
*/
scanPlugins(): Promise<PluginEntry[]>;
/**
* 扫描单个目录插件
*/
private scanDirectoryPlugin;
/**
* 查找插件目录的入口文件
*/
private findEntryFile;
/**
* 动态导入模块
*/
importModule(filePath: string): Promise<any>;
/**
* 加载插件模块
*/
loadPluginModule(entry: PluginEntry): Promise<PluginModule | null>;
/**
* 检查模块是否为有效的插件模块
*/
isValidPluginModule(module: any): module is PluginModule;
/**
* 验证插件入口文件是否包含有效的 plugin_init 函数
* 用于扫描阶段快速验证
*/
validatePluginEntry(entryPath: string): Promise<{
valid: boolean;
error?: string;
}>;
/**
* 重新扫描单个插件
*/
rescanPlugin(dirname: string): PluginEntry | null;
/**
* 通过 ID 查找插件目录名
*/
findPluginDirById(pluginId: string): string | null;
/**
* 清除插件文件的 require 缓存
* 用于确保卸载插件时清理 CJS 模块缓存
*/
clearCache(pluginPath: string): void;
}
@@ -0,0 +1,6 @@
import {
AlignRightBoldIcon
} from "../chunk-M4HZWITS.mjs";
export {
AlignRightBoldIcon
};
@@ -0,0 +1,941 @@
/**
* @import {Event, Extension, Point, Resolver, State, Token, TokenizeContext, Tokenizer} from 'micromark-util-types'
*/
/**
* @typedef {[number, number, number, number]} Range
* Cell info.
*
* @typedef {0 | 1 | 2 | 3} RowKind
* Where we are: `1` for head row, `2` for delimiter row, `3` for body row.
*/
import {ok as assert} from 'devlop'
import {factorySpace} from 'micromark-factory-space'
import {
markdownLineEnding,
markdownLineEndingOrSpace,
markdownSpace
} from 'micromark-util-character'
import {codes, constants, types} from 'micromark-util-symbol'
import {EditMap} from './edit-map.js'
import {gfmTableAlign} from './infer.js'
/**
* Create an HTML extension for `micromark` to support GitHub tables syntax.
*
* @returns {Extension}
* Extension for `micromark` that can be passed in `extensions` to enable GFM
* table syntax.
*/
export function gfmTable() {
return {
flow: {
null: {name: 'table', tokenize: tokenizeTable, resolveAll: resolveTable}
}
}
}
/**
* @this {TokenizeContext}
* @type {Tokenizer}
*/
function tokenizeTable(effects, ok, nok) {
const self = this
let size = 0
let sizeB = 0
/** @type {boolean | undefined} */
let seen
return start
/**
* Start of a GFM table.
*
* If there is a valid table row or table head before, then we try to parse
* another row.
* Otherwise, we try to parse a head.
*
* ```markdown
* > | | a |
* ^
* | | - |
* > | | b |
* ^
* ```
* @type {State}
*/
function start(code) {
let index = self.events.length - 1
while (index > -1) {
const type = self.events[index][1].type
if (
type === types.lineEnding ||
// Note: markdown-rs uses `whitespace` instead of `linePrefix`
type === types.linePrefix
)
index--
else break
}
const tail = index > -1 ? self.events[index][1].type : null
const next =
tail === 'tableHead' || tail === 'tableRow' ? bodyRowStart : headRowBefore
// Don’t allow lazy body rows.
if (next === bodyRowStart && self.parser.lazy[self.now().line]) {
return nok(code)
}
return next(code)
}
/**
* Before table head row.
*
* ```markdown
* > | | a |
* ^
* | | - |
* | | b |
* ```
*
* @type {State}
*/
function headRowBefore(code) {
effects.enter('tableHead')
effects.enter('tableRow')
return headRowStart(code)
}
/**
* Before table head row, after whitespace.
*
* ```markdown
* > | | a |
* ^
* | | - |
* | | b |
* ```
*
* @type {State}
*/
function headRowStart(code) {
if (code === codes.verticalBar) {
return headRowBreak(code)
}
// To do: micromark-js should let us parse our own whitespace in extensions,
// like `markdown-rs`:
//
// ```js
// // 4+ spaces.
// if (markdownSpace(code)) {
// return nok(code)
// }
// ```
seen = true
// Count the first character, that isn’t a pipe, double.
sizeB += 1
return headRowBreak(code)
}
/**
* At break in table head row.
*
* ```markdown
* > | | a |
* ^
* ^
* ^
* | | - |
* | | b |
* ```
*
* @type {State}
*/
function headRowBreak(code) {
if (code === codes.eof) {
// Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.
return nok(code)
}
if (markdownLineEnding(code)) {
// If anything other than one pipe (ignoring whitespace) was used, it’s fine.
if (sizeB > 1) {
sizeB = 0
// To do: check if this works.
// Feel free to interrupt:
self.interrupt = true
effects.exit('tableRow')
effects.enter(types.lineEnding)
effects.consume(code)
effects.exit(types.lineEnding)
return headDelimiterStart
}
// Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.
return nok(code)
}
if (markdownSpace(code)) {
// To do: check if this is fine.
// effects.attempt(State::Next(StateName::GfmTableHeadRowBreak), State::Nok)
// State::Retry(space_or_tab(tokenizer))
return factorySpace(effects, headRowBreak, types.whitespace)(code)
}
sizeB += 1
if (seen) {
seen = false
// Header cell count.
size += 1
}
if (code === codes.verticalBar) {
effects.enter('tableCellDivider')
effects.consume(code)
effects.exit('tableCellDivider')
// Whether a delimiter was seen.
seen = true
return headRowBreak
}
// Anything else is cell data.
effects.enter(types.data)
return headRowData(code)
}
/**
* In table head row data.
*
* ```markdown
* > | | a |
* ^
* | | - |
* | | b |
* ```
*
* @type {State}
*/
function headRowData(code) {
if (
code === codes.eof ||
code === codes.verticalBar ||
markdownLineEndingOrSpace(code)
) {
effects.exit(types.data)
return headRowBreak(code)
}
effects.consume(code)
return code === codes.backslash ? headRowEscape : headRowData
}
/**
* In table head row escape.
*
* ```markdown
* > | | a\-b |
* ^
* | | ---- |
* | | c |
* ```
*
* @type {State}
*/
function headRowEscape(code) {
if (code === codes.backslash || code === codes.verticalBar) {
effects.consume(code)
return headRowData
}
return headRowData(code)
}
/**
* Before delimiter row.
*
* ```markdown
* | | a |
* > | | - |
* ^
* | | b |
* ```
*
* @type {State}
*/
function headDelimiterStart(code) {
// Reset `interrupt`.
self.interrupt = false
// Note: in `markdown-rs`, we need to handle piercing here too.
if (self.parser.lazy[self.now().line]) {
return nok(code)
}
effects.enter('tableDelimiterRow')
// Track if we’ve seen a `:` or `|`.
seen = false
if (markdownSpace(code)) {
assert(self.parser.constructs.disable.null, 'expected `disabled.null`')
return factorySpace(
effects,
headDelimiterBefore,
types.linePrefix,
self.parser.constructs.disable.null.includes('codeIndented')
? undefined
: constants.tabSize
)(code)
}
return headDelimiterBefore(code)
}
/**
* Before delimiter row, after optional whitespace.
*
* Reused when a `|` is found later, to parse another cell.
*
* ```markdown
* | | a |
* > | | - |
* ^
* | | b |
* ```
*
* @type {State}
*/
function headDelimiterBefore(code) {
if (code === codes.dash || code === codes.colon) {
return headDelimiterValueBefore(code)
}
if (code === codes.verticalBar) {
seen = true
// If we start with a pipe, we open a cell marker.
effects.enter('tableCellDivider')
effects.consume(code)
effects.exit('tableCellDivider')
return headDelimiterCellBefore
}
// More whitespace / empty row not allowed at start.
return headDelimiterNok(code)
}
/**
* After `|`, before delimiter cell.
*
* ```markdown
* | | a |
* > | | - |
* ^
* ```
*
* @type {State}
*/
function headDelimiterCellBefore(code) {
if (markdownSpace(code)) {
return factorySpace(
effects,
headDelimiterValueBefore,
types.whitespace
)(code)
}
return headDelimiterValueBefore(code)
}
/**
* Before delimiter cell value.
*
* ```markdown
* | | a |
* > | | - |
* ^
* ```
*
* @type {State}
*/
function headDelimiterValueBefore(code) {
// Align: left.
if (code === codes.colon) {
sizeB += 1
seen = true
effects.enter('tableDelimiterMarker')
effects.consume(code)
effects.exit('tableDelimiterMarker')
return headDelimiterLeftAlignmentAfter
}
// Align: none.
if (code === codes.dash) {
sizeB += 1
// To do: seems weird that this *isn’t* left aligned, but that state is used?
return headDelimiterLeftAlignmentAfter(code)
}
if (code === codes.eof || markdownLineEnding(code)) {
return headDelimiterCellAfter(code)
}
return headDelimiterNok(code)
}
/**
* After delimiter cell left alignment marker.
*
* ```markdown
* | | a |
* > | | :- |
* ^
* ```
*
* @type {State}
*/
function headDelimiterLeftAlignmentAfter(code) {
if (code === codes.dash) {
effects.enter('tableDelimiterFiller')
return headDelimiterFiller(code)
}
// Anything else is not ok after the left-align colon.
return headDelimiterNok(code)
}
/**
* In delimiter cell filler.
*
* ```markdown
* | | a |
* > | | - |
* ^
* ```
*
* @type {State}
*/
function headDelimiterFiller(code) {
if (code === codes.dash) {
effects.consume(code)
return headDelimiterFiller
}
// Align is `center` if it was `left`, `right` otherwise.
if (code === codes.colon) {
seen = true
effects.exit('tableDelimiterFiller')
effects.enter('tableDelimiterMarker')
effects.consume(code)
effects.exit('tableDelimiterMarker')
return headDelimiterRightAlignmentAfter
}
effects.exit('tableDelimiterFiller')
return headDelimiterRightAlignmentAfter(code)
}
/**
* After delimiter cell right alignment marker.
*
* ```markdown
* | | a |
* > | | -: |
* ^
* ```
*
* @type {State}
*/
function headDelimiterRightAlignmentAfter(code) {
if (markdownSpace(code)) {
return factorySpace(
effects,
headDelimiterCellAfter,
types.whitespace
)(code)
}
return headDelimiterCellAfter(code)
}
/**
* After delimiter cell.
*
* ```markdown
* | | a |
* > | | -: |
* ^
* ```
*
* @type {State}
*/
function headDelimiterCellAfter(code) {
if (code === codes.verticalBar) {
return headDelimiterBefore(code)
}
if (code === codes.eof || markdownLineEnding(code)) {
// Exit when:
// * there was no `:` or `|` at all (it’s a thematic break or setext
// underline instead)
// * the header cell count is not the delimiter cell count
if (!seen || size !== sizeB) {
return headDelimiterNok(code)
}
// Note: in markdown-rs`, a reset is needed here.
effects.exit('tableDelimiterRow')
effects.exit('tableHead')
// To do: in `markdown-rs`, resolvers need to be registered manually.
// effects.register_resolver(ResolveName::GfmTable)
return ok(code)
}
return headDelimiterNok(code)
}
/**
* In delimiter row, at a disallowed byte.
*
* ```markdown
* | | a |
* > | | x |
* ^
* ```
*
* @type {State}
*/
function headDelimiterNok(code) {
// Note: in `markdown-rs`, we need to reset, in `micromark-js` we don‘t.
return nok(code)
}
/**
* Before table body row.
*
* ```markdown
* | | a |
* | | - |
* > | | b |
* ^
* ```
*
* @type {State}
*/
function bodyRowStart(code) {
// Note: in `markdown-rs` we need to manually take care of a prefix,
// but in `micromark-js` that is done for us, so if we’re here, we’re
// never at whitespace.
effects.enter('tableRow')
return bodyRowBreak(code)
}
/**
* At break in table body row.
*
* ```markdown
* | | a |
* | | - |
* > | | b |
* ^
* ^
* ^
* ```
*
* @type {State}
*/
function bodyRowBreak(code) {
if (code === codes.verticalBar) {
effects.enter('tableCellDivider')
effects.consume(code)
effects.exit('tableCellDivider')
return bodyRowBreak
}
if (code === codes.eof || markdownLineEnding(code)) {
effects.exit('tableRow')
return ok(code)
}
if (markdownSpace(code)) {
return factorySpace(effects, bodyRowBreak, types.whitespace)(code)
}
// Anything else is cell content.
effects.enter(types.data)
return bodyRowData(code)
}
/**
* In table body row data.
*
* ```markdown
* | | a |
* | | - |
* > | | b |
* ^
* ```
*
* @type {State}
*/
function bodyRowData(code) {
if (
code === codes.eof ||
code === codes.verticalBar ||
markdownLineEndingOrSpace(code)
) {
effects.exit(types.data)
return bodyRowBreak(code)
}
effects.consume(code)
return code === codes.backslash ? bodyRowEscape : bodyRowData
}
/**
* In table body row escape.
*
* ```markdown
* | | a |
* | | ---- |
* > | | b\-c |
* ^
* ```
*
* @type {State}
*/
function bodyRowEscape(code) {
if (code === codes.backslash || code === codes.verticalBar) {
effects.consume(code)
return bodyRowData
}
return bodyRowData(code)
}
}
/** @type {Resolver} */
function resolveTable(events, context) {
let index = -1
let inFirstCellAwaitingPipe = true
/** @type {RowKind} */
let rowKind = 0
/** @type {Range} */
let lastCell = [0, 0, 0, 0]
/** @type {Range} */
let cell = [0, 0, 0, 0]
let afterHeadAwaitingFirstBodyRow = false
let lastTableEnd = 0
/** @type {Token | undefined} */
let currentTable
/** @type {Token | undefined} */
let currentBody
/** @type {Token | undefined} */
let currentCell
const map = new EditMap()
while (++index < events.length) {
const event = events[index]
const token = event[1]
if (event[0] === 'enter') {
// Start of head.
if (token.type === 'tableHead') {
afterHeadAwaitingFirstBodyRow = false
// Inject previous (body end and) table end.
if (lastTableEnd !== 0) {
assert(currentTable, 'there should be a table opening')
flushTableEnd(map, context, lastTableEnd, currentTable, currentBody)
currentBody = undefined
lastTableEnd = 0
}
// Inject table start.
currentTable = {
type: 'table',
start: Object.assign({}, token.start),
// Note: correct end is set later.
end: Object.assign({}, token.end)
}
map.add(index, 0, [['enter', currentTable, context]])
} else if (
token.type === 'tableRow' ||
token.type === 'tableDelimiterRow'
) {
inFirstCellAwaitingPipe = true
currentCell = undefined
lastCell = [0, 0, 0, 0]
cell = [0, index + 1, 0, 0]
// Inject table body start.
if (afterHeadAwaitingFirstBodyRow) {
afterHeadAwaitingFirstBodyRow = false
currentBody = {
type: 'tableBody',
start: Object.assign({}, token.start),
// Note: correct end is set later.
end: Object.assign({}, token.end)
}
map.add(index, 0, [['enter', currentBody, context]])
}
rowKind = token.type === 'tableDelimiterRow' ? 2 : currentBody ? 3 : 1
}
// Cell data.
else if (
rowKind &&
(token.type === types.data ||
token.type === 'tableDelimiterMarker' ||
token.type === 'tableDelimiterFiller')
) {
inFirstCellAwaitingPipe = false
// First value in cell.
if (cell[2] === 0) {
if (lastCell[1] !== 0) {
cell[0] = cell[1]
currentCell = flushCell(
map,
context,
lastCell,
rowKind,
undefined,
currentCell
)
lastCell = [0, 0, 0, 0]
}
cell[2] = index
}
} else if (token.type === 'tableCellDivider') {
if (inFirstCellAwaitingPipe) {
inFirstCellAwaitingPipe = false
} else {
if (lastCell[1] !== 0) {
cell[0] = cell[1]
currentCell = flushCell(
map,
context,
lastCell,
rowKind,
undefined,
currentCell
)
}
lastCell = cell
cell = [lastCell[1], index, 0, 0]
}
}
}
// Exit events.
else if (token.type === 'tableHead') {
afterHeadAwaitingFirstBodyRow = true
lastTableEnd = index
} else if (
token.type === 'tableRow' ||
token.type === 'tableDelimiterRow'
) {
lastTableEnd = index
if (lastCell[1] !== 0) {
cell[0] = cell[1]
currentCell = flushCell(
map,
context,
lastCell,
rowKind,
index,
currentCell
)
} else if (cell[1] !== 0) {
currentCell = flushCell(map, context, cell, rowKind, index, currentCell)
}
rowKind = 0
} else if (
rowKind &&
(token.type === types.data ||
token.type === 'tableDelimiterMarker' ||
token.type === 'tableDelimiterFiller')
) {
cell[3] = index
}
}
if (lastTableEnd !== 0) {
assert(currentTable, 'expected table opening')
flushTableEnd(map, context, lastTableEnd, currentTable, currentBody)
}
map.consume(context.events)
// To do: move this into `html`, when events are exposed there.
// That’s what `markdown-rs` does.
// That needs updates to `mdast-util-gfm-table`.
index = -1
while (++index < context.events.length) {
const event = context.events[index]
if (event[0] === 'enter' && event[1].type === 'table') {
event[1]._align = gfmTableAlign(context.events, index)
}
}
return events
}
/**
* Generate a cell.
*
* @param {EditMap} map
* @param {Readonly<TokenizeContext>} context
* @param {Readonly<Range>} range
* @param {RowKind} rowKind
* @param {number | undefined} rowEnd
* @param {Token | undefined} previousCell
* @returns {Token | undefined}
*/
// eslint-disable-next-line max-params
function flushCell(map, context, range, rowKind, rowEnd, previousCell) {
// `markdown-rs` uses:
// rowKind === 2 ? 'tableDelimiterCell' : 'tableCell'
const groupName =
rowKind === 1
? 'tableHeader'
: rowKind === 2
? 'tableDelimiter'
: 'tableData'
// `markdown-rs` uses:
// rowKind === 2 ? 'tableDelimiterCellValue' : 'tableCellText'
const valueName = 'tableContent'
// Insert an exit for the previous cell, if there is one.
//
// ```markdown
// > | | aa | bb | cc |
// ^-- exit
// ^^^^-- this cell
// ```
if (range[0] !== 0) {
assert(previousCell, 'expected previous cell enter')
previousCell.end = Object.assign({}, getPoint(context.events, range[0]))
map.add(range[0], 0, [['exit', previousCell, context]])
}
// Insert enter of this cell.
//
// ```markdown
// > | | aa | bb | cc |
// ^-- enter
// ^^^^-- this cell
// ```
const now = getPoint(context.events, range[1])
previousCell = {
type: groupName,
start: Object.assign({}, now),
// Note: correct end is set later.
end: Object.assign({}, now)
}
map.add(range[1], 0, [['enter', previousCell, context]])
// Insert text start at first data start and end at last data end, and
// remove events between.
//
// ```markdown
// > | | aa | bb | cc |
// ^-- enter
// ^-- exit
// ^^^^-- this cell
// ```
if (range[2] !== 0) {
const relatedStart = getPoint(context.events, range[2])
const relatedEnd = getPoint(context.events, range[3])
/** @type {Token} */
const valueToken = {
type: valueName,
start: Object.assign({}, relatedStart),
end: Object.assign({}, relatedEnd)
}
map.add(range[2], 0, [['enter', valueToken, context]])
assert(range[3] !== 0)
if (rowKind !== 2) {
// Fix positional info on remaining events
const start = context.events[range[2]]
const end = context.events[range[3]]
start[1].end = Object.assign({}, end[1].end)
start[1].type = types.chunkText
start[1].contentType = constants.contentTypeText
// Remove if needed.
if (range[3] > range[2] + 1) {
const a = range[2] + 1
const b = range[3] - range[2] - 1
map.add(a, b, [])
}
}
map.add(range[3] + 1, 0, [['exit', valueToken, context]])
}
// Insert an exit for the last cell, if at the row end.
//
// ```markdown
// > | | aa | bb | cc |
// ^-- exit
// ^^^^^^-- this cell (the last one contains two “between” parts)
// ```
if (rowEnd !== undefined) {
previousCell.end = Object.assign({}, getPoint(context.events, rowEnd))
map.add(rowEnd, 0, [['exit', previousCell, context]])
previousCell = undefined
}
return previousCell
}
/**
* Generate table end (and table body end).
*
* @param {Readonly<EditMap>} map
* @param {Readonly<TokenizeContext>} context
* @param {number} index
* @param {Token} table
* @param {Token | undefined} tableBody
*/
// eslint-disable-next-line max-params
function flushTableEnd(map, context, index, table, tableBody) {
/** @type {Array<Event>} */
const exits = []
const related = getPoint(context.events, index)
if (tableBody) {
tableBody.end = Object.assign({}, related)
exits.push(['exit', tableBody, context])
}
table.end = Object.assign({}, related)
exits.push(['exit', table, context])
map.add(index + 1, 0, exits)
}
/**
* @param {Readonly<Array<Event>>} events
* @param {number} index
* @returns {Readonly<Point>}
*/
function getPoint(events, index) {
const event = events[index]
const side = event[0] === 'enter' ? 'start' : 'end'
return event[1][side]
}
@@ -0,0 +1,52 @@
{
"name": "winston-transport",
"description": "Base stream implementations for winston@3 and up.",
"version": "4.9.0",
"main": "index.js",
"browser": "dist/index.js",
"scripts": {
"lint": "ESLINT_USE_FLAT_CONFIG=false eslint test/*.js index.js --resolve-plugins-relative-to ./node_modules/@dabh/eslint-config-populist",
"pretest": "npm run lint && npm run build",
"test": "nyc mocha test/*.test.js",
"report": "nyc report --reporter=lcov",
"build": "rimraf dist && babel *.js -d ./dist",
"prepublishOnly": "npm run build"
},
"repository": {
"type": "git",
"url": "git@github.com:winstonjs/winston-transport.git"
},
"keywords": [
"winston",
"transport",
"winston3"
],
"author": "Charlie Robbins <charlie.robbins@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/winstonjs/winston-transport/issues"
},
"homepage": "https://github.com/winstonjs/winston-transport#readme",
"dependencies": {
"logform": "^2.7.0",
"readable-stream": "^3.6.2",
"triple-beam": "^1.3.0"
},
"devDependencies": {
"@types/node": "^22.6.0",
"abstract-winston-transport": ">=0.5.1",
"assume": "^2.3.0",
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"deep-equal": "^2.0.5",
"eslint": "^9.6.0",
"@dabh/eslint-config-populist": "^4.4.0",
"mocha": "^10.6.0",
"nyc": "^17.0.0",
"rimraf": "^6.0.1",
"winston-compat": "^0.1.5"
},
"engines": {
"node": ">= 12.0.0"
}
}
@@ -0,0 +1,18 @@
'use strict';
var AddEntriesFromIterable = require('es-abstract/2024/AddEntriesFromIterable');
var CreateDataPropertyOrThrow = require('es-abstract/2024/CreateDataPropertyOrThrow');
var RequireObjectCoercible = require('es-object-atoms/RequireObjectCoercible');
var ToPropertyKey = require('es-abstract/2024/ToPropertyKey');
var adder = function addDataProperty(key, value) {
var O = this; // eslint-disable-line no-invalid-this
var propertyKey = ToPropertyKey(key);
CreateDataPropertyOrThrow(O, propertyKey, value);
};
module.exports = function fromEntries(iterable) {
RequireObjectCoercible(iterable);
return AddEntriesFromIterable({}, iterable, adder);
};
@@ -0,0 +1,111 @@
{
"name": "array.prototype.findlast",
"version": "1.2.5",
"description": "An ESnext spec-compliant `Array.prototype.findLast` shim/polyfill/replacement that works as far down as ES3.",
"author": {
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"contributors": [
{
"name": "Jordan Harband",
"email": "ljharb@gmail.com",
"url": "http://ljharb.codes"
}
],
"license": "MIT",
"bugs": {
"url": "https://github.com/es-shims/Array.prototype.findLast/issues"
},
"homepage": "https://github.com/es-shims/Array.prototype.findLast#readme",
"main": "index.js",
"exports": {
".": "./index.js",
"./auto": "./auto.js",
"./polyfill": "./polyfill.js",
"./implementation": "./implementation.js",
"./shim": "./shim.js",
"./package.json": "./package.json"
},
"scripts": {
"prepack": "npmignore --auto --commentLines=autogenerated",
"prepublishOnly": "safe-publish-latest",
"prepublish": "not-in-publish || npm run prepublishOnly",
"pretest": "npm run --silent lint && evalmd README.md",
"posttest": "aud --production",
"tests-only": "nyc tape 'test/**/*.js'",
"test": "npm run tests-only",
"lint": "eslint --ext=js,mjs .",
"postlint": "es-shim-api --bound",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git+https://github.com/es-shims/Array.prototype.findLast.git"
},
"keywords": [
"Array.prototype.findLast",
"find",
"findLast",
"array",
"ESnext",
"shim",
"polyfill",
"last",
"es-shim API"
],
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1",
"es-abstract": "^1.23.2",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.0.0",
"es-shim-unscopables": "^1.0.2"
},
"devDependencies": {
"@es-shims/api": "^2.4.2",
"@ljharb/eslint-config": "^21.1.0",
"aud": "^2.0.4",
"auto-changelog": "^2.4.0",
"es-value-fixtures": "^1.4.2",
"eslint": "=8.8.0",
"evalmd": "^0.0.19",
"for-each": "^0.3.3",
"globalthis": "^1.0.3",
"has-strict-mode": "^1.0.1",
"hasown": "^2.0.2",
"in-publish": "^2.0.1",
"npmignore": "^0.3.1",
"nyc": "^10.3.2",
"object-inspect": "^1.13.1",
"safe-publish-latest": "^2.0.0",
"tape": "^5.7.5"
},
"testling": {
"files": [
"test/index.js",
"test/shimmed.js"
]
},
"engines": {
"node": ">= 0.4"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
},
"publishConfig": {
"ignore": [
".github/workflows"
]
}
}
@@ -0,0 +1,150 @@
/*!
* is-glob <https://github.com/jonschlinkert/is-glob>
*
* Copyright (c) 2014-2017, Jon Schlinkert.
* Released under the MIT License.
*/
var isExtglob = require('is-extglob');
var chars = { '{': '}', '(': ')', '[': ']'};
var strictCheck = function(str) {
if (str[0] === '!') {
return true;
}
var index = 0;
var pipeIndex = -2;
var closeSquareIndex = -2;
var closeCurlyIndex = -2;
var closeParenIndex = -2;
var backSlashIndex = -2;
while (index < str.length) {
if (str[index] === '*') {
return true;
}
if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) {
return true;
}
if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') {
if (closeSquareIndex < index) {
closeSquareIndex = str.indexOf(']', index);
}
if (closeSquareIndex > index) {
if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
return true;
}
backSlashIndex = str.indexOf('\\', index);
if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) {
return true;
}
}
}
if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') {
closeCurlyIndex = str.indexOf('}', index);
if (closeCurlyIndex > index) {
backSlashIndex = str.indexOf('\\', index);
if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) {
return true;
}
}
}
if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') {
closeParenIndex = str.indexOf(')', index);
if (closeParenIndex > index) {
backSlashIndex = str.indexOf('\\', index);
if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
return true;
}
}
}
if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') {
if (pipeIndex < index) {
pipeIndex = str.indexOf('|', index);
}
if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') {
closeParenIndex = str.indexOf(')', pipeIndex);
if (closeParenIndex > pipeIndex) {
backSlashIndex = str.indexOf('\\', pipeIndex);
if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) {
return true;
}
}
}
}
if (str[index] === '\\') {
var open = str[index + 1];
index += 2;
var close = chars[open];
if (close) {
var n = str.indexOf(close, index);
if (n !== -1) {
index = n + 1;
}
}
if (str[index] === '!') {
return true;
}
} else {
index++;
}
}
return false;
};
var relaxedCheck = function(str) {
if (str[0] === '!') {
return true;
}
var index = 0;
while (index < str.length) {
if (/[*?{}()[\]]/.test(str[index])) {
return true;
}
if (str[index] === '\\') {
var open = str[index + 1];
index += 2;
var close = chars[open];
if (close) {
var n = str.indexOf(close, index);
if (n !== -1) {
index = n + 1;
}
}
if (str[index] === '!') {
return true;
}
} else {
index++;
}
}
return false;
};
module.exports = function isGlob(str, options) {
if (typeof str !== 'string' || str === '') {
return false;
}
if (isExtglob(str)) {
return true;
}
var check = strictCheck;
// optionally relax check
if (options && options.strict === false) {
check = relaxedCheck;
}
return check(str);
};
@@ -0,0 +1,32 @@
{
"author": "Tim Koschützki <tim@debuggable.com> (http://debuggable.com/)",
"name": "retry",
"description": "Abstraction for exponential and custom retry strategies for failed operations.",
"license": "MIT",
"version": "0.12.0",
"homepage": "https://github.com/tim-kos/node-retry",
"repository": {
"type": "git",
"url": "git://github.com/tim-kos/node-retry.git"
},
"directories": {
"lib": "./lib"
},
"main": "index",
"engines": {
"node": ">= 4"
},
"dependencies": {},
"devDependencies": {
"fake": "0.2.0",
"istanbul": "^0.4.5",
"tape": "^4.8.0"
},
"scripts": {
"test": "./node_modules/.bin/istanbul cover ./node_modules/tape/bin/tape ./test/integration/*.js",
"release:major": "env SEMANTIC=major npm run release",
"release:minor": "env SEMANTIC=minor npm run release",
"release:patch": "env SEMANTIC=patch npm run release",
"release": "npm version ${SEMANTIC:-patch} -m \"Release %s\" && git push && git push --tags && npm publish"
}
}
@@ -0,0 +1,3 @@
declare const _exports: import('eslint').Rule.RuleModule;
export = _exports;
//# sourceMappingURL=no-is-mounted.d.ts.map
@@ -0,0 +1,43 @@
import {useLocale as $18f2051aff69b9bf$export$43bb16f9c6d9e3f7} from "./context.module.js";
import {MessageDictionary as $eZWU1$MessageDictionary, MessageFormatter as $eZWU1$MessageFormatter} from "@internationalized/message";
import {useMemo as $eZWU1$useMemo, useCallback as $eZWU1$useCallback} from "react";
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
const $321bc95feeb923dd$var$cache = new WeakMap();
function $321bc95feeb923dd$var$getCachedDictionary(strings) {
let dictionary = $321bc95feeb923dd$var$cache.get(strings);
if (!dictionary) {
dictionary = new (0, $eZWU1$MessageDictionary)(strings);
$321bc95feeb923dd$var$cache.set(strings, dictionary);
}
return dictionary;
}
function $321bc95feeb923dd$export$ec23bf898b1eed85(strings) {
let { locale: locale } = (0, $18f2051aff69b9bf$export$43bb16f9c6d9e3f7)();
let dictionary = (0, $eZWU1$useMemo)(()=>$321bc95feeb923dd$var$getCachedDictionary(strings), [
strings
]);
let formatter = (0, $eZWU1$useMemo)(()=>new (0, $eZWU1$MessageFormatter)(locale, dictionary), [
locale,
dictionary
]);
return (0, $eZWU1$useCallback)((key, variables)=>formatter.format(key, variables), [
formatter
]);
}
export {$321bc95feeb923dd$export$ec23bf898b1eed85 as useMessageFormatter};
//# sourceMappingURL=useMessageFormatter.module.js.map
@@ -0,0 +1 @@
{"mappings":";;AAAA;;;;;;;;;;CAUC;AAMD;;CAEC,GACD,MAAM,mDAA6B,MAAM,WAAW;AA2B7C,SAAS,0CAAc,OAA8B;IAC1D,IAAI,oBAAC,gBAAgB,oBAAE,gBAAgB,gBAAE,YAAY,EAAC,GAAG;IACzD,IAAI,QAAQ,CAAA,GAAA,aAAK,EAAwE;QACvF,QAAQ;QACR,SAAS;IACX,GAAG,OAAO;IAEV,IAAI,YAAY,CAAC;QACf,IAAI,YAAY,sCAAgB,EAAE,GAAG;QACrC,IAAI,CAAC,aAAa,EAAE,OAAO,IAAI,EAAE,OAAO,IAAI,CAAC,EAAE,aAAa,CAAC,QAAQ,CAAC,EAAE,MAAM,KAAqB,MAAM,MAAM,CAAC,MAAM,KAAK,KAAK,cAAc,KAC5I;QAGF,8EAA8E;QAC9E,8EAA8E;QAC9E,+EAA+E;QAC/E,4EAA4E;QAC5E,IAAI,cAAc,OAAO,MAAM,MAAM,CAAC,IAAI,GAAG,MAAM,GAAG,GAAG;YACvD,EAAE,cAAc;YAChB,IAAI,CAAE,CAAA,yBAAyB,CAAA,GAC7B,EAAE,eAAe;QAErB;QAEA,MAAM,MAAM,IAAI;QAEhB,IAAI,iBAAiB,eAAe,IAAI,MAAM;YAC5C,2CAA2C;YAC3C,+FAA+F;YAC/F,IAAI,MAAM,iBAAiB,eAAe,CAAC,MAAM,MAAM,EAAE,iBAAiB,UAAU;YAEpF,wCAAwC;YACxC,IAAI,OAAO,MACT,MAAM,iBAAiB,eAAe,CAAC,MAAM,MAAM;YAGrD,IAAI,OAAO,MAAM;gBACf,iBAAiB,aAAa,CAAC;gBAC/B,IAAI,cACF,aAAa;YAEjB;QACF;QAEA,aAAa,MAAM,OAAO;QAC1B,MAAM,OAAO,GAAG,WAAW;YACzB,MAAM,MAAM,GAAG;QACjB,GAAG;IACL;IAEA,OAAO;QACL,iBAAiB;YACf,+DAA+D;YAC/D,qDAAqD;YACrD,kBAAkB,iBAAiB,eAAe,GAAG,YAAY;QACnE;IACF;AACF;AAEA,SAAS,sCAAgB,GAAW;IAClC,mDAAmD;IACnD,+DAA+D;IAC/D,6BAA6B;IAC7B,0CAA0C;IAC1C,IAAI,IAAI,MAAM,KAAK,KAAK,CAAC,UAAU,IAAI,CAAC,MACtC,OAAO;IAGT,OAAO;AACT","sources":["packages/@react-aria/selection/src/useTypeSelect.ts"],"sourcesContent":["/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {DOMAttributes, Key, KeyboardDelegate} from '@react-types/shared';\nimport {KeyboardEvent, useRef} from 'react';\nimport {MultipleSelectionManager} from '@react-stately/selection';\n\n/**\n * Controls how long to wait before clearing the typeahead buffer.\n */\nconst TYPEAHEAD_DEBOUNCE_WAIT_MS = 1000; // 1 second\n\nexport interface AriaTypeSelectOptions {\n /**\n * A delegate that returns collection item keys with respect to visual layout.\n */\n keyboardDelegate: KeyboardDelegate,\n /**\n * An interface for reading and updating multiple selection state.\n */\n selectionManager: MultipleSelectionManager,\n /**\n * Called when an item is focused by typing.\n */\n onTypeSelect?: (key: Key) => void\n}\n\nexport interface TypeSelectAria {\n /**\n * Props to be spread on the owner of the options.\n */\n typeSelectProps: DOMAttributes\n}\n\n/**\n * Handles typeahead interactions with collections.\n */\nexport function useTypeSelect(options: AriaTypeSelectOptions): TypeSelectAria {\n let {keyboardDelegate, selectionManager, onTypeSelect} = options;\n let state = useRef<{search: string, timeout: ReturnType<typeof setTimeout> | undefined}>({\n search: '',\n timeout: undefined\n }).current;\n\n let onKeyDown = (e: KeyboardEvent) => {\n let character = getStringForKey(e.key);\n if (!character || e.ctrlKey || e.metaKey || !e.currentTarget.contains(e.target as HTMLElement) || (state.search.length === 0 && character === ' ')) {\n return;\n }\n\n // Do not propagate the Spacebar event if it's meant to be part of the search.\n // When we time out, the search term becomes empty, hence the check on length.\n // Trimming is to account for the case of pressing the Spacebar more than once,\n // which should cycle through the selection/deselection of the focused item.\n if (character === ' ' && state.search.trim().length > 0) {\n e.preventDefault();\n if (!('continuePropagation' in e)) {\n e.stopPropagation();\n }\n }\n\n state.search += character;\n\n if (keyboardDelegate.getKeyForSearch != null) {\n // Use the delegate to find a key to focus.\n // Prioritize items after the currently focused item, falling back to searching the whole list.\n let key = keyboardDelegate.getKeyForSearch(state.search, selectionManager.focusedKey);\n\n // If no key found, search from the top.\n if (key == null) {\n key = keyboardDelegate.getKeyForSearch(state.search);\n }\n\n if (key != null) {\n selectionManager.setFocusedKey(key);\n if (onTypeSelect) {\n onTypeSelect(key);\n }\n }\n }\n\n clearTimeout(state.timeout);\n state.timeout = setTimeout(() => {\n state.search = '';\n }, TYPEAHEAD_DEBOUNCE_WAIT_MS);\n };\n\n return {\n typeSelectProps: {\n // Using a capturing listener to catch the keydown event before\n // other hooks in order to handle the Spacebar event.\n onKeyDownCapture: keyboardDelegate.getKeyForSearch ? onKeyDown : undeLine truncated
@@ -0,0 +1,24 @@
// Copyright 2017 Lovell Fuller and others.
// SPDX-License-Identifier: Apache-2.0
'use strict';
const isLinux = () => process.platform === 'linux';
let report = null;
const getReport = () => {
if (!report) {
/* istanbul ignore next */
if (isLinux() && process.report) {
const orig = process.report.excludeNetwork;
process.report.excludeNetwork = true;
report = process.report.getReport();
process.report.excludeNetwork = orig;
} else {
report = {};
}
}
return report;
};
module.exports = { isLinux, getReport };
@@ -0,0 +1,265 @@
# socks examples
## Example for SOCKS 'connect' command
The connect command is the most common use-case for a SOCKS proxy. This establishes a direct connection to a destination host through a proxy server. The destination host only has knowledge of the proxy server connecting to it and does not know about the origin client (you).
**Origin Client (you) <-> Proxy Server <-> Destination Server**
In this example, we are connecting to a web server on port 80, and sending a very basic HTTP request to receive a response. It's worth noting that there are many socks-http-agents that can be used with the node http module (and libraries such as request.js) to make this easier. This HTTP request is used as a simple example.
The 'connect' command can be used via the SocksClient.createConnection() factory function as well as by creating a SocksClient instance and using event handlers.
### Using createConnection with async/await
Since SocksClient.createConnection returns a Promise, we can easily use async/await for flow control.
```typescript
import { SocksClient, SocksClientOptions } from 'socks';
const options: SocksClientOptions = {
proxy: {
host: '104.131.124.203',
port: 1081,
type: 5
},
destination: {
host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5.
port: 80
},
command: 'connect'
};
async function start() {
try {
const info = await SocksClient.createConnection(options);
console.log(info.socket);
// <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy servers)
info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n');
info.socket.on('data', (data) => {
console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you).
/*
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Date: Sun, 24 Dec 2017 03:47:51 GMT
Content-Length: 300
{
"as":"AS14061 Digital Ocean, Inc.",
"city":"Clifton",
"country":"United States",
"countryCode":"US",
"isp":"Digital Ocean",
"lat":40.8326,
"lon":-74.1307,
"org":"Digital Ocean",
"query":"104.131.124.203",
"region":"NJ",
"regionName":"New Jersey",
"status":"success",
"timezone":"America/New_York",
"zip":"07014"
}
*/
});
} catch (err) {
// Handle errors
}
}
start();
```
### Using createConnection with Promises
```typescript
import { SocksClient, SocksClientOptions } from 'socks';
const options: SocksClientOptions = {
proxy: {
ipaddress: '104.131.124.203',
port: 1081,
type: 5
},
destination: {
host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5.
port: 80
},
command: 'connect'
};
SocksClient.createConnection(options)
.then(info => {
console.log(info.socket);
// <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy servers)
info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n');
info.socket.on('data', (data) => {
console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you).
/*
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Date: Sun, 24 Dec 2017 03:47:51 GMT
Content-Length: 300
{
"as":"AS14061 Digital Ocean, Inc.",
"city":"Clifton",
"country":"United States",
"countryCode":"US",
"isp":"Digital Ocean",
"lat":40.8326,
"lon":-74.1307,
"org":"Digital Ocean",
"query":"104.131.124.203",
"region":"NJ",
"regionName":"New Jersey",
"status":"success",
"timezone":"America/New_York",
"zip":"07014"
}
*/
});
})
.catch(err => {
// handle errors
});
```
### Using createConnection with callbacks
SocksClient.createConnection() optionally accepts a callback function as a second parameter.
**Note:** If a callback function is provided, a Promise is still returned from the function, but the promise will always resolve regardless of if there was en error. (tldr: Do not mix callbacks and Promises).
```typescript
import { SocksClient, SocksClientOptions } from 'socks';
const options: SocksClientOptions = {
proxy: {
ipaddress: '104.131.124.203',
port: 1081,
type: 5
},
destination: {
host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5.
port: 80
},
command: 'connect'
};
SocksClient.createConnection(options, (err, info) => {
if (err) {
// handle errors
} else {
console.log(info.socket);
// <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy servers)
info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n');
info.socket.on('data', (data) => {
console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you).
/*
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Date: Sun, 24 Dec 2017 03:47:51 GMT
Content-Length: 300
{
"as":"AS14061 Digital Ocean, Inc.",
"city":"Clifton",
"country":"United States",
"countryCode":"US",
"isp":"Digital Ocean",
"lat":40.8326,
"lon":-74.1307,
"org":"Digital Ocean",
"query":"104.131.124.203",
"region":"NJ",
"regionName":"New Jersey",
"status":"success",
"timezone":"America/New_York",
"zip":"07014"
}
*/
});
}
})
```
### Using event handlers
SocksClient also supports instance creation of a SocksClient. This allows for event based flow control.
```typescript
import { SocksClient, SocksClientOptions } from 'socks';
const options: SocksClientOptions = {
proxy: {
ipaddress: '104.131.124.203',
port: 1081,
type: 5
},
destination: {
host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5.
port: 80
},
command: 'connect'
};
const client = new SocksClient(options);
client.on('established', (info) => {
console.log(info.socket);
// <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy servers)
info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n');
info.socket.on('data', (data) => {
console.log(data.toString()); // ip-api.com sees that the last proxy (104.131.124.203) is connected to it and not the origin client (you).
/*
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Date: Sun, 24 Dec 2017 03:47:51 GMT
Content-Length: 300
{
"as":"AS14061 Digital Ocean, Inc.",
"city":"Clifton",
"country":"United States",
"countryCode":"US",
"isp":"Digital Ocean",
"lat":40.8326,
"lon":-74.1307,
"org":"Digital Ocean",
"query":"104.131.124.203",
"region":"NJ",
"regionName":"New Jersey",
"status":"success",
"timezone":"America/New_York",
"zip":"07014"
}
*/
});
});
// Failed to establish proxy connection to destination.
client.on('error', () => {
// Handle errors
});
// Start connection
client.connect();
```
@@ -0,0 +1 @@
{"version":3,"file":"resolve.js","sourceRoot":"","sources":["../../src/utils/resolve.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAA;AACxB,OAAO,IAAI,MAAM,WAAW,CAAA;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAExC,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAA;AACtD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAE1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAA;AACxD,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAW1C,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AACtC,OAAO,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAA;AACrD,OAAO,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAA;AACxD,OAAO,EACL,qBAAqB,EACrB,wBAAwB,EACxB,yBAAyB,GAC1B,MAAM,+BAA+B,CAAA;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAA;AAE/C,MAAM,aAAa,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAA;AAErC,MAAM,SAAS,GAAG,aAAa;IAC7B,CAAC,CAAC,aAAa,CAAC,aAAa,CAAC;IAC9B,CAAC,CAA4B,UAAU,CAAA;AACzC,MAAM,QAAQ,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC,CAAA;AAExC,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,EAAE,CAAC,UAAU,CAC7C,IAAI,CAAC,OAAO,CACV,QAAQ,EACR,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,UAAU,CAAC,CAC3D,CACF,CAAA;AAED,MAAM,CAAC,MAAM,yBAAyB,GAAG,gCAAgC,CAAA;AAEzE,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,WAAW,EAAE,CAAA;AAGhD,MAAM,UAAU,sBAAsB,CACpC,QAAuB,EACvB,aAAsC,EACtC,MAAgB,EAChB,OAAgB,IAAI;IAGpB,IAAI,iBAAiB,EAAE,CAAC;QACtB,OAAO,IAAI,CAAA;IACb,CAAC;IAGD,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;QACtB,OAAO,IAAI,CAAA;IACb,CAAC;IACD,IAAI,QAAQ,CAAC,WAAW,EAAE,KAAK,OAAO,CAAC,GAAG,EAAE,CAAC,WAAW,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC;QACtE,OAAO,IAAI,CAAA;IACb,CAAC;IACD,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;IACvC,MAAM,GAAG,GAAG,UAAU,CAAC,GAAG,CAAA;IAE1B,IAAI,MAAM,GAAG,eAAe,CAAC,GAAG,CAAU,QAAQ,EAAE,aAAa,CAAC,CAAA;IAClE,IAAI,MAAM,IAAI,IAAI,EAAE,CAAC;QACnB,OAAO,MAAM,CAAA;IACf,CAAC;IAGD,IAAI,GAAG,KAAK,EAAE,IAAI,UAAU,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;QAC/C,MAAM,GAAG,IAAI,CAAA;IACf,CAAC;SAAM,CAAC;QACN,MAAM,SAAS,GAAG,EAAE,CAAC,WAAW,CAAC,GAAG,CAAC,CAAA;QACrC,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC;YAC1C,CAAC,CAAC,sBAAsB,CAAC,GAAG,EAAE,aAAa,EAAE,MAAM,EAAE,KAAK,CAAC;YAC3D,CAAC,CAAC,CAAC,IAAI;gBAIL,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,KAAK,UAAU,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAA;IAC7E,CAAC;IACD,eAAe,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA;IACrC,OAAO,MAAM,CAAA;AACf,CAAC;AAED,IAAI,YAAY,GAA0B,IAAI,CAAA;AAC9C,IAAI,YAAoB,CAAA;AAExB,SAAS,eAAe,CAAC,QAAiB;IACxC,OAAO,CAAC,CAAC,CACP,OAAO,QAAQ,KAAK,QAAQ;QAC5B,QAAQ;QACR,MAAM,IAAI,QAAQ;QAClB,OAAO,QAAQ,CAAC,IAAI,KAAK,QAAQ;QACjC,QAAQ,CAAC,IAAI,CACd,CAAA;AACH,CAAC;AAED,SAAS,kBAAkB,CAAC,QAAiB;IAC3C,IAAI,OAAO,QAAQ,KAAK,QAAQ,IAAI,QAAQ,IAAI,IAAI,EAAE,CAAC;QACrD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,CAAC,CAAC,SAAS,IAAI,QAAQ,CAAC,IAAI,CAAC,CAAC,kBAAkB,IAAI,QAAQ,CAAC,EAAE,CAAC;QAClE,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IACE,OAAO,QAAQ,CAAC,gBAAgB,KAAK,QAAQ;QAC7C,QAAQ,CAAC,gBAAgB,KAAK,CAAC,EAC/B,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,IAAI,OAAO,QAAQ,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QAC3C,OAAO,KAAK,CAAA;IACd,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC;AAED,SAAS,iBAAiB,CACxB,eAAoC,EACpC,OAAmC,EACnC,UAAkB,EAClB,UAAkB;IAElB,MAAM,EACJ,UAAU,EACV,kBAAkB,EAClB,eAAe,EACf,KAAK,EACL,gBAAgB,EAChB,OAAO,EAAE,WAAW,EACpB,aAAa,EACb,UAAU,EACV,eAAe,EACf,GAAG,IAAI,EACR,GAAG,eAAe,CAAA;IAEnB,MAAM,oBAAoB,GAAG,OAAO,CAAC,UAAU,CAAC,CAAA;IAEhD,MAAM,OAAO,GAAG,OAAO,CAAC,eAAe,CAAC,CAAA;IAGxC,MAAM,QAAQ,GAAG,gBAAgB,KAAK,KAAK,CAAA;IAE3C,MAAM,QAAQ,GAAG,kBAAkB,CAAC;QAClC,UAAU,EAAE,oBAAoB;QAChC,cAAc,EAAE,kBAAkB,KAAK,KAAK;QAC5C,OAAO;QACP,QAAQ;QACR,GAAG,IAAI;KACR,CAAC,CAAA;IAEF,MAAM,QAAQ,GAAG,cAAc,CAAC,OAAO,EAAE,GAAG,EAAE,CAC5C,QAAQ,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC,CACzC,CAAA;IAED,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;QACnB,OAAO,QAAQ,CAAA;IACjB,CAAC;IAED,MAAM,eAAe,GAAG,OAAO,CAAC,KAAK,CAAC,CAAA;IAEtC,IAAI,eAAe,EAAE,MAAM,EAAE,CAAC;QAC5B,MAAM,KAAK,GAAG,OAAO,EAAE,MAAM;YAC3B,CAAC,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;YACnD,CAAC,CAAC,eAAe,CAAA;QAEnB,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrB,MAAM,QAAQ,GAAG,kBAAkB,CAAC;gBAClC,UAAU,EAAE,oBAAoB;gBAChC,cAAc,EAAE,kBAAkB,KAAK,KAAK;gBAC5C,OAAO,EAAE,KAAK;gBACd,QAAQ;gBACR,GAAG,IAAI;aACR,CAAC,CAAA;YAEF,MAAM,QAAQ,GAAG,cAAc,CAAC,OAAO,EAAE,GAAG,EAAE,CAC5C,QAAQ,CAAC,OAAO,CAAC,UAAU,EAAE,UAAU,CAAC,CACzC,CAAA;YAED,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;gBACnB,OAAO,QAAQ,CAAA;YACjB,CAAC;QACH,CAAC;IACH,CAAC;IAED,IACE,CAAC,WAAW,EAAE,aAAa,EAAE,UAAU,EAAE,eAAe,CAAC,CAAC,IAAI,CAC5D,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,IAAI,CACjB,EACD,CAAC;QACD,IAAI,kBAAkC,CAAA;QACtC,IAAI,CAAC;YACH,kBAAkB,GAAG,UAAU,CAC7B,6BAA6B,CAC9B,CAAA;QACH,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,KAAK,CACb;gBACE,mFAAmF;gBACnF,gBAAgB;gBAChB,4DAA4D;gBAC5D,uFAAuF;aACxF,CAAC,IAAI,CAAC,IAAI,CAAC,CACb,CAAA;QACH,CAAC;QACD,MAAM,QAAQ,GAAG,yBAAyB,CACxC,kBAAkB,EAClB,eAAe,EACf,UAAU,EACV,UAAU,CACX,CAAA;QACD,IAAI,QAAQ,CAAC,KAAK,EAAE,CAAC;YACnB,OAAO,QAAQ,CAAA;QACjB,CAAC;IACH,CAAC;AACH,CAAC;AAED,SAAS,WAAW,CAClB,UAAkB,EAClB,UAAkB,EAClB,QAAwB,EACxB,OAAmC;IAGnC,MAAM,OAAO,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,uBAAuB,CAAC,CAAC,CAAA;IAC1D,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC;QAC5B,OAAO;YACL,KAAK,EAAE,IAAI;YACX,IAAI,EAAE,IAAI;SACX,CAAA;IACH,CAAC;IAED,MAAM,mBAAmB,GAAG,mBAAmB,CAAC,OAAO,CALine truncated
@@ -0,0 +1,129 @@
{
"name": "micromark-extension-gfm-strikethrough",
"version": "2.1.0",
"description": "micromark extension to support GFM strikethrough",
"license": "MIT",
"keywords": [
"micromark",
"micromark-extension",
"strikethrough",
"strike",
"through",
"del",
"delete",
"deletion",
"gfm",
"markdown",
"unified"
],
"repository": "micromark/micromark-extension-gfm-strikethrough",
"bugs": "https://github.com/micromark/micromark-extension-gfm-strikethrough/issues",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
},
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"contributors": [
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
],
"sideEffects": false,
"type": "module",
"files": [
"dev/",
"lib/",
"index.d.ts",
"index.js"
],
"exports": {
"development": "./dev/index.js",
"default": "./index.js"
},
"dependencies": {
"devlop": "^1.0.0",
"micromark-util-chunked": "^2.0.0",
"micromark-util-classify-character": "^2.0.0",
"micromark-util-resolve-all": "^2.0.0",
"micromark-util-symbol": "^2.0.0",
"micromark-util-types": "^2.0.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"c8": "^10.0.0",
"create-gfm-fixtures": "^1.0.0",
"micromark": "^4.0.0",
"micromark-build": "^2.0.0",
"prettier": "^3.0.0",
"remark-cli": "^12.0.0",
"remark-preset-wooorm": "^10.0.0",
"tape": "^5.0.0",
"type-coverage": "^2.0.0",
"typescript": "^5.0.0",
"xo": "^0.58.0"
},
"scripts": {
"prepack": "npm run build && npm run format",
"build": "tsc --build --clean && tsc --build && type-coverage && micromark-build",
"format": "remark . -qfo && prettier . -w --log-level warn && xo --fix",
"test-api-prod": "node --conditions production test/index.js",
"test-api-dev": "node --conditions development test/index.js",
"test-api": "npm run test-api-dev && npm run test-api-prod",
"test-coverage": "c8 --100 --reporter lcov npm run test-api",
"test": "npm run build && npm run format && npm run test-coverage"
},
"prettier": {
"bracketSpacing": false,
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"useTabs": false
},
"remarkConfig": {
"plugins": [
"remark-preset-wooorm"
]
},
"typeCoverage": {
"atLeast": 100,
"detail": true,
"ignoreCatch": true,
"strict": true
},
"xo": {
"prettier": true,
"rules": {
"logical-assignment-operators": "off",
"max-depth": "off",
"unicorn/prefer-at": "off"
},
"overrides": [
{
"files": "**/*.ts",
"rules": {
"@typescript-eslint/array-type": [
"error",
{
"default": "generic"
}
],
"@typescript-eslint/ban-types": [
"error",
{
"extendDefaults": true
}
],
"@typescript-eslint/consistent-type-definitions": [
"error",
"interface"
]
}
},
{
"files": "test/**/*.js",
"rules": {
"no-await-in-loop": 0
}
}
]
}
}
@@ -0,0 +1,26 @@
{
'defines': [ 'NAPI_DISABLE_CPP_EXCEPTIONS' ],
'cflags': [ '-fno-exceptions' ],
'cflags_cc': [ '-fno-exceptions' ],
'conditions': [
["OS=='win'", {
# _HAS_EXCEPTIONS is already defined and set to 0 in common.gypi
#"defines": [
# "_HAS_EXCEPTIONS=0"
#],
"msvs_settings": {
"VCCLCompilerTool": {
'ExceptionHandling': 0,
'EnablePREfast': 'true',
},
},
}],
["OS=='mac'", {
'xcode_settings': {
'CLANG_CXX_LIBRARY': 'libc++',
'MACOSX_DEPLOYMENT_TARGET': '10.7',
'GCC_ENABLE_CPP_EXCEPTIONS': 'NO',
},
}],
],
}
@@ -0,0 +1 @@
{"version":3,"file":"no-named-as-default.js","sourceRoot":"","sources":["../../src/rules/no-named-as-default.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAA;AAI5E,eAAe,UAAU,CAAgB;IACvC,IAAI,EAAE,qBAAqB;IAC3B,IAAI,EAAE;QACJ,IAAI,EAAE,SAAS;QACf,IAAI,EAAE;YACJ,QAAQ,EAAE,kBAAkB;YAC5B,WAAW,EACT,8DAA8D;SACjE;QACD,MAAM,EAAE,EAAE;QACV,QAAQ,EAAE;YACR,OAAO,EACL,kEAAkE;SACrE;KACF;IACD,cAAc,EAAE,EAAE;IAClB,MAAM,CAAC,OAAO;QACZ,SAAS,kBAAkB,CAAC,OAA6B;YACvD,OAAO,SAAS,YAAY,CAC1B,gBAAiD;gBAKjD,MAAM,SAAS,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC,IAAc,CAAA;gBAE1D,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;oBAC5B,OAAM;gBACR,CAAC;gBAED,MAAM,WAAW,GAAG,iBAAiB,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAA;gBAEhE,MAAM,mBAAmB,GAAG,SAAS,CAAC,GAAG,CACvC,WAAW,CAAC,MAAM,CAAC,KAAK,EACxB,OAAO,CACR,CAAA;gBAED,IAAI,mBAAmB,IAAI,IAAI,EAAE,CAAC;oBAChC,OAAM;gBACR,CAAC;gBAED,IAAI,mBAAmB,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;oBAC1C,mBAAmB,CAAC,YAAY,CAAC,OAAO,EAAE,WAAW,CAAC,CAAA;oBACtD,OAAM;gBACR,CAAC;gBAED,IAAI,CAAC,mBAAmB,CAAC,UAAU,EAAE,CAAC;oBAGpC,OAAM;gBACR,CAAC;gBAED,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC;oBAExC,OAAM;gBACR,CAAC;gBAED,IACE,mBAAmB,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC;oBAC1C,mBAAmB,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,EAC1C,CAAC;oBACD,OAAO,CAAC,MAAM,CAAC;wBACb,IAAI,EAAE,gBAAgB;wBACtB,SAAS,EAAE,SAAS;wBACpB,IAAI,EAAE;4BACJ,IAAI,EAAE,SAAS;yBAChB;qBACF,CAAC,CAAA;gBACJ,CAAC;YACH,CAAC,CAAA;QACH,CAAC;QACD,OAAO;YACL,sBAAsB,EAAE,kBAAkB,CAAC,OAAO,CAAC;YACnD,sBAAsB,EAAE,kBAAkB,CAAC,UAAU,CAAC;SACvD,CAAA;IACH,CAAC;CACF,CAAC,CAAA"}
@@ -0,0 +1,28 @@
// src/react/index.ts
export * from "@reduxjs/toolkit";
// src/dynamicMiddleware/react/index.ts
import { createDynamicMiddleware as cDM } from "@reduxjs/toolkit";
import { createDispatchHook, ReactReduxContext, useDispatch as useDefaultDispatch } from "react-redux";
var createDynamicMiddleware = () => {
const instance = cDM();
const createDispatchWithMiddlewareHookFactory = (context = ReactReduxContext) => {
const useDispatch = context === ReactReduxContext ? useDefaultDispatch : createDispatchHook(context);
function createDispatchWithMiddlewareHook2(...middlewares) {
instance.addMiddleware(...middlewares);
return useDispatch;
}
createDispatchWithMiddlewareHook2.withTypes = () => createDispatchWithMiddlewareHook2;
return createDispatchWithMiddlewareHook2;
};
const createDispatchWithMiddlewareHook = createDispatchWithMiddlewareHookFactory();
return {
...instance,
createDispatchWithMiddlewareHookFactory,
createDispatchWithMiddlewareHook
};
};
export {
createDynamicMiddleware
};
//# sourceMappingURL=redux-toolkit-react.modern.mjs.map
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveInstanceBindingNodeFromConstructorParams = resolveInstanceBindingNodeFromConstructorParams;
const common_1 = require("@inversifyjs/common");
const resolvePostConstruct_1 = require("./resolvePostConstruct");
function resolveAllPostConstructMethods(instance, binding, postConstructMethodNames) {
if (postConstructMethodNames.size === 0) {
return instance;
}
let result = instance;
for (const methodName of postConstructMethodNames) {
if ((0, common_1.isPromise)(result)) {
result = result.then((resolvedInstance) => (0, resolvePostConstruct_1.resolvePostConstruct)(resolvedInstance, binding, methodName));
}
else {
result = (0, resolvePostConstruct_1.resolvePostConstruct)(result, binding, methodName);
}
}
return result;
}
function resolveInstanceBindingNodeFromConstructorParams(setInstanceProperties) {
return (constructorValues, params, node) => {
const instance = new node.binding.implementationType(...constructorValues);
const propertiesAssignmentResult = setInstanceProperties(params, instance, node);
if ((0, common_1.isPromise)(propertiesAssignmentResult)) {
return propertiesAssignmentResult.then(() => resolveAllPostConstructMethods(instance, node.binding, node.classMetadata.lifecycle.postConstructMethodNames));
}
return resolveAllPostConstructMethods(instance, node.binding, node.classMetadata.lifecycle.postConstructMethodNames);
};
}
//# sourceMappingURL=resolveInstanceBindingNodeFromConstructorParams.js.map
@@ -0,0 +1,15 @@
module.exports = {
"deselectedItem": (args)=>`${args.item} \u{5DC}\u{5D0} \u{5E0}\u{5D1}\u{5D7}\u{5E8}.`,
"longPressToSelect": `\u{5D4}\u{5E7}\u{5E9}\u{5D4} \u{5D0}\u{5E8}\u{5D5}\u{5DB}\u{5D4} \u{5DC}\u{5DB}\u{5E0}\u{5D9}\u{5E1}\u{5D4} \u{5DC}\u{5DE}\u{5E6}\u{5D1} \u{5D1}\u{5D7}\u{5D9}\u{5E8}\u{5D4}.`,
"select": `\u{5D1}\u{5D7}\u{5E8}`,
"selectedAll": `\u{5DB}\u{5DC} \u{5D4}\u{5E4}\u{5E8}\u{5D9}\u{5D8}\u{5D9}\u{5DD} \u{5E0}\u{5D1}\u{5D7}\u{5E8}\u{5D5}.`,
"selectedCount": (args, formatter)=>`${formatter.plural(args.count, {
"=0": `\u{5DC}\u{5D0} \u{5E0}\u{5D1}\u{5D7}\u{5E8}\u{5D5} \u{5E4}\u{5E8}\u{5D9}\u{5D8}\u{5D9}\u{5DD}`,
one: ()=>`\u{5E4}\u{5E8}\u{5D9}\u{5D8} ${formatter.number(args.count)} \u{5E0}\u{5D1}\u{5D7}\u{5E8}`,
other: ()=>`${formatter.number(args.count)} \u{5E4}\u{5E8}\u{5D9}\u{5D8}\u{5D9}\u{5DD} \u{5E0}\u{5D1}\u{5D7}\u{5E8}\u{5D5}`
})}.`,
"selectedItem": (args)=>`${args.item} \u{5E0}\u{5D1}\u{5D7}\u{5E8}.`
};
//# sourceMappingURL=he-IL.main.js.map
@@ -0,0 +1,14 @@
module.exports = {
"ascending": `\u{432}\u{44A}\u{437}\u{445}\u{43E}\u{434}\u{44F}\u{449}`,
"ascendingSort": (args)=>`\u{441}\u{43E}\u{440}\u{442}\u{438}\u{440}\u{430}\u{43D}\u{43E} \u{43F}\u{43E} \u{43A}\u{43E}\u{43B}\u{43E}\u{43D}\u{430} ${args.columnName} \u{432}\u{44A}\u{432} \u{432}\u{44A}\u{437}\u{445}\u{43E}\u{434}\u{44F}\u{449} \u{440}\u{435}\u{434}`,
"columnSize": (args)=>`${args.value} \u{43F}\u{438}\u{43A}\u{441}\u{435}\u{43B}\u{430}`,
"descending": `\u{43D}\u{438}\u{437}\u{445}\u{43E}\u{434}\u{44F}\u{449}`,
"descendingSort": (args)=>`\u{441}\u{43E}\u{440}\u{442}\u{438}\u{440}\u{430}\u{43D}\u{43E} \u{43F}\u{43E} \u{43A}\u{43E}\u{43B}\u{43E}\u{43D}\u{430} ${args.columnName} \u{432} \u{43D}\u{438}\u{437}\u{445}\u{43E}\u{434}\u{44F}\u{449} \u{440}\u{435}\u{434}`,
"resizerDescription": `\u{41D}\u{430}\u{442}\u{438}\u{441}\u{43D}\u{435}\u{442}\u{435} \u{201E}Enter\u{201C}, \u{437}\u{430} \u{434}\u{430} \u{437}\u{430}\u{43F}\u{43E}\u{447}\u{43D}\u{435}\u{442}\u{435} \u{434}\u{430} \u{43F}\u{440}\u{435}\u{43E}\u{440}\u{430}\u{437}\u{43C}\u{435}\u{440}\u{44F}\u{432}\u{430}\u{442}\u{435}`,
"select": `\u{418}\u{437}\u{431}\u{435}\u{440}\u{435}\u{442}\u{435}`,
"selectAll": `\u{418}\u{437}\u{431}\u{435}\u{440}\u{435}\u{442}\u{435} \u{432}\u{441}\u{438}\u{447}\u{43A}\u{43E}`,
"sortable": `\u{441}\u{43E}\u{440}\u{442}\u{438}\u{440}\u{430}\u{449}\u{430} \u{43A}\u{43E}\u{43B}\u{43E}\u{43D}\u{430}`
};
//# sourceMappingURL=bg-BG.main.js.map
@@ -0,0 +1 @@
{"processes":{"c579bf8f-6820-47a5-b2da-a11267eb8435":{"parent":null,"children":[]}},"files":{"/Users/dabh/triple-beam/index.js":["c579bf8f-6820-47a5-b2da-a11267eb8435"],"/Users/dabh/triple-beam/config/index.js":["c579bf8f-6820-47a5-b2da-a11267eb8435"],"/Users/dabh/triple-beam/config/cli.js":["c579bf8f-6820-47a5-b2da-a11267eb8435"],"/Users/dabh/triple-beam/config/npm.js":["c579bf8f-6820-47a5-b2da-a11267eb8435"],"/Users/dabh/triple-beam/config/syslog.js":["c579bf8f-6820-47a5-b2da-a11267eb8435"]},"externalIds":{}}
@@ -0,0 +1,5 @@
var convert = require('./convert'),
func = convert('lowerCase', require('../lowerCase'), require('./_falseOptions'));
func.placeholder = require('./placeholder');
module.exports = func;
@@ -0,0 +1,32 @@
/**
* Parse a path string into an array of path segments.
*
* Square bracket notation `a[b]` may be used to "escape" dots that would otherwise be interpreted as path separators.
*
* Example:
* a -> ['a']
* a.b.c -> ['a', 'b', 'c']
* a[b].c -> ['a', 'b', 'c']
* a[b.c].e.f -> ['a', 'b.c', 'e', 'f']
* a[b][c][d] -> ['a', 'b', 'c', 'd']
*
* @param {string|string[]} path
**/ "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "toPath", {
enumerable: true,
get: function() {
return toPath;
}
});
function toPath(path) {
if (Array.isArray(path)) return path;
let openBrackets = path.split("[").length - 1;
let closedBrackets = path.split("]").length - 1;
if (openBrackets !== closedBrackets) {
throw new Error(`Path is invalid. Has unbalanced brackets: ${path}`);
}
return path.split(/\.(?![^\[]*\])|[\[\]]/g).filter(Boolean);
}
@@ -0,0 +1,47 @@
{
"name": "@npmcli/move-file",
"version": "2.0.1",
"files": [
"bin/",
"lib/"
],
"main": "lib/index.js",
"description": "move a file (fork of move-file)",
"dependencies": {
"mkdirp": "^1.0.4",
"rimraf": "^3.0.2"
},
"devDependencies": {
"@npmcli/eslint-config": "^3.0.1",
"@npmcli/template-oss": "3.5.0",
"tap": "^16.0.1"
},
"scripts": {
"test": "tap",
"snap": "tap",
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags",
"lint": "eslint \"**/*.js\"",
"postlint": "template-oss-check",
"template-oss-apply": "template-oss-apply --force",
"lintfix": "npm run lint -- --fix",
"posttest": "npm run lint"
},
"repository": {
"type": "git",
"url": "https://github.com/npm/move-file.git"
},
"tap": {
"check-coverage": true
},
"license": "MIT",
"engines": {
"node": "^12.13.0 || ^14.15.0 || >=16.0.0"
},
"author": "GitHub Inc.",
"templateOSS": {
"//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
"version": "3.5.0"
}
}
@@ -0,0 +1,5 @@
## Security contact information
To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.
@@ -0,0 +1,3 @@
<svg viewBox="0 0 18 18">
<path class="ql-fill" d="M10,4V14a1,1,0,0,1-2,0V10H3v4a1,1,0,0,1-2,0V4A1,1,0,0,1,3,4V8H8V4a1,1,0,0,1,2,0Zm6.06787,9.209H14.98975V7.59863a.54085.54085,0,0,0-.605-.60547h-.62744a1.01119,1.01119,0,0,0-.748.29688L11.645,8.56641a.5435.5435,0,0,0-.022.8584l.28613.30762a.53861.53861,0,0,0,.84717.0332l.09912-.08789a1.2137,1.2137,0,0,0,.2417-.35254h.02246s-.01123.30859-.01123.60547V13.209H12.041a.54085.54085,0,0,0-.605.60547v.43945a.54085.54085,0,0,0,.605.60547h4.02686a.54085.54085,0,0,0,.605-.60547v-.43945A.54085.54085,0,0,0,16.06787,13.209Z"/>
</svg>

After

Width:  |  Height:  |  Size: 577 B

@@ -0,0 +1 @@
{"version":3,"file":"settingsService.d.ts","sourceRoot":"","sources":["../../src/services/settingsService.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAE/E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAYrD,MAAM,MAAM,kBAAkB,GAAG,iBAAiB,GAAG,KAAK,CAAC;AAE3D,UAAU,eAAe;IACvB;;;;;;OAMG;IACH,mBAAmB,CAAC,IAAI,EAAE;QACxB,UAAU,EAAE,kBAAkB,CAAC;QAC/B,YAAY,EAAE,CAAC,WAAW,GAAG,MAAM,CAAC,EAAE,CAAC;KACxC,GAAG,IAAI,CAAC;IAET;;OAEG;IACH,mBAAmB,CAAC,IAAI,EAAE;QAAE,UAAU,EAAE,kBAAkB,CAAA;KAAE,GAAG,MAAM,EAAE,CAAC;CACzE;AAkCD;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,eAAe,EAAE,eAA2C,CAAC"}
@@ -0,0 +1 @@
{"version":3,"names":["_isValidIdentifier","require","_index","_default","exports","default","valueToNode","objectToString","Function","call","bind","Object","prototype","toString","isRegExp","value","isPlainObject","proto","getPrototypeOf","undefined","identifier","booleanLiteral","nullLiteral","stringLiteral","result","Number","isFinite","numericLiteral","Math","abs","numerator","isNaN","binaryExpression","is","unaryExpression","bigIntLiteral","pattern","source","flags","exec","regExpLiteral","Array","isArray","arrayExpression","map","props","key","keys","nodeKey","computed","isValidIdentifier","push","objectProperty","objectExpression","Error"],"sources":["../../src/converters/valueToNode.ts"],"sourcesContent":["import isValidIdentifier from \"../validators/isValidIdentifier.ts\";\nimport {\n identifier,\n booleanLiteral,\n nullLiteral,\n stringLiteral,\n numericLiteral,\n bigIntLiteral,\n regExpLiteral,\n arrayExpression,\n objectProperty,\n objectExpression,\n unaryExpression,\n binaryExpression,\n} from \"../builders/generated/index.ts\";\nimport type * as t from \"../index.ts\";\n\nexport default valueToNode as {\n (value: undefined): t.Identifier; // TODO: This should return \"void 0\"\n (value: boolean): t.BooleanLiteral;\n (value: null): t.NullLiteral;\n (value: string): t.StringLiteral;\n // Infinities and NaN need to use a BinaryExpression; negative values must be wrapped in UnaryExpression\n (value: number): t.NumericLiteral | t.BinaryExpression | t.UnaryExpression;\n (value: bigint): t.BigIntLiteral;\n (value: RegExp): t.RegExpLiteral;\n (value: ReadonlyArray<unknown>): t.ArrayExpression;\n\n // this throws with objects that are not plain objects,\n // or if there are non-valueToNode-able values\n (value: object): t.ObjectExpression;\n\n (value: unknown): t.Expression;\n};\n\n// @ts-expect-error: Object.prototype.toString must return a string\nconst objectToString: (value: unknown) => string = Function.call.bind(\n Object.prototype.toString,\n);\n\nfunction isRegExp(value: unknown): value is RegExp {\n return objectToString(value) === \"[object RegExp]\";\n}\n\nfunction isPlainObject(value: unknown): value is object {\n if (\n typeof value !== \"object\" ||\n value === null ||\n Object.prototype.toString.call(value) !== \"[object Object]\"\n ) {\n return false;\n }\n const proto = Object.getPrototypeOf(value);\n // Object.prototype's __proto__ is null. Every other class's __proto__.__proto__ is\n // not null by default. We cannot check if proto === Object.prototype because it\n // could come from another realm.\n return proto === null || Object.getPrototypeOf(proto) === null;\n}\n\nfunction valueToNode(value: unknown): t.Expression {\n // undefined\n if (value === undefined) {\n return identifier(\"undefined\");\n }\n\n // boolean\n if (value === true || value === false) {\n return booleanLiteral(value);\n }\n\n // null\n if (value === null) {\n return nullLiteral();\n }\n\n // strings\n if (typeof value === \"string\") {\n return stringLiteral(value);\n }\n\n // numbers\n if (typeof value === \"number\") {\n let result;\n if (Number.isFinite(value)) {\n result = numericLiteral(Math.abs(value));\n } else {\n let numerator;\n if (Number.isNaN(value)) {\n // NaN\n numerator = numericLiteral(0);\n } else {\n // Infinity / -Infinity\n numerator = numericLiteral(1);\n }\n\n result = binaryExpression(\"/\", numerator, numericLiteral(0));\n }\n\n if (value < 0 || Object.is(value, -0)) {\n result = unaryExpression(\"-\", result);\n }\n\n return result;\n }\n\n // bigints\n if (typeof value === \"bigint\") {\n if (value < 0) {\n return unaryExpression(\"-\", bigIntLiteral(-value));\n } else {\n return bigIntLiteral(value);\n }\n }\n\n // regexes\n if (isRegExp(value)) {\n const pattern = value.source;\n const flags = /\\/([a-z]*)$/.exec(value.toString())[1];\n return regExpLiteral(pattern, flags);\n }\n\n // array\n if (Array.isArray(value)) {\n return arrayExpression(value.map(valueToNode));\n }\n\n // object\n if (isPlainObject(value)) {\n const props = [];\n for (const key of Object.keys(value)) {\n let nodeKey,\n computed = false;\n if (isValidIdentifier(key)) {\n if (key === \"__proto__\") {\n computed = true;\n nodeKey = stringLiteral(key);\n } else {\n nodeKey = identifier(key);\n }\n } else {\n nodeKey = stringLiteral(key);\n }\n props.push(\n objectProperty(\n nodeKey,\n valueToNode(\n // @ts-expect-error key must present in value\n value[key],\n ),\n computed,\n ),\n );\n }\n return objectExpression(props);\n }\n\n throw new Error(\"don't know how to turn this value into a node\");\n}\n"],"mappings":";;;;;;AAAA,IAAAA,kBALine truncated
@@ -0,0 +1,18 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./instantiate"), exports);
@@ -0,0 +1,12 @@
# These are supported funding model platforms
github: [ljharb]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: npm/array.prototype.flat
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getForStatementHeadLoc = getForStatementHeadLoc;
const eslint_utils_1 = require("@typescript-eslint/utils/eslint-utils");
/**
* Gets the location of the head of the given for statement variant for reporting.
*
* - `for (const foo in bar) expressionOrBlock`
* ^^^^^^^^^^^^^^^^^^^^^^
*
* - `for (const foo of bar) expressionOrBlock`
* ^^^^^^^^^^^^^^^^^^^^^^
*
* - `for await (const foo of bar) expressionOrBlock`
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*
* - `for (let i = 0; i < 10; i++) expressionOrBlock`
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*/
function getForStatementHeadLoc(sourceCode, node) {
const closingParens = (0, eslint_utils_1.nullThrows)(sourceCode.getTokenBefore(node.body, token => token.value === ')'), 'for statement must have a closing parenthesis.');
return {
end: structuredClone(closingParens.loc.end),
start: structuredClone(node.loc.start),
};
}
@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E F A B wC"},B:{"1":"0 1 2 3 4 5 V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I","2":"C L M G N O P","328":"Q H R S T U"},C:{"1":"0 1 2 3 4 5 U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I XC MC YC yC zC","2":"xC TC 0C 1C","161":"6 7 8 9 J ZB K D E F A B C L M G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B UC 4B VC 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R WC S T"},D:{"1":"0 1 2 3 4 5 V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I XC MC YC","2":"6 7 8 9 J ZB K D E F A B C L M G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B UC 4B VC 5B 6B 7B 8B 9B","328":"AC BC CC DC EC FC GC HC IC JC KC LC Q H R S T U"},E:{"1":"cC PC AD QC dC eC fC gC hC BD RC iC jC kC lC mC CD SC nC oC pC qC rC sC tC DD ED","2":"J ZB K D E F A B C L M 2C ZC 3C 4C 5C 6C aC NC OC 7C 8C","578":"G 9C bC"},F:{"1":"0 1 2 3 4 5 FC GC HC IC JC KC LC Q H R WC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z","2":"6 7 8 9 F B C G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B FD GD HD ID NC uC JD OC","328":"9B AC BC CC DC EC"},G:{"1":"cC PC eD QC dC eC fC gC hC fD RC iC jC kC lC mC gD SC nC oC pC qC rC sC tC","2":"E ZC KD vC LD MD ND OD PD QD RD SD TD UD VD WD XD YD ZD aD bD cD","578":"dD bC"},H:{"2":"hD"},I:{"1":"I","2":"TC J iD jD kD lD vC mD nD"},J:{"2":"D A"},K:{"1":"H","2":"A B C NC uC OC"},L:{"1":"I"},M:{"1":"MC"},N:{"2":"A B"},O:{"2":"PC"},P:{"1":"6 7 8 9 AB BB CB DB EB FB wD xD QC RC SC yD","2":"J oD pD qD rD sD aC tD uD vD"},Q:{"2":"zD"},R:{"1":"0D"},S:{"161":"1D 2D"}},B:5,C:":focus-visible CSS pseudo-class",D:true};
@@ -0,0 +1 @@
module.exports={A:{A:{"16":"wC","132":"K D E F A B"},B:{"1":"0 1 2 3 4 5 P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I","132":"C L M G N O"},C:{"1":"0 1 2 3 4 5 1B 2B 3B UC 4B VC 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R WC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I XC MC YC yC zC","132":"6 7 8 9 xC TC J ZB K D E F A B C L M G N O P aB AB BB CB DB EB 0C 1C","260":"xB yB zB 0B","772":"FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB"},D:{"1":"0 1 2 3 4 5 DC EC FC GC HC IC JC KC LC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I XC MC YC","132":"6 7 8 9 J ZB K D E F A B C L M G N O P aB","260":"jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B UC 4B VC 5B 6B 7B 8B 9B AC BC CC","772":"AB BB CB DB EB FB bB cB dB eB fB gB hB iB"},E:{"1":"C L M G OC 7C 8C 9C bC cC PC AD QC dC eC fC gC hC BD RC iC jC kC lC mC CD SC nC oC pC qC rC sC tC DD ED","16":"J ZB 2C ZC","132":"K D E F A 3C 4C 5C 6C","260":"B aC NC"},F:{"1":"0 1 2 3 4 5 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R WC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z","16":"F B C FD GD HD ID NC uC JD","132":"OC","260":"BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B","772":"6 7 8 9 G N O P aB AB"},G:{"1":"SD TD UD VD WD XD YD ZD aD bD cD dD bC cC PC eD QC dC eC fC gC hC fD RC iC jC kC lC mC gD SC nC oC pC qC rC sC tC","16":"ZC KD vC LD","132":"E MD ND OD PD QD RD"},H:{"132":"hD"},I:{"1":"I","16":"TC iD jD kD","132":"J lD vC","772":"mD nD"},J:{"132":"D A"},K:{"1":"H","16":"A B C NC uC","132":"OC"},L:{"1":"I"},M:{"1":"MC"},N:{"132":"A B"},O:{"1":"PC"},P:{"1":"6 7 8 9 AB BB CB DB EB FB sD aC tD uD vD wD xD QC RC SC yD","260":"J oD pD qD rD"},Q:{"1":"zD"},R:{"1":"0D"},S:{"1":"2D","132":"1D"}},B:6,C:"Date.prototype.toLocaleDateString",D:true};
@@ -0,0 +1 @@
module.exports={C:{"43":0.04748,"45":0.09496,"85":0.09496,"93":0.04748,"96":0.47481,"99":0.04748,"115":1.37017,"120":0.28489,"132":0.04748,"141":0.18992,"142":0.56977,"143":1.65505,"144":2.78781,_:"2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 86 87 88 89 90 91 92 94 95 97 98 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 116 117 118 119 121 122 123 124 125 126 127 128 129 130 131 133 134 135 136 137 138 139 140 145 146 147 3.5 3.6"},D:{"33":0.04748,"41":0.04748,"57":0.04748,"77":0.09496,"83":0.04748,"92":0.37985,"109":7.00006,"112":0.42733,"118":0.37985,"125":0.71222,"126":0.28489,"127":1.56009,"131":5.91478,"134":1.32269,"135":1.2752,"136":0.09496,"137":0.33237,"138":0.52229,"139":1.60757,"140":7.3799,"141":12.86735,"142":0.28489,_:"4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 34 35 36 37 38 39 40 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 78 79 80 81 84 85 86 87 88 89 90 91 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 110 111 113 114 115 116 117 119 120 121 122 123 124 128 129 130 132 133 143 144 145"},F:{"57":0.28489,"90":0.04748,"110":0.04748,"122":0.18992,_:"9 11 12 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 58 60 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 111 112 113 114 115 116 117 118 119 120 121 9.5-9.6 10.0-10.1 10.5 10.6 11.1 11.5 11.6 12.1"},B:{"18":0.14244,"90":0.04748,"100":0.47481,"135":0.04748,"137":0.09496,"138":0.18992,"139":2.69285,"140":4.96516,"141":3.78491,_:"12 13 14 15 16 17 79 80 81 83 84 85 86 87 88 89 91 92 93 94 95 96 97 98 99 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 136 142"},E:{_:"0 4 5 6 7 8 9 10 11 12 13 14 15 3.1 3.2 5.1 6.1 7.1 9.1 10.1 11.1 12.1 13.1 14.1 15.1 15.2-15.3 15.4 15.5 15.6 16.0 16.1 16.2 16.3 16.4 16.5 16.6 17.0 17.1 17.2 17.3 17.4 17.5 17.6 18.0 18.1 18.2 18.3 18.4 26.0 26.1 26.2","18.5-18.6":0.33237},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00012,"5.0-5.1":0,"6.0-6.1":0.00047,"7.0-7.1":0.00036,"8.1-8.4":0,"9.0-9.2":0,"9.3":0.00107,"10.0-10.2":0.00012,"10.3":0.00201,"11.0-11.2":0.02982,"11.3-11.4":0.00071,"12.0-12.1":0.00024,"12.2-12.5":0.0058,"13.0-13.1":0,"13.2":0.00059,"13.3":0.00024,"13.4-13.7":0.00095,"14.0-14.4":0.00201,"14.5-14.8":0.00213,"15.0-15.1":0.00201,"15.2-15.3":0.00154,"15.4":0.00178,"15.5":0.00201,"15.6-15.8":0.02627,"16.0":0.00355,"16.1":0.00663,"16.2":0.00343,"16.3":0.00615,"16.4":0.00154,"16.5":0.00272,"16.6-16.7":0.03515,"17.0":0.00249,"17.1":0.00379,"17.2":0.00272,"17.3":0.00402,"17.4":0.0071,"17.5":0.01219,"17.6-17.7":0.03077,"18.0":0.00698,"18.1":0.01444,"18.2":0.00781,"18.3":0.02509,"18.4":0.0129,"18.5-18.6":0.65778,"26.0":0.08131,"26.1":0.00296},P:{"27":0.05146,_:"4 20 21 22 23 24 25 26 28 29 5.0-5.4 6.2-6.4 7.2-7.4 8.2 9.2 10.1 11.1-11.2 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0"},I:{"0":0,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0,"4.2-4.3":0,"4.4":0,"4.4.3-4.4.4":0},K:{"0":0.72038,_:"10 11 12 11.1 11.5 12.1"},A:{_:"6 7 8 9 10 11 5.5"},S:{_:"2.5 3.0-3.1"},J:{_:"7 10"},N:{_:"10 11"},R:{_:"0"},M:{"0":0.05146},Q:{_:"14.9"},O:{"0":0.41165},H:{"0":0},L:{"0":31.33721}};
@@ -0,0 +1,325 @@
import {isCtrlKeyPressed as $feb5ffebff200149$export$16792effe837dba3, isNonContiguousSelectionModifier as $feb5ffebff200149$export$d3e3bd3e26688c04} from "./utils.mjs";
import {useTypeSelect as $fb3050f43d946246$export$e32c88dfddc6e1d8} from "./useTypeSelect.mjs";
import {flushSync as $3H3GQ$flushSync} from "react-dom";
import {useRef as $3H3GQ$useRef, useEffect as $3H3GQ$useEffect} from "react";
import {getFocusableTreeWalker as $3H3GQ$getFocusableTreeWalker, focusSafely as $3H3GQ$focusSafely} from "@react-aria/focus";
import {useRouter as $3H3GQ$useRouter, focusWithoutScrolling as $3H3GQ$focusWithoutScrolling, useEvent as $3H3GQ$useEvent, scrollIntoViewport as $3H3GQ$scrollIntoViewport, scrollIntoView as $3H3GQ$scrollIntoView, mergeProps as $3H3GQ$mergeProps} from "@react-aria/utils";
import {getInteractionModality as $3H3GQ$getInteractionModality} from "@react-aria/interactions";
import {useLocale as $3H3GQ$useLocale} from "@react-aria/i18n";
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
function $ae20dd8cbca75726$export$d6daf82dcd84e87c(options) {
let { selectionManager: manager, keyboardDelegate: delegate, ref: ref, autoFocus: autoFocus = false, shouldFocusWrap: shouldFocusWrap = false, disallowEmptySelection: disallowEmptySelection = false, disallowSelectAll: disallowSelectAll = false, selectOnFocus: selectOnFocus = manager.selectionBehavior === 'replace', disallowTypeAhead: disallowTypeAhead = false, shouldUseVirtualFocus: shouldUseVirtualFocus, allowsTabNavigation: allowsTabNavigation = false, isVirtualized: isVirtualized, scrollRef: // If no scrollRef is provided, assume the collection ref is the scrollable region
scrollRef = ref, linkBehavior: linkBehavior = 'action' } = options;
let { direction: direction } = (0, $3H3GQ$useLocale)();
let router = (0, $3H3GQ$useRouter)();
let onKeyDown = (e)=>{
var _ref_current;
// Prevent option + tab from doing anything since it doesn't move focus to the cells, only buttons/checkboxes
if (e.altKey && e.key === 'Tab') e.preventDefault();
// Keyboard events bubble through portals. Don't handle keyboard events
// for elements outside the collection (e.g. menus).
if (!((_ref_current = ref.current) === null || _ref_current === void 0 ? void 0 : _ref_current.contains(e.target))) return;
const navigateToKey = (key, childFocus)=>{
if (key != null) {
if (manager.isLink(key) && linkBehavior === 'selection' && selectOnFocus && !(0, $feb5ffebff200149$export$d3e3bd3e26688c04)(e)) {
var _scrollRef_current;
// Set focused key and re-render synchronously to bring item into view if needed.
(0, $3H3GQ$flushSync)(()=>{
manager.setFocusedKey(key, childFocus);
});
let item = (_scrollRef_current = scrollRef.current) === null || _scrollRef_current === void 0 ? void 0 : _scrollRef_current.querySelector(`[data-key="${CSS.escape(key.toString())}"]`);
let itemProps = manager.getItemProps(key);
if (item) router.open(item, e, itemProps.href, itemProps.routerOptions);
return;
}
manager.setFocusedKey(key, childFocus);
if (manager.isLink(key) && linkBehavior === 'override') return;
if (e.shiftKey && manager.selectionMode === 'multiple') manager.extendSelection(key);
else if (selectOnFocus && !(0, $feb5ffebff200149$export$d3e3bd3e26688c04)(e)) manager.replaceSelection(key);
}
};
switch(e.key){
case 'ArrowDown':
if (delegate.getKeyBelow) {
var _delegate_getKeyBelow, _delegate_getFirstKey, _delegate_getFirstKey1;
let nextKey = manager.focusedKey != null ? (_delegate_getKeyBelow = delegate.getKeyBelow) === null || _delegate_getKeyBelow === void 0 ? void 0 : _delegate_getKeyBelow.call(delegate, manager.focusedKey) : (_delegate_getFirstKey = delegate.getFirstKey) === null || _delegate_getFirstKey === void 0 ? void 0 : _delegate_getFirstKey.call(delegate);
if (nextKey == null && shouldFocusWrap) nextKey = (_delegate_getFirstKey1 = delegate.getFirstKey) === null || _delegate_getFirstKey1 === void 0 ? void 0 : _delegate_getFirstKey1.call(delegate, manager.focusedKey);
if (nextKey != null) {
e.preventDefault();
navigateToKey(nextKey);
}
}
break;
case 'ArrowUp':
if (delegate.getKeyAbove) {
var _delegate_getKeyAbove, _delegate_getLastKey, _delegate_getLastKey1;
let nextKey = manager.focusedKey != null ? (_delegate_getKeyAbove = delegate.getKeyAbove) === null || _delegate_getKeyAbove === void 0 ? void 0 : _delegate_getKeyAbove.call(delegate, manager.focusedKey) : (_delegate_getLastKey = delegate.getLastKey) === null || _delegate_getLastKey === void 0 ? void 0 : _delegate_getLastKey.call(delegate);
if (nextKey == null && shouldFocusWrap) nextKey = (_delegate_getLastKey1 = delegate.getLastKey) === null || _delegate_getLastKey1 === void 0 ? void 0 : _delegate_getLastKey1.call(delegate, manager.focusedKey);
if (nextKey != null) {
e.preventDefault();
navigateToKey(nextKey);
}
}
break;
case 'ArrowLeft':
if (delegate.getKeyLeftOf) {
var _delegate_getKeyLeftOf, _delegate_getFirstKey2, _delegate_getLastKey2;
let nextKey = manager.focusedKey != null ? (_delegate_getKeyLeftOf = delegate.getKeyLeftOf) === null || _delegate_getKeyLeftOf === void 0 ? void 0 : _delegate_getKeyLeftOf.call(delegate, manager.focusedKey) : null;
if (nextKey == null && shouldFocusWrap) nextKey = direction === 'rtl' ? (_delegate_getFirstKey2 = delegate.getFirstKey) === null || _delegate_getFirstKey2 === void 0 ? void 0 : _delegate_getFirstKey2.call(delegate, manager.focusedKey) : (_delegate_getLastKey2 = delegate.getLastKey) === null || _delegate_getLastKey2 === void 0 ? void 0 : _delegate_getLastKey2.call(delegate, manager.focusedKey);
if (nextKey != null) {
e.preventDefault();
navigateToKey(nextKey, direction === 'rtl' ? 'first' : 'last');
}
}
break;
case 'ArrowRight':
if (delegate.getKeyRightOf) {
var _delegate_getKeyRightOf, _delegate_getLastKey3, _delegate_getFirstKey3;
let nextKey = manager.focusedKey != null ? (_delegate_getKeyRightOf = delegate.getKeyRightOf) === null || _delegate_getKeyRightOf === void 0 ? void 0 : _delegate_getKeyRightOf.call(delegate, manager.focusedKey) : null;
if (nextKey == null && shouldFocusWrap) nextKey = direction === 'rtl' ? (_delegate_getLastKey3 = delegate.getLastKey) === null || _delegate_getLastKey3 === void 0 ? void 0 : _delegate_getLastKey3.call(delegate, manager.focusedKey) : (_delegate_getFirstKey3 = delegate.getFirstKey) === null || _delegate_getFirstKey3 === void 0 ? void 0 : _delegate_getFirstKey3.call(delegate, manager.focusedKey);
if (nextKey != null) {
e.preventDefault();
navigateToKey(nextKey, direction === 'rtl' ? 'last' : 'first');
}
}
break;
case 'Home':
if (delegate.getFirstKey) {
e.preventDefault();
let firstKey = delegate.getFirstKey(manager.focusedKey, (0, $feb5ffebff200149$export$16792effe837dba3)(e));
manager.setFocusedKey(firstKey);
if (firstKey != null) {
if ((0, $feb5ffebff200149$export$16792effe837dba3)(e) && e.shiftKey && manager.selectionMode === 'multiple') manager.extendSelection(firstKey);
else if (selectOnFocus) manager.replaceSelection(firstKey);
}
}
break;
case 'End':
if (delegate.getLastKey) {
e.preventDefault();
let lastKey = delegate.getLastKey(manager.focusedKey, (0, $feb5ffebff200149$export$16792effe837dba3)(e));
manager.setFocusedKey(lastKey);
if (lastKey != null) {
if ((0, $feb5ffebff200149$export$16792effe837dba3)(e) && e.shiftKey && manager.selectionMode === 'multiple') manager.extendSelection(lastKey);
else if (selectOnFocus) manager.replaceSelection(lastKey);
}
}
break;
case 'PageDown':
if (delegate.getKeyPageBelow && manager.focusedKey != null) {
let nextKey = delegate.getKeyPageBelow(manager.focusedKey);
if (nextKey != null) {
e.preventDefault();
navigateToKey(nextKey);
}
}
break;
case 'PageUp':
if (delegate.getKeyPageAbove && manager.focusedKey != null) {
let nextKey = delegate.getKeyPageAbove(manager.focusedKey);
if (nextKey != null) {
e.preventDefault();
navigateToKey(nextKey);
}
}
break;
case 'a':
if ((0, $feb5ffebff200149$export$16792effe837dba3)(e) && manager.selectionMode === 'multiple' && disallowSelectAll !== true) {
e.preventDefault();
manager.selectAll();
}
break;
case 'Escape':
if (!disallowEmptySelection && manager.selectedKeys.size !== 0) {
e.stopPropagation();
e.preventDefault();
manager.clearSelection();
}
break;
case 'Tab':
if (!allowsTabNavigation) {
// There may be elements that are "tabbable" inside a collection (e.g. in a grid cell).
// However, collections should be treated as a single tab stop, with arrow key navigation internally.
// We don't control the rendering of these, so we can't override the tabIndex to prevent tabbing.
// Instead, we handle the Tab key, and move focus manually to the first/last tabbable element
// in the collection, so that the browser default behavior will apply starting from that element
// rather than the currently focused one.
if (e.shiftKey) ref.current.focus();
else {
let walker = (0, $3H3GQ$getFocusableTreeWalker)(ref.current, {
tabbable: true
});
let next = undefined;
let last;
do {
last = walker.lastChild();
if (last) next = last;
}while (last);
if (next && !next.contains(document.activeElement)) (0, $3H3GQ$focusWithoutScrolling)(next);
}
break;
}
}
};
// Store the scroll position so we can restore it later.
/// TODO: should this happen all the time??
let scrollPos = (0, $3H3GQ$useRef)({
top: 0,
left: 0
});
(0, $3H3GQ$useEvent)(scrollRef, 'scroll', isVirtualized ? undefined : ()=>{
var _scrollRef_current, _scrollRef_current1;
var _scrollRef_current_scrollTop, _scrollRef_current_scrollLeft;
scrollPos.current = {
top: (_scrollRef_current_scrollTop = (_scrollRef_current = scrollRef.current) === null || _scrollRef_current === void 0 ? void 0 : _scrollRef_current.scrollTop) !== null && _scrollRef_current_scrollTop !== void 0 ? _scrollRef_current_scrollTop : 0,
left: (_scrollRef_current_scrollLeft = (_scrollRef_current1 = scrollRef.current) === null || _scrollRef_current1 === void 0 ? void 0 : _scrollRef_current1.scrollLeft) !== null && _scrollRef_current_scrollLeft !== void 0 ? _scrollRef_current_scrollLeft : 0
};
});
let onFocus = (e)=>{
if (manager.isFocused) {
// If a focus event bubbled through a portal, reset focus state.
if (!e.currentTarget.contains(e.target)) manager.setFocused(false);
return;
}
// Focus events can bubble through portals. Ignore these events.
if (!e.currentTarget.contains(e.target)) return;
manager.setFocused(true);
if (manager.focusedKey == null) {
var _delegate_getLastKey, _delegate_getFirstKey;
let navigateToFirstKey = (key)=>{
if (key != null) {
manager.setFocusedKey(key);
if (selectOnFocus) manager.replaceSelection(key);
}
};
// If the user hasn't yet interacted with the collection, there will be no focusedKey set.
// Attempt to detect whether the user is tabbing forward or backward into the collection
// and either focus the first or last item accordingly.
let relatedTarget = e.relatedTarget;
var _manager_lastSelectedKey, _manager_firstSelectedKey;
if (relatedTarget && e.currentTarget.compareDocumentPosition(relatedTarget) & Node.DOCUMENT_POSITION_FOLLOWING) navigateToFirstKey((_manager_lastSelectedKey = manager.lastSelectedKey) !== null && _manager_lastSelectedKey !== void 0 ? _manager_lastSelectedKey : (_delegate_getLastKey = delegate.getLastKey) === null || _delegate_getLastKey === void 0 ? void 0 : _delegate_getLastKey.call(delegate));
else navigateToFirstKey((_manager_firstSelectedKey = manager.firstSelectedKey) !== null && _manager_firstSelectedKey !== void 0 ? _manager_firstSelectedKey : (_delegate_getFirstKey = delegate.getFirstKey) === null || _delegate_getFirstKey === void 0 ? void 0 : _delegate_getFirstKey.call(delegate));
} else if (!isVirtualized && scrollRef.current) {
// Restore the scroll position to what it was before.
scrollRef.current.scrollTop = scrollPos.current.top;
scrollRef.current.scrollLeft = scrollPos.current.left;
}
if (manager.focusedKey != null && scrollRef.current) {
// Refocus and scroll the focused item into view if it exists within the scrollable region.
let element = scrollRef.current.querySelector(`[data-key="${CSS.escape(manager.focusedKey.toString())}"]`);
if (element) {
// This prevents a flash of focus on the first/last element in the collection, or the collection itself.
if (!element.contains(document.activeElement)) (0, $3H3GQ$focusWithoutScrolling)(element);
let modality = (0, $3H3GQ$getInteractionModality)();
if (modality === 'keyboard') (0, $3H3GQ$scrollIntoViewport)(element, {
containingElement: ref.current
});
}
}
};
let onBlur = (e)=>{
// Don't set blurred and then focused again if moving focus within the collection.
if (!e.currentTarget.contains(e.relatedTarget)) manager.setFocused(false);
};
const autoFocusRef = (0, $3H3GQ$useRef)(autoFocus);
(0, $3H3GQ$useEffect)(()=>{
if (autoFocusRef.current) {
var _delegate_getFirstKey, _delegate_getLastKey;
let focusedKey = null;
var _delegate_getFirstKey1;
// Check focus strategy to determine which item to focus
if (autoFocus === 'first') focusedKey = (_delegate_getFirstKey1 = (_delegate_getFirstKey = delegate.getFirstKey) === null || _delegate_getFirstKey === void 0 ? void 0 : _delegate_getFirstKey.call(delegate)) !== null && _delegate_getFirstKey1 !== void 0 ? _delegate_getFirstKey1 : null;
var _delegate_getLastKey1;
if (autoFocus === 'last') focusedKey = (_delegate_getLastKey1 = (_delegate_getLastKey = delegate.getLastKey) === null || _delegate_getLastKey === void 0 ? void 0 : _delegate_getLastKey.call(delegate)) !== null && _delegate_getLastKey1 !== void 0 ? _delegate_getLastKey1 : null;
// If there are any selected keys, make the first one the new focus target
let selectedKeys = manager.selectedKeys;
if (selectedKeys.size) {
for (let key of selectedKeys)if (manager.canSelectItem(key)) {
focusedKey = key;
break;
}
}
manager.setFocused(true);
manager.setFocusedKey(focusedKey);
// If no default focus key is selected, focus the collection itself.
if (focusedKey == null && !shouldUseVirtualFocus && ref.current) (0, $3H3GQ$focusSafely)(ref.current);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Scroll the focused element into view when the focusedKey changes.
let lastFocusedKey = (0, $3H3GQ$useRef)(manager.focusedKey);
(0, $3H3GQ$useEffect)(()=>{
if (manager.isFocused && manager.focusedKey != null && (manager.focusedKey !== lastFocusedKey.current || autoFocusRef.current) && scrollRef.current && ref.current) {
let modality = (0, $3H3GQ$getInteractionModality)();
let element = ref.current.querySelector(`[data-key="${CSS.escape(manager.focusedKey.toString())}"]`);
if (!element) // If item element wasn't found, return early (don't update autoFocusRef and lastFocusedKey).
// The collection may initially be empty (e.g. virtualizer), so wait until the element exists.
return;
if (modality === 'keyboard' || autoFocusRef.current) {
(0, $3H3GQ$scrollIntoView)(scrollRef.current, element);
// Avoid scroll in iOS VO, since it may cause overlay to close (i.e. RAC submenu)
if (modality !== 'virtual') (0, $3H3GQ$scrollIntoViewport)(element, {
containingElement: ref.current
});
}
}
// If the focused key becomes null (e.g. the last item is deleted), focus the whole collection.
if (!shouldUseVirtualFocus && manager.isFocused && manager.focusedKey == null && lastFocusedKey.current != null && ref.current) (0, $3H3GQ$focusSafely)(ref.current);
lastFocusedKey.current = manager.focusedKey;
autoFocusRef.current = false;
});
// Intercept FocusScope restoration since virtualized collections can reuse DOM nodes.
(0, $3H3GQ$useEvent)(ref, 'react-aria-focus-scope-restore', (e)=>{
e.preventDefault();
manager.setFocused(true);
});
let handlers = {
onKeyDown: onKeyDown,
onFocus: onFocus,
onBlur: onBlur,
onMouseDown (e) {
// Ignore events that bubbled through portals.
if (scrollRef.current === e.target) // Prevent focus going to the collection when clicking on the scrollbar.
e.preventDefault();
}
};
let { typeSelectProps: typeSelectProps } = (0, $fb3050f43d946246$export$e32c88dfddc6e1d8)({
keyboardDelegate: delegate,
selectionManager: manager
});
if (!disallowTypeAhead) handlers = (0, $3H3GQ$mergeProps)(typeSelectProps, handlers);
// If nothing is focused within the collection, make the collection itself tabbable.
// This will be marshalled to either the first or last item depending on where focus came from.
// If using virtual focus, don't set a tabIndex at all so that VoiceOver on iOS 14 doesn't try
// to move real DOM focus to the element anyway.
let tabIndex = undefined;
if (!shouldUseVirtualFocus) tabIndex = manager.focusedKey == null ? 0 : -1;
return {
collectionProps: {
...handlers,
tabIndex: tabIndex
}
};
}
export {$ae20dd8cbca75726$export$d6daf82dcd84e87c as useSelectableCollection};
//# sourceMappingURL=useSelectableCollection.module.js.map
@@ -0,0 +1 @@
{"version":3,"names":["_index","require","getQualifiedName","node","isIdentifier","name","id","qualification","removeTypeDuplicates","nodesIn","nodes","Array","from","generics","Map","bases","typeGroups","Set","types","i","length","includes","isAnyTypeAnnotation","isFlowBaseAnnotation","set","type","isUnionTypeAnnotation","has","push","add","isGenericTypeAnnotation","existing","get","typeParameters","params","baseType","genericName"],"sources":["../../../src/modifications/flow/removeTypeDuplicates.ts"],"sourcesContent":["import {\n isAnyTypeAnnotation,\n isGenericTypeAnnotation,\n isUnionTypeAnnotation,\n isFlowBaseAnnotation,\n isIdentifier,\n} from \"../../validators/generated/index.ts\";\nimport type * as t from \"../../index.ts\";\n\nfunction getQualifiedName(node: t.GenericTypeAnnotation[\"id\"]): string {\n return isIdentifier(node)\n ? node.name\n : `${node.id.name}.${getQualifiedName(node.qualification)}`;\n}\n\n/**\n * Dedupe type annotations.\n */\nexport default function removeTypeDuplicates(\n nodesIn: ReadonlyArray<t.FlowType | false | null | undefined>,\n): t.FlowType[] {\n const nodes = Array.from(nodesIn);\n\n const generics = new Map<string, t.GenericTypeAnnotation>();\n const bases = new Map<t.FlowBaseAnnotation[\"type\"], t.FlowBaseAnnotation>();\n\n // store union type groups to circular references\n const typeGroups = new Set<t.FlowType[]>();\n\n const types: t.FlowType[] = [];\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i];\n if (!node) continue;\n\n // detect duplicates\n if (types.includes(node)) {\n continue;\n }\n\n // this type matches anything\n if (isAnyTypeAnnotation(node)) {\n return [node];\n }\n\n if (isFlowBaseAnnotation(node)) {\n bases.set(node.type, node);\n continue;\n }\n\n if (isUnionTypeAnnotation(node)) {\n if (!typeGroups.has(node.types)) {\n nodes.push(...node.types);\n typeGroups.add(node.types);\n }\n continue;\n }\n\n // find a matching generic type and merge and deduplicate the type parameters\n if (isGenericTypeAnnotation(node)) {\n const name = getQualifiedName(node.id);\n\n if (generics.has(name)) {\n let existing: t.Flow = generics.get(name);\n if (existing.typeParameters) {\n if (node.typeParameters) {\n existing.typeParameters.params.push(...node.typeParameters.params);\n existing.typeParameters.params = removeTypeDuplicates(\n existing.typeParameters.params,\n );\n }\n } else {\n existing = node.typeParameters;\n }\n } else {\n generics.set(name, node);\n }\n\n continue;\n }\n\n types.push(node);\n }\n\n // add back in bases\n for (const [, baseType] of bases) {\n types.push(baseType);\n }\n\n // add back in generics\n for (const [, genericName] of generics) {\n types.push(genericName);\n }\n\n return types;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AASA,SAASC,gBAAgBA,CAACC,IAAmC,EAAU;EACrE,OAAO,IAAAC,mBAAY,EAACD,IAAI,CAAC,GACrBA,IAAI,CAACE,IAAI,GACT,GAAGF,IAAI,CAACG,EAAE,CAACD,IAAI,IAAIH,gBAAgB,CAACC,IAAI,CAACI,aAAa,CAAC,EAAE;AAC/D;AAKe,SAASC,oBAAoBA,CAC1CC,OAA6D,EAC/C;EACd,MAAMC,KAAK,GAAGC,KAAK,CAACC,IAAI,CAACH,OAAO,CAAC;EAEjC,MAAMI,QAAQ,GAAG,IAAIC,GAAG,CAAkC,CAAC;EAC3D,MAAMC,KAAK,GAAG,IAAID,GAAG,CAAqD,CAAC;EAG3E,MAAME,UAAU,GAAG,IAAIC,GAAG,CAAe,CAAC;EAE1C,MAAMC,KAAmB,GAAG,EAAE;EAE9B,KAAK,IAAIC,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGT,KAAK,CAACU,MAAM,EAAED,CAAC,EAAE,EAAE;IACrC,MAAMhB,IAAI,GAAGO,KAAK,CAACS,CAAC,CAAC;IACrB,IAAI,CAAChB,IAAI,EAAE;IAGX,IAAIe,KAAK,CAACG,QAAQ,CAAClB,IAAI,CAAC,EAAE;MACxB;IACF;IAGA,IAAI,IAAAmB,0BAAmB,EAACnB,IAAI,CAAC,EAAE;MAC7B,OAAO,CAACA,IAAI,CAAC;IACf;IAEA,IAAI,IAAAoB,2BAAoB,EAACpB,IAAI,CAAC,EAAE;MAC9BY,KAAK,CAACS,GAAG,CAACrB,IAAI,CAACsB,IAAI,EAAEtB,IAAI,CAAC;MAC1B;IACF;IAEA,IAAI,IAAAuB,4BAAqB,EAACvB,IAAI,CAAC,EAAE;MAC/B,IAAI,CAACa,UAAU,CAACW,GAAG,CAACxB,IAAI,CAACe,KAAK,CAAC,EAAE;QAC/BR,KAAK,CAACkB,IAAI,CAAC,GAAGzB,IAAI,CAACe,KAAK,CAAC;QACzBF,UAAU,CAACa,GAAG,CAAC1B,IAAI,CAACe,KAAK,CAAC;MAC5B;MACA;IACF;IAGA,IAAI,IAAAY,8BAAuB,EAAC3B,IAAI,CAAC,EAAE;MACjC,MAAME,IAAI,GAAGH,gBAAgB,CAACC,IAAI,CAACG,EAAE,CAAC;MAEtC,IAAIO,QAAQ,CAACc,GAAG,CAACtB,IAAI,CAAC,EAAE;QACtB,IAAI0B,QAAgB,GAAGlB,QAAQ,CAACmB,GAAG,CAAC3B,IAAI,CAAC;QACzC,IAAI0B,QAAQ,CAACE,cAAc,EAAE;UAC3B,IAAI9B,IAAI,CAAC8B,cAAc,EAAE;YACvBF,QAAQ,CAACE,cAAc,CAACC,MAAM,CAACN,IAAI,CAAC,GAAGzB,IAAI,CAAC8B,cAAc,CAACC,MAAM,CAAC;YAClEH,QAAQ,CAACE,cAAc,CAACC,MAAM,GAAG1B,oBAAoB,CACnDuB,QAAQ,CAACE,cAAc,CAACC,MAC1B,CAAC;UACH;QACF,CAAC,MAAM;UACLH,QAAQ,GAAG5B,IAAI,CAAC8B,cAAc;QAChC;MACF,CAAC,MAAM;QACLpB,QAAQ,CAACW,GAAG,CAACnB,IAAI,EAAEF,IAAI,CAAC;MAC1B;MAEA;IACF;IAEAe,KAAK,CAACU,IAAI,CAACzB,IAAI,CAAC;EAClB;EAGA,KAAK,MAAM,GAAGgC,QAAQ,CAAC,IAAIpB,KAAK,EAAE;IAChCG,KAAK,CAACU,IAAI,CAACO,QAAQ,CAAC;EACtB;EAGA,KAAK,MAAM,GAAGC,WAAW,CAAC,IAAIvB,QAAQ,EAAE;IACtCK,KAAK,CAACU,IAAI,CAACQ,WAAW,CAAC;EACzB;EAEA,OAAOlB,KAAK;AACd",Line truncated
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/helpers/iso/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,YAAY,MAAM,mBAAmB,CAAC;AAClD,OAAO,KAAK,OAAO,MAAM,cAAc,CAAC;AACxC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAC;AAClD,OAAO,KAAK,aAAa,MAAM,oBAAoB,CAAC"}
@@ -0,0 +1,10 @@
{
"extends": "@ljharb/tsconfig",
"compilerOptions": {
"target": "es2022",
},
"exclude": [
"coverage",
"test/list-exports"
],
}
@@ -0,0 +1 @@
module.exports={A:{A:{"1":"A B","2":"K D E F wC"},B:{"1":"0 1 2 3 4 5 C L M G N O P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I"},C:{"1":"0 1 2 3 4 5 6 7 8 9 xC TC J ZB K D E F A B C L M G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B UC 4B VC 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R WC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I XC MC YC yC zC 0C 1C"},D:{"1":"0 1 2 3 4 5 6 7 8 9 F A B C L M G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B UC 4B VC 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB I XC MC YC","2":"J ZB K D E"},E:{"1":"K D E F A B C L M G 3C 4C 5C 6C aC NC OC 7C 8C 9C bC cC PC AD QC dC eC fC gC hC BD RC iC jC kC lC mC CD SC nC oC pC qC rC sC tC DD ED","2":"J ZB 2C ZC"},F:{"1":"0 1 2 3 4 5 6 7 8 9 B C G N O P aB AB BB CB DB EB FB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC EC FC GC HC IC JC KC LC Q H R WC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z HD ID NC uC JD OC","2":"F FD GD"},G:{"4":"E ZC KD vC LD MD ND OD PD QD RD SD TD UD VD WD XD YD ZD aD bD cD dD bC cC PC eD QC dC eC fC gC hC fD RC iC jC kC lC mC gD SC nC oC pC qC rC sC tC"},H:{"4":"hD"},I:{"4":"TC J I iD jD kD lD vC mD nD"},J:{"1":"A","4":"D"},K:{"4":"A B C H NC uC OC"},L:{"4":"I"},M:{"4":"MC"},N:{"4":"A B"},O:{"4":"PC"},P:{"4":"6 7 8 9 J AB BB CB DB EB FB oD pD qD rD sD aC tD uD vD wD xD QC RC SC yD"},Q:{"1":"zD"},R:{"4":"0D"},S:{"2":"1D 2D"}},B:1,C:"Spellcheck attribute",D:true};
@@ -0,0 +1,173 @@
import React, { useRef, forwardRef, useImperativeHandle, useCallback } from 'react';
import type { EditorState, EditorStateConfig, Extension, StateField } from '@codemirror/state';
import type { EditorView, ViewUpdate } from '@codemirror/view';
import { type BasicSetupOptions } from '@uiw/codemirror-extensions-basic-setup';
import { useCodeMirror } from './useCodeMirror';
import { type Statistics } from './utils';
export * from '@codemirror/view';
export * from '@codemirror/state';
export * from '@uiw/codemirror-extensions-basic-setup';
export * from './useCodeMirror';
export * from './getDefaultExtensions';
export * from './utils';
export interface ReactCodeMirrorProps
extends Omit<EditorStateConfig, 'doc' | 'extensions'>,
Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange' | 'placeholder'> {
/** value of the auto created model in the editor. */
value?: string;
height?: string;
minHeight?: string;
maxHeight?: string;
width?: string;
minWidth?: string;
maxWidth?: string;
/** focus on the editor. */
autoFocus?: boolean;
/** Enables a placeholder—a piece of example content to show when the editor is empty. */
placeholder?: string | HTMLElement;
/**
* `light` / `dark` / `Extension` Defaults to `light`.
* @default light
*/
theme?: 'light' | 'dark' | 'none' | Extension;
/**
* Whether to optional basicSetup by default
* @default true
*/
basicSetup?: boolean | BasicSetupOptions;
/**
* This disables editing of the editor content by the user.
* @default true
*/
editable?: boolean;
/**
* This disables editing of the editor content by the user.
* @default false
*/
readOnly?: boolean;
/**
* Controls whether pressing the `Tab` key inserts a tab character and indents the text (`true`)
* or behaves according to the browser's default behavior (`false`).
* @default true
*/
indentWithTab?: boolean;
/** Fired whenever a change occurs to the document. */
onChange?(value: string, viewUpdate: ViewUpdate): void;
/** Some data on the statistics editor. */
onStatistics?(data: Statistics): void;
/** Fired whenever any state change occurs within the editor, including non-document changes like lint results. */
onUpdate?(viewUpdate: ViewUpdate): void;
/** The first time the editor executes the event. */
onCreateEditor?(view: EditorView, state: EditorState): void;
/**
* Extension values can be [provided](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions) when creating a state to attach various kinds of configuration and behavior information.
* They can either be built-in extension-providing objects,
* such as [state fields](https://codemirror.net/6/docs/ref/#state.StateField) or [facet providers](https://codemirror.net/6/docs/ref/#state.Facet.of),
* or objects with an extension in its `extension` property. Extensions can be nested in arrays arbitrarily deep—they will be flattened when processed.
*/
extensions?: Extension[];
/**
* If the view is going to be mounted in a shadow root or document other than the one held by the global variable document (the default), you should pass it here.
* Originally from the [config of EditorView](https://codemirror.net/6/docs/ref/#view.EditorView.constructor%5Econfig.root)
*/
root?: ShadowRoot | Document;
/**
* Create a state from its JSON representation serialized with [toJSON](https://codemirror.net/docs/ref/#state.EditorState.toJSON) function
*/
initialState?: {
json: any;
fields?: Record<string, StateField<any>>;
};
}
export interface ReactCodeMirrorRef {
editor?: HTMLDivElement | null;
state?: EditorState;
view?: EditorView;
}
const ReactCodeMirror = forwardRef<ReactCodeMirrorRef, ReactCodeMirrorProps>((props, ref) => {
const {
className,
value = '',
selection,
extensions = [],
onChange,
onStatistics,
onCreateEditor,
onUpdate,
autoFocus,
theme = 'light',
height,
minHeight,
maxHeight,
width,
minWidth,
maxWidth,
basicSetup,
placeholder,
indentWithTab,
editable,
readOnly,
root,
initialState,
...other
} = props;
const editor = useRef<HTMLDivElement | null>(null);
const { state, view, container, setContainer } = useCodeMirror({
root,
value,
autoFocus,
theme,
height,
minHeight,
maxHeight,
width,
minWidth,
maxWidth,
basicSetup,
placeholder,
indentWithTab,
editable,
readOnly,
selection,
onChange,
onStatistics,
onCreateEditor,
onUpdate,
extensions,
initialState,
});
useImperativeHandle(ref, () => ({ editor: editor.current, state: state, view: view }), [
editor,
container,
state,
view,
]);
const setEditorRef = useCallback(
(el: HTMLDivElement) => {
editor.current = el;
setContainer(el);
},
[setContainer],
);
// check type of value
if (typeof value !== 'string') {
throw new Error(`value must be typeof string but got ${typeof value}`);
}
const defaultClassNames = typeof theme === 'string' ? `cm-theme-${theme}` : 'cm-theme';
return (
<div ref={setEditorRef} className={`${defaultClassNames}${className ? ` ${className}` : ''}`} {...other}></div>
);
});
ReactCodeMirror.displayName = 'CodeMirror';
export default ReactCodeMirror;
@@ -0,0 +1,10 @@
import { PluginFunc } from 'dayjs'
declare const plugin: PluginFunc
export = plugin
declare module 'dayjs' {
interface Dayjs {
weekYear(): number
}
}
@@ -0,0 +1,22 @@
import { OneBotAction } from '../../../action/OneBotAction';
import { Static } from '@sinclair/typebox';
export declare const DownloadFilesetPayloadSchema: import("@sinclair/typebox").TObject<{
fileset_id: import("@sinclair/typebox").TString;
}>;
export type DownloadFilesetPayload = Static<typeof DownloadFilesetPayloadSchema>;
export declare class DownloadFileset extends OneBotAction<DownloadFilesetPayload, any> {
actionName: "download_fileset";
payloadSchema: import("@sinclair/typebox").TObject<{
fileset_id: import("@sinclair/typebox").TString;
}>;
returnSchema: import("@sinclair/typebox").TAny;
actionSummary: string;
actionTags: string[];
payloadExample: {
fileset_id: string;
};
returnExample: null;
_handle(payload: DownloadFilesetPayload): Promise<import("../../../../napcat-core").GeneralCallResult & {
extraInfo: unknown;
}>;
}
@@ -0,0 +1,155 @@
/**
* @fileoverview Limit maximum of props on a single line in JSX
* @author Yannick Croissant
*/
'use strict';
const docsUrl = require('../util/docsUrl');
const getText = require('../util/eslint').getText;
const report = require('../util/report');
function getPropName(context, propNode) {
if (propNode.type === 'JSXSpreadAttribute') {
return getText(context, propNode.argument);
}
return propNode.name.name;
}
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
const messages = {
newLine: 'Prop `{{prop}}` must be placed on a new line',
};
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
docs: {
description: 'Enforce maximum of props on a single line in JSX',
category: 'Stylistic Issues',
recommended: false,
url: docsUrl('jsx-max-props-per-line'),
},
fixable: 'code',
messages,
schema: [{
anyOf: [{
type: 'object',
properties: {
maximum: {
type: 'object',
properties: {
single: {
type: 'integer',
minimum: 1,
},
multi: {
type: 'integer',
minimum: 1,
},
},
},
},
additionalProperties: false,
}, {
type: 'object',
properties: {
maximum: {
type: 'number',
minimum: 1,
},
when: {
type: 'string',
enum: ['always', 'multiline'],
},
},
additionalProperties: false,
}],
}],
},
create(context) {
const configuration = context.options[0] || {};
const maximum = configuration.maximum || 1;
const maxConfig = typeof maximum === 'number'
? {
single: configuration.when === 'multiline' ? Infinity : maximum,
multi: maximum,
}
: {
single: maximum.single || Infinity,
multi: maximum.multi || Infinity,
};
function generateFixFunction(line, max) {
const output = [];
const front = line[0].range[0];
const back = line[line.length - 1].range[1];
for (let i = 0; i < line.length; i += max) {
const nodes = line.slice(i, i + max);
output.push(nodes.reduce((prev, curr) => {
if (prev === '') {
return getText(context, curr);
}
return `${prev} ${getText(context, curr)}`;
}, ''));
}
const code = output.join('\n');
return function fix(fixer) {
return fixer.replaceTextRange([front, back], code);
};
}
return {
JSXOpeningElement(node) {
if (!node.attributes.length) {
return;
}
const isSingleLineTag = node.loc.start.line === node.loc.end.line;
if ((isSingleLineTag ? maxConfig.single : maxConfig.multi) === Infinity) {
return;
}
const firstProp = node.attributes[0];
const linePartitionedProps = [[firstProp]];
node.attributes.reduce((last, decl) => {
if (last.loc.end.line === decl.loc.start.line) {
linePartitionedProps[linePartitionedProps.length - 1].push(decl);
} else {
linePartitionedProps.push([decl]);
}
return decl;
});
linePartitionedProps.forEach((propsInLine) => {
const maxPropsCountPerLine = isSingleLineTag && propsInLine[0].loc.start.line === node.loc.start.line
? maxConfig.single
: maxConfig.multi;
if (propsInLine.length > maxPropsCountPerLine) {
const name = getPropName(context, propsInLine[maxPropsCountPerLine]);
report(context, messages.newLine, 'newLine', {
node: propsInLine[maxPropsCountPerLine],
data: {
prop: name,
},
fix: generateFixFunction(propsInLine, maxPropsCountPerLine),
});
}
});
},
};
},
};
@@ -0,0 +1,6 @@
import { useLayoutEffect } from 'react';
/**
* A hook that resolves to useEffect on the server and useLayoutEffect on the client
* @param callback {function} Callback function that is invoked when the dependencies of the hook change
*/
export declare const useIsomorphicLayoutEffect: typeof useLayoutEffect;
@@ -0,0 +1,39 @@
var baseSlice = require('./_baseSlice'),
toInteger = require('./toInteger');
/**
* Creates a slice of `array` with `n` elements taken from the end.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to query.
* @param {number} [n=1] The number of elements to take.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {Array} Returns the slice of `array`.
* @example
*
* _.takeRight([1, 2, 3]);
* // => [3]
*
* _.takeRight([1, 2, 3], 2);
* // => [2, 3]
*
* _.takeRight([1, 2, 3], 5);
* // => [1, 2, 3]
*
* _.takeRight([1, 2, 3], 0);
* // => []
*/
function takeRight(array, n, guard) {
var length = array == null ? 0 : array.length;
if (!length) {
return [];
}
n = (guard || n === undefined) ? 1 : toInteger(n);
n = length - n;
return baseSlice(array, n < 0 ? 0 : n, length);
}
module.exports = takeRight;
@@ -0,0 +1,498 @@
import { noop } from '@internal/listenerMiddleware/utils'
import type { PayloadAction } from '@reduxjs/toolkit'
import {
configureStore,
createAction,
createListenerMiddleware,
createSlice,
isAnyOf,
TaskAbortError,
} from '@reduxjs/toolkit'
describe('Saga-style Effects Scenarios', () => {
interface CounterState {
value: number
}
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 } as CounterState,
reducers: {
increment(state) {
state.value += 1
},
decrement(state) {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number>) => {
state.value += action.payload
},
},
})
const { increment, decrement, incrementByAmount } = counterSlice.actions
let { reducer } = counterSlice
let listenerMiddleware = createListenerMiddleware<CounterState>()
let { middleware, startListening, stopListening } = listenerMiddleware
let store = configureStore({
reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
const testAction1 = createAction<string>('testAction1')
type TestAction1 = ReturnType<typeof testAction1>
const testAction2 = createAction<string>('testAction2')
type TestAction2 = ReturnType<typeof testAction2>
const testAction3 = createAction<string>('testAction3')
type TestAction3 = ReturnType<typeof testAction3>
type RootState = ReturnType<typeof store.getState>
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)
beforeEach(() => {
listenerMiddleware = createListenerMiddleware<CounterState>()
middleware = listenerMiddleware.middleware
startListening = listenerMiddleware.startListening
store = configureStore({
reducer,
middleware: (gDM) => gDM().prepend(middleware),
})
})
afterEach(() => {
vi.clearAllMocks()
})
afterAll(() => {
vi.restoreAllMocks()
})
test('throttle', async () => {
// Ignore incoming actions for a given period of time while processing a task.
// Ref: https://redux-saga.js.org/docs/api#throttlems-pattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: (action, listenerApi) => {
listenerCalls++
// Stop listening until further notice
listenerApi.unsubscribe()
// Queue to start listening again after a delay
setTimeout(listenerApi.subscribe, 15)
workPerformed++
},
})
// Dispatch 3 actions. First triggers listener, next two ignored.
store.dispatch(increment())
store.dispatch(increment())
store.dispatch(increment())
// Wait for resubscription
await delay(25)
// Dispatch 2 more actions, first triggers, second ignored
store.dispatch(increment())
store.dispatch(increment())
// Wait for work
await delay(5)
// Both listener calls completed
expect(listenerCalls).toBe(2)
expect(workPerformed).toBe(2)
})
test('debounce / takeLatest', async () => {
// Repeated calls cancel previous ones, no work performed
// until the specified delay elapses without another call
// NOTE: This is also basically identical to `takeLatest`.
// Ref: https://redux-saga.js.org/docs/api#debouncems-pattern-saga-args
// Ref: https://redux-saga.js.org/docs/api#takelatestpattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
listenerCalls++
// Cancel any in-progress instances of this listener
listenerApi.cancelActiveListeners()
// Delay before starting actual work
await listenerApi.delay(15)
workPerformed++
},
})
// First action, listener 1 starts, nothing to cancel
store.dispatch(increment())
// Second action, listener 2 starts, cancels 1
store.dispatch(increment())
// Third action, listener 3 starts, cancels 2
store.dispatch(increment())
// 3 listeners started, third is still paused
expect(listenerCalls).toBe(3)
expect(workPerformed).toBe(0)
await delay(25)
// All 3 started
expect(listenerCalls).toBe(3)
// First two canceled, `delay()` threw JobCanceled and skipped work.
// Third actually completed.
expect(workPerformed).toBe(1)
})
test('takeEvery', async () => {
// Runs the listener on every action match
// Ref: https://redux-saga.js.org/docs/api#takeeverypattern-saga-args
// NOTE: This is already the default behavior - nothing special here!
let listenerCalls = 0
startListening({
actionCreator: increment,
effect: (action, listenerApi) => {
listenerCalls++
},
})
store.dispatch(increment())
expect(listenerCalls).toBe(1)
store.dispatch(increment())
expect(listenerCalls).toBe(2)
})
test('takeLeading', async () => {
// Starts listener on first action, ignores others until task completes
// Ref: https://redux-saga.js.org/docs/api#takeleadingpattern-saga-args
let listenerCalls = 0
let workPerformed = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
listenerCalls++
// Stop listening for this action
listenerApi.unsubscribe()
// Pretend we're doing expensive work
await listenerApi.delay(25)
workPerformed++
// Re-enable the listener
listenerApi.subscribe()
},
})
// First action starts the listener, which unsubscribes
store.dispatch(increment())
// Second action is ignored
store.dispatch(increment())
// One instance in progress, but not complete
expect(listenerCalls).toBe(1)
expect(workPerformed).toBe(0)
await delay(5)
// In-progress listener not done yet
store.dispatch(increment())
// No changes in status
expect(listenerCalls).toBe(1)
expect(workPerformed).toBe(0)
await delay(50)
// Work finished, should have resubscribed
expect(workPerformed).toBe(1)
// Listener is re-subscribed, will trigger again
store.dispatch(increment())
expect(listenerCalls).toBe(2)
expect(workPerformed).toBe(1)
await delay(50)
expect(workPerformed).toBe(2)
})
test('fork + join', async () => {
// fork starts a child job, join waits for the child to complete and return a value
// Ref: https://redux-saga.js.org/docs/api#forkfn-args
// Ref: https://redux-saga.js.org/docs/api#jointask
let childResult = 0
startListening({
actionCreator: increment,
effect: async (_, listenerApi) => {
const childOutput = 42
// Spawn a child job and start it immediately
const result = await listenerApi.fork(async () => {
// Artificially wait a bit inside the child
await listenerApi.delay(5)
// Complete the child by returning an Outcome-wrapped value
return childOutput
}).result
// Unwrap the child result in the listener
if (result.status === 'ok') {
childResult = result.value
}
},
})
store.dispatch(increment())
await delay(10)
expect(childResult).toBe(42)
})
test('fork + cancel', async () => {
// fork starts a child job, cancel will raise an exception if the
// child is paused in the middle of an effect
// Ref: https://redux-saga.js.org/docs/api#forkfn-args
let childResult = 0
let listenerCompleted = false
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
// Spawn a child job and start it immediately
const forkedTask = listenerApi.fork(async () => {
// Artificially wait a bit inside the child
await listenerApi.delay(15)
// Complete the child by returning an Outcome-wrapped value
childResult = 42
return 0
})
await listenerApi.delay(5)
forkedTask.cancel()
listenerCompleted = true
},
})
// Starts listener, which starts child
store.dispatch(increment())
// Wait for child to have maybe completed
await delay(20)
// Listener finished, but the child was canceled and threw an exception, so it never finished
expect(listenerCompleted).toBe(true)
expect(childResult).toBe(0)
})
test('canceled', async () => {
// canceled allows checking if the current task was canceled
// Ref: https://redux-saga.js.org/docs/api#cancelled
let canceledAndCaught = false
let canceledCheck = false
startListening({
matcher: isAnyOf(increment, decrement, incrementByAmount),
effect: async (action, listenerApi) => {
if (increment.match(action)) {
// Have this branch wait around to be canceled by the other
try {
await listenerApi.delay(10)
} catch (err) {
// Can check cancelation based on the exception and its reason
if (err instanceof TaskAbortError) {
canceledAndCaught = true
}
}
} else if (incrementByAmount.match(action)) {
// do a non-cancelation-aware wait
await delay(15)
if (listenerApi.signal.aborted) {
canceledCheck = true
}
} else if (decrement.match(action)) {
listenerApi.cancelActiveListeners()
}
},
})
// Start first branch
store.dispatch(increment())
// Cancel first listener
store.dispatch(decrement())
// Have to wait for the delay to resolve
// TODO Can we make ``Job.delay()` be a race?
await delay(15)
expect(canceledAndCaught).toBe(true)
// Start second branch
store.dispatch(incrementByAmount(42))
// Cancel second listener, although it won't know about that until later
store.dispatch(decrement())
expect(canceledCheck).toBe(false)
await delay(20)
expect(canceledCheck).toBe(true)
})
test('long-running listener with immediate unsubscribe is cancelable', async () => {
let runCount = 0
let abortCount = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
runCount++
// Stop listening for this action
listenerApi.unsubscribe()
try {
// Wait indefinitely
await listenerApi.condition(() => false)
} catch (err) {
if (err instanceof TaskAbortError) {
abortCount++
}
}
},
})
// First action starts the listener, which unsubscribes
store.dispatch(increment())
expect(runCount).toBe(1)
// Verify that the first action unsubscribed the listener
store.dispatch(increment())
expect(runCount).toBe(1)
// Now call clearListeners, which should abort the running effect, even
// though the listener is no longer subscribed
listenerMiddleware.clearListeners()
await delay(0)
expect(abortCount).toBe(1)
})
test('long-running listener with unsubscribe race is cancelable', async () => {
let runCount = 0
let abortCount = 0
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
runCount++
if (runCount === 2) {
// On the second run, stop listening for this action
listenerApi.unsubscribe()
return
}
try {
// Wait indefinitely
await listenerApi.condition(() => false)
} catch (err) {
if (err instanceof TaskAbortError) {
abortCount++
}
}
},
})
// First action starts the hanging effect
store.dispatch(increment())
expect(runCount).toBe(1)
// Second action starts the fast effect, which unsubscribes
store.dispatch(increment())
expect(runCount).toBe(2)
// Third action should be a noop
store.dispatch(increment())
expect(runCount).toBe(2)
// The hanging effect should still be hanging
expect(abortCount).toBe(0)
// Now call clearListeners, which should abort the hanging effect, even
// though the listener is no longer subscribed
listenerMiddleware.clearListeners()
await delay(0)
expect(abortCount).toBe(1)
})
test('long-running listener with immediate unsubscribe and forked child is cancelable', async () => {
let outerAborted = false
let innerAborted = false
startListening({
actionCreator: increment,
effect: async (action, listenerApi) => {
// Stop listening for this action
listenerApi.unsubscribe()
const pollingTask = listenerApi.fork(async (forkApi) => {
try {
// Cancellation-aware indefinite pause
await forkApi.pause(new Promise(() => {}))
} catch (err) {
if (err instanceof TaskAbortError) {
innerAborted = true
}
}
})
try {
// Wait indefinitely
await listenerApi.condition(() => false)
pollingTask.cancel()
} catch (err) {
if (err instanceof TaskAbortError) {
outerAborted = true
}
}
},
})
store.dispatch(increment())
await delay(0)
listenerMiddleware.clearListeners()
await delay(0)
expect(outerAborted).toBe(true)
expect(innerAborted).toBe(true)
})
})
@@ -0,0 +1,5 @@
export * from './extends-check';
export * from './extends-from-mapped-key';
export * from './extends-from-mapped-result';
export * from './extends-undefined';
export * from './extends';
@@ -0,0 +1,193 @@
// Copyright (c) 2011-2016 Ryan Prichard
//
// 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.
#include "Win32ConsoleBuffer.h"
#include <windows.h>
#include "../shared/DebugClient.h"
#include "../shared/StringBuilder.h"
#include "../shared/WinptyAssert.h"
std::unique_ptr<Win32ConsoleBuffer> Win32ConsoleBuffer::openStdout() {
return std::unique_ptr<Win32ConsoleBuffer>(
new Win32ConsoleBuffer(GetStdHandle(STD_OUTPUT_HANDLE), false));
}
std::unique_ptr<Win32ConsoleBuffer> Win32ConsoleBuffer::openConout() {
const HANDLE conout = CreateFileW(L"CONOUT$",
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, NULL);
ASSERT(conout != INVALID_HANDLE_VALUE);
return std::unique_ptr<Win32ConsoleBuffer>(
new Win32ConsoleBuffer(conout, true));
}
std::unique_ptr<Win32ConsoleBuffer> Win32ConsoleBuffer::createErrorBuffer() {
SECURITY_ATTRIBUTES sa = {};
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
const HANDLE conout =
CreateConsoleScreenBuffer(GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
&sa,
CONSOLE_TEXTMODE_BUFFER,
nullptr);
ASSERT(conout != INVALID_HANDLE_VALUE);
return std::unique_ptr<Win32ConsoleBuffer>(
new Win32ConsoleBuffer(conout, true));
}
HANDLE Win32ConsoleBuffer::conout() {
return m_conout;
}
void Win32ConsoleBuffer::clearLines(
int row,
int count,
const ConsoleScreenBufferInfo &info) {
// TODO: error handling
const int width = info.bufferSize().X;
DWORD actual = 0;
if (!FillConsoleOutputCharacterW(
m_conout, L' ', width * count, Coord(0, row),
&actual) || static_cast<int>(actual) != width * count) {
trace("FillConsoleOutputCharacterW failed");
}
if (!FillConsoleOutputAttribute(
m_conout, kDefaultAttributes, width * count, Coord(0, row),
&actual) || static_cast<int>(actual) != width * count) {
trace("FillConsoleOutputAttribute failed");
}
}
void Win32ConsoleBuffer::clearAllLines(const ConsoleScreenBufferInfo &info) {
clearLines(0, info.bufferSize().Y, info);
}
ConsoleScreenBufferInfo Win32ConsoleBuffer::bufferInfo() {
// TODO: error handling
ConsoleScreenBufferInfo info;
if (!GetConsoleScreenBufferInfo(m_conout, &info)) {
trace("GetConsoleScreenBufferInfo failed");
}
return info;
}
Coord Win32ConsoleBuffer::bufferSize() {
return bufferInfo().bufferSize();
}
SmallRect Win32ConsoleBuffer::windowRect() {
return bufferInfo().windowRect();
}
bool Win32ConsoleBuffer::resizeBufferRange(const Coord &initialSize,
Coord &finalSize) {
if (SetConsoleScreenBufferSize(m_conout, initialSize)) {
finalSize = initialSize;
return true;
}
// The font might be too small to accommodate a very narrow console window.
// In that case, rather than simply give up, it's better to try wider
// buffer sizes until the call succeeds.
Coord size = initialSize;
while (size.X < 20) {
size.X++;
if (SetConsoleScreenBufferSize(m_conout, size)) {
finalSize = size;
trace("SetConsoleScreenBufferSize: initial size (%d,%d) failed, "
"but wider size (%d,%d) succeeded",
initialSize.X, initialSize.Y,
finalSize.X, finalSize.Y);
return true;
}
}
trace("SetConsoleScreenBufferSize failed: "
"tried (%d,%d) through (%d,%d)",
initialSize.X, initialSize.Y,
size.X, size.Y);
return false;
}
void Win32ConsoleBuffer::resizeBuffer(const Coord &size) {
// TODO: error handling
if (!SetConsoleScreenBufferSize(m_conout, size)) {
trace("SetConsoleScreenBufferSize failed: size=(%d,%d)",
size.X, size.Y);
}
}
void Win32ConsoleBuffer::moveWindow(const SmallRect &rect) {
// TODO: error handling
if (!SetConsoleWindowInfo(m_conout, TRUE, &rect)) {
trace("SetConsoleWindowInfo failed");
}
}
Coord Win32ConsoleBuffer::cursorPosition() {
return bufferInfo().dwCursorPosition;
}
void Win32ConsoleBuffer::setCursorPosition(const Coord &coord) {
// TODO: error handling
if (!SetConsoleCursorPosition(m_conout, coord)) {
trace("SetConsoleCursorPosition failed");
}
}
void Win32ConsoleBuffer::read(const SmallRect &rect, CHAR_INFO *data) {
// TODO: error handling
SmallRect tmp(rect);
if (!ReadConsoleOutputW(m_conout, data, rect.size(), Coord(), &tmp) &&
isTracingEnabled()) {
StringBuilder sb(256);
auto outStruct = [&](const SMALL_RECT &sr) {
sb << "{L=" << sr.Left << ",T=" << sr.Top
<< ",R=" << sr.Right << ",B=" << sr.Bottom << '}';
};
sb << "Win32ConsoleBuffer::read: ReadConsoleOutput failed: readRegion=";
outStruct(rect);
CONSOLE_SCREEN_BUFFER_INFO info = {};
if (GetConsoleScreenBufferInfo(m_conout, &info)) {
sb << ", dwSize=(" << info.dwSize.X << ',' << info.dwSize.Y
<< "), srWindow=";
outStruct(info.srWindow);
} else {
sb << ", GetConsoleScreenBufferInfo also failed";
}
trace("%s", sb.c_str());
}
}
void Win32ConsoleBuffer::write(const SmallRect &rect, const CHAR_INFO *data) {
// TODO: error handling
SmallRect tmp(rect);
if (!WriteConsoleOutputW(m_conout, data, rect.size(), Coord(), &tmp)) {
trace("WriteConsoleOutput failed");
}
}
void Win32ConsoleBuffer::setTextAttribute(WORD attributes) {
if (!SetConsoleTextAttribute(m_conout, attributes)) {
trace("SetConsoleTextAttribute failed");
}
}
Loaded 100 of 35554 files, more files were not shown because too many files have changed in this diff. Show more