new license file version [CI SKIP]

This commit is contained in:
2023-03-15 12:34:41 +00:00
parent 0a6d92a1f3
commit 61328d20ed
13115 changed files with 1892314 additions and 1 deletions

View File

@@ -0,0 +1,33 @@
var baseIteratee = require('./_baseIteratee'),
basePullAll = require('./_basePullAll');
/**
* This method is like `_.pullAll` except that it accepts `iteratee` which is
* invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The iteratee is invoked with one argument: (value).
*
* **Note:** Unlike `_.differenceBy`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
*
* _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
* console.log(array);
* // => [{ 'x': 2 }]
*/
function pullAllBy(array, values, iteratee) {
return (array && array.length && values && values.length)
? basePullAll(array, values, baseIteratee(iteratee, 2))
: array;
}
module.exports = pullAllBy;

View File

@@ -0,0 +1,4 @@
export type CreateDonation = {
donor: number;
paidAmount?: number;
};

View File

@@ -0,0 +1,428 @@
# Commander.js
[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
[API documentation](http://tj.github.com/commander.js/)
## Installation
$ npm install commander
## Option parsing
Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq-sauce', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbqSauce) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
```
Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.option('--no-sauce', 'Remove sauce')
.parse(process.argv);
console.log('you ordered a pizza');
if (program.sauce) console.log(' with sauce');
else console.log(' without sauce');
```
To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs.
e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```
Then to access the input if it was passed in.
e.g. ```var myInput = program.myarg```
**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.
## Version option
Calling the `version` implicitly adds the `-V` and `--version` options to the command.
When either of these options is present, the command prints the version number and exits.
$ ./examples/pizza -V
0.0.1
If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method.
```js
program
.version('0.0.1', '-v, --version')
```
The version flags can be named anything, but the long option is required.
## Command-specific options
You can attach options to a command.
```js
#!/usr/bin/env node
var program = require('commander');
program
.command('rm <dir>')
.option('-r, --recursive', 'Remove recursively')
.action(function (dir, cmd) {
console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
})
program.parse(process.argv)
```
A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
## Coercion
```js
function range(val) {
return val.split('..').map(Number);
}
function list(val) {
return val.split(',');
}
function collect(val, memo) {
memo.push(val);
return memo;
}
function increaseVerbosity(v, total) {
return total + 1;
}
program
.version('0.1.0')
.usage('[options] <file ...>')
.option('-i, --integer <n>', 'An integer argument', parseInt)
.option('-f, --float <n>', 'A float argument', parseFloat)
.option('-r, --range <a>..<b>', 'A range', range)
.option('-l, --list <items>', 'A list', list)
.option('-o, --optional [value]', 'An optional value')
.option('-c, --collect [value]', 'A repeatable value', collect, [])
.option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
.parse(process.argv);
console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' collect: %j', program.collect);
console.log(' verbosity: %j', program.verbose);
console.log(' args: %j', program.args);
```
## Regular Expression
```js
program
.version('0.1.0')
.option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
.option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
.parse(process.argv);
console.log(' size: %j', program.size);
console.log(' drink: %j', program.drink);
```
## Variadic arguments
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
append `...` to the argument name. Here is an example:
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.command('rmdir <dir> [otherDirs...]')
.action(function (dir, otherDirs) {
console.log('rmdir %s', dir);
if (otherDirs) {
otherDirs.forEach(function (oDir) {
console.log('rmdir %s', oDir);
});
}
});
program.parse(process.argv);
```
An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
to your action as demonstrated above.
## Specify the argument syntax
```js
#!/usr/bin/env node
var program = require('commander');
program
.version('0.1.0')
.arguments('<cmd> [env]')
.action(function (cmd, env) {
cmdValue = cmd;
envValue = env;
});
program.parse(process.argv);
if (typeof cmdValue === 'undefined') {
console.error('no command given!');
process.exit(1);
}
console.log('command:', cmdValue);
console.log('environment:', envValue || "no environment given");
```
Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
## Git-style sub-commands
```js
// file: ./examples/pm
var program = require('commander');
program
.version('0.1.0')
.command('install [name]', 'install one or more packages')
.command('search [query]', 'search with optional query')
.command('list', 'list packages installed', {isDefault: true})
.parse(process.argv);
```
When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.
Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
### `--harmony`
You can enable `--harmony` option in two ways:
* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version dont support this pattern.
* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.
## Automated --help
The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
```
$ ./examples/pizza --help
Usage: pizza [options]
An application for pizzas ordering
Options:
-h, --help output usage information
-V, --version output the version number
-p, --peppers Add peppers
-P, --pineapple Add pineapple
-b, --bbq Add bbq sauce
-c, --cheese <type> Add the specified type of cheese [marble]
-C, --no-cheese You do not want any cheese
```
## Custom help
You can display arbitrary `-h, --help` information
by listening for "--help". Commander will automatically
exit once you are done so that the remainder of your program
does not execute causing undesired behaviors, for example
in the following executable "stuff" will not output when
`--help` is used.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.option('-f, --foo', 'enable some foo')
.option('-b, --bar', 'enable some bar')
.option('-B, --baz', 'enable some baz');
// must be before .parse() since
// node's emit() is immediate
program.on('--help', function(){
console.log('')
console.log('Examples:');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
});
program.parse(process.argv);
console.log('stuff');
```
Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
```
Usage: custom-help [options]
Options:
-h, --help output usage information
-V, --version output the version number
-f, --foo enable some foo
-b, --bar enable some bar
-B, --baz enable some baz
Examples:
$ custom-help --help
$ custom-help -h
```
## .outputHelp(cb)
Output help information without exiting.
Optional callback cb allows post-processing of help text before it is displayed.
If you want to display help by default (e.g. if no command was provided), you can use something like:
```js
var program = require('commander');
var colors = require('colors');
program
.version('0.1.0')
.command('getstream [url]', 'get stream URL')
.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp(make_red);
}
function make_red(txt) {
return colors.red(txt); //display the help text in red on the console
}
```
## .help(cb)
Output help information and exit immediately.
Optional callback cb allows post-processing of help text before it is displayed.
## Custom event listeners
You can execute custom actions by listening to command and option events.
```js
program.on('option:verbose', function () {
process.env.VERBOSE = this.verbose;
});
// error on unknown commands
program.on('command:*', function () {
console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
process.exit(1);
});
```
## Examples
```js
var program = require('commander');
program
.version('0.1.0')
.option('-C, --chdir <path>', 'change the working directory')
.option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
.option('-T, --no-tests', 'ignore test hook');
program
.command('setup [env]')
.description('run setup commands for all envs')
.option("-s, --setup_mode [mode]", "Which setup mode to use")
.action(function(env, options){
var mode = options.setup_mode || "normal";
env = env || 'all';
console.log('setup for %s env(s) with %s mode', env, mode);
});
program
.command('exec <cmd>')
.alias('ex')
.description('execute the given remote cmd')
.option("-e, --exec_mode <mode>", "Which exec mode to use")
.action(function(cmd, options){
console.log('exec "%s" using %s mode', cmd, options.exec_mode);
}).on('--help', function() {
console.log('');
console.log('Examples:');
console.log('');
console.log(' $ deploy exec sequential');
console.log(' $ deploy exec async');
});
program
.command('*')
.action(function(env){
console.log('deploying "%s"', env);
});
program.parse(process.argv);
```
More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
## License
[MIT](https://github.com/tj/commander.js/blob/master/LICENSE)

View File

@@ -0,0 +1,505 @@
import { Observable } from '../Observable';
import { ColdObservable } from './ColdObservable';
import { HotObservable } from './HotObservable';
import { SubscriptionLog } from './SubscriptionLog';
import { VirtualTimeScheduler, VirtualAction } from '../scheduler/VirtualTimeScheduler';
import { COMPLETE_NOTIFICATION, errorNotification, nextNotification } from '../NotificationFactories';
import { dateTimestampProvider } from '../scheduler/dateTimestampProvider';
import { performanceTimestampProvider } from '../scheduler/performanceTimestampProvider';
import { animationFrameProvider } from '../scheduler/animationFrameProvider';
import { immediateProvider } from '../scheduler/immediateProvider';
import { intervalProvider } from '../scheduler/intervalProvider';
import { timeoutProvider } from '../scheduler/timeoutProvider';
const defaultMaxFrame = 750;
export class TestScheduler extends VirtualTimeScheduler {
constructor(assertDeepEqual) {
super(VirtualAction, defaultMaxFrame);
this.assertDeepEqual = assertDeepEqual;
this.hotObservables = [];
this.coldObservables = [];
this.flushTests = [];
this.runMode = false;
}
createTime(marbles) {
const indexOf = this.runMode ? marbles.trim().indexOf('|') : marbles.indexOf('|');
if (indexOf === -1) {
throw new Error('marble diagram for time should have a completion marker "|"');
}
return indexOf * TestScheduler.frameTimeFactor;
}
createColdObservable(marbles, values, error) {
if (marbles.indexOf('^') !== -1) {
throw new Error('cold observable cannot have subscription offset "^"');
}
if (marbles.indexOf('!') !== -1) {
throw new Error('cold observable cannot have unsubscription marker "!"');
}
const messages = TestScheduler.parseMarbles(marbles, values, error, undefined, this.runMode);
const cold = new ColdObservable(messages, this);
this.coldObservables.push(cold);
return cold;
}
createHotObservable(marbles, values, error) {
if (marbles.indexOf('!') !== -1) {
throw new Error('hot observable cannot have unsubscription marker "!"');
}
const messages = TestScheduler.parseMarbles(marbles, values, error, undefined, this.runMode);
const subject = new HotObservable(messages, this);
this.hotObservables.push(subject);
return subject;
}
materializeInnerObservable(observable, outerFrame) {
const messages = [];
observable.subscribe({
next: (value) => {
messages.push({ frame: this.frame - outerFrame, notification: nextNotification(value) });
},
error: (error) => {
messages.push({ frame: this.frame - outerFrame, notification: errorNotification(error) });
},
complete: () => {
messages.push({ frame: this.frame - outerFrame, notification: COMPLETE_NOTIFICATION });
},
});
return messages;
}
expectObservable(observable, subscriptionMarbles = null) {
const actual = [];
const flushTest = { actual, ready: false };
const subscriptionParsed = TestScheduler.parseMarblesAsSubscriptions(subscriptionMarbles, this.runMode);
const subscriptionFrame = subscriptionParsed.subscribedFrame === Infinity ? 0 : subscriptionParsed.subscribedFrame;
const unsubscriptionFrame = subscriptionParsed.unsubscribedFrame;
let subscription;
this.schedule(() => {
subscription = observable.subscribe({
next: (x) => {
const value = x instanceof Observable ? this.materializeInnerObservable(x, this.frame) : x;
actual.push({ frame: this.frame, notification: nextNotification(value) });
},
error: (error) => {
actual.push({ frame: this.frame, notification: errorNotification(error) });
},
complete: () => {
actual.push({ frame: this.frame, notification: COMPLETE_NOTIFICATION });
},
});
}, subscriptionFrame);
if (unsubscriptionFrame !== Infinity) {
this.schedule(() => subscription.unsubscribe(), unsubscriptionFrame);
}
this.flushTests.push(flushTest);
const { runMode } = this;
return {
toBe(marbles, values, errorValue) {
flushTest.ready = true;
flushTest.expected = TestScheduler.parseMarbles(marbles, values, errorValue, true, runMode);
},
toEqual: (other) => {
flushTest.ready = true;
flushTest.expected = [];
this.schedule(() => {
subscription = other.subscribe({
next: (x) => {
const value = x instanceof Observable ? this.materializeInnerObservable(x, this.frame) : x;
flushTest.expected.push({ frame: this.frame, notification: nextNotification(value) });
},
error: (error) => {
flushTest.expected.push({ frame: this.frame, notification: errorNotification(error) });
},
complete: () => {
flushTest.expected.push({ frame: this.frame, notification: COMPLETE_NOTIFICATION });
},
});
}, subscriptionFrame);
},
};
}
expectSubscriptions(actualSubscriptionLogs) {
const flushTest = { actual: actualSubscriptionLogs, ready: false };
this.flushTests.push(flushTest);
const { runMode } = this;
return {
toBe(marblesOrMarblesArray) {
const marblesArray = typeof marblesOrMarblesArray === 'string' ? [marblesOrMarblesArray] : marblesOrMarblesArray;
flushTest.ready = true;
flushTest.expected = marblesArray
.map((marbles) => TestScheduler.parseMarblesAsSubscriptions(marbles, runMode))
.filter((marbles) => marbles.subscribedFrame !== Infinity);
},
};
}
flush() {
const hotObservables = this.hotObservables;
while (hotObservables.length > 0) {
hotObservables.shift().setup();
}
super.flush();
this.flushTests = this.flushTests.filter((test) => {
if (test.ready) {
this.assertDeepEqual(test.actual, test.expected);
return false;
}
return true;
});
}
static parseMarblesAsSubscriptions(marbles, runMode = false) {
if (typeof marbles !== 'string') {
return new SubscriptionLog(Infinity);
}
const characters = [...marbles];
const len = characters.length;
let groupStart = -1;
let subscriptionFrame = Infinity;
let unsubscriptionFrame = Infinity;
let frame = 0;
for (let i = 0; i < len; i++) {
let nextFrame = frame;
const advanceFrameBy = (count) => {
nextFrame += count * this.frameTimeFactor;
};
const c = characters[i];
switch (c) {
case ' ':
if (!runMode) {
advanceFrameBy(1);
}
break;
case '-':
advanceFrameBy(1);
break;
case '(':
groupStart = frame;
advanceFrameBy(1);
break;
case ')':
groupStart = -1;
advanceFrameBy(1);
break;
case '^':
if (subscriptionFrame !== Infinity) {
throw new Error("found a second subscription point '^' in a " + 'subscription marble diagram. There can only be one.');
}
subscriptionFrame = groupStart > -1 ? groupStart : frame;
advanceFrameBy(1);
break;
case '!':
if (unsubscriptionFrame !== Infinity) {
throw new Error("found a second unsubscription point '!' in a " + 'subscription marble diagram. There can only be one.');
}
unsubscriptionFrame = groupStart > -1 ? groupStart : frame;
break;
default:
if (runMode && c.match(/^[0-9]$/)) {
if (i === 0 || characters[i - 1] === ' ') {
const buffer = characters.slice(i).join('');
const match = buffer.match(/^([0-9]+(?:\.[0-9]+)?)(ms|s|m) /);
if (match) {
i += match[0].length - 1;
const duration = parseFloat(match[1]);
const unit = match[2];
let durationInMs;
switch (unit) {
case 'ms':
durationInMs = duration;
break;
case 's':
durationInMs = duration * 1000;
break;
case 'm':
durationInMs = duration * 1000 * 60;
break;
default:
break;
}
advanceFrameBy(durationInMs / this.frameTimeFactor);
break;
}
}
}
throw new Error("there can only be '^' and '!' markers in a " + "subscription marble diagram. Found instead '" + c + "'.");
}
frame = nextFrame;
}
if (unsubscriptionFrame < 0) {
return new SubscriptionLog(subscriptionFrame);
}
else {
return new SubscriptionLog(subscriptionFrame, unsubscriptionFrame);
}
}
static parseMarbles(marbles, values, errorValue, materializeInnerObservables = false, runMode = false) {
if (marbles.indexOf('!') !== -1) {
throw new Error('conventional marble diagrams cannot have the ' + 'unsubscription marker "!"');
}
const characters = [...marbles];
const len = characters.length;
const testMessages = [];
const subIndex = runMode ? marbles.replace(/^[ ]+/, '').indexOf('^') : marbles.indexOf('^');
let frame = subIndex === -1 ? 0 : subIndex * -this.frameTimeFactor;
const getValue = typeof values !== 'object'
? (x) => x
: (x) => {
if (materializeInnerObservables && values[x] instanceof ColdObservable) {
return values[x].messages;
}
return values[x];
};
let groupStart = -1;
for (let i = 0; i < len; i++) {
let nextFrame = frame;
const advanceFrameBy = (count) => {
nextFrame += count * this.frameTimeFactor;
};
let notification;
const c = characters[i];
switch (c) {
case ' ':
if (!runMode) {
advanceFrameBy(1);
}
break;
case '-':
advanceFrameBy(1);
break;
case '(':
groupStart = frame;
advanceFrameBy(1);
break;
case ')':
groupStart = -1;
advanceFrameBy(1);
break;
case '|':
notification = COMPLETE_NOTIFICATION;
advanceFrameBy(1);
break;
case '^':
advanceFrameBy(1);
break;
case '#':
notification = errorNotification(errorValue || 'error');
advanceFrameBy(1);
break;
default:
if (runMode && c.match(/^[0-9]$/)) {
if (i === 0 || characters[i - 1] === ' ') {
const buffer = characters.slice(i).join('');
const match = buffer.match(/^([0-9]+(?:\.[0-9]+)?)(ms|s|m) /);
if (match) {
i += match[0].length - 1;
const duration = parseFloat(match[1]);
const unit = match[2];
let durationInMs;
switch (unit) {
case 'ms':
durationInMs = duration;
break;
case 's':
durationInMs = duration * 1000;
break;
case 'm':
durationInMs = duration * 1000 * 60;
break;
default:
break;
}
advanceFrameBy(durationInMs / this.frameTimeFactor);
break;
}
}
}
notification = nextNotification(getValue(c));
advanceFrameBy(1);
break;
}
if (notification) {
testMessages.push({ frame: groupStart > -1 ? groupStart : frame, notification });
}
frame = nextFrame;
}
return testMessages;
}
createAnimator() {
if (!this.runMode) {
throw new Error('animate() must only be used in run mode');
}
let lastHandle = 0;
let map;
const delegate = {
requestAnimationFrame(callback) {
if (!map) {
throw new Error('animate() was not called within run()');
}
const handle = ++lastHandle;
map.set(handle, callback);
return handle;
},
cancelAnimationFrame(handle) {
if (!map) {
throw new Error('animate() was not called within run()');
}
map.delete(handle);
},
};
const animate = (marbles) => {
if (map) {
throw new Error('animate() must not be called more than once within run()');
}
if (/[|#]/.test(marbles)) {
throw new Error('animate() must not complete or error');
}
map = new Map();
const messages = TestScheduler.parseMarbles(marbles, undefined, undefined, undefined, true);
for (const message of messages) {
this.schedule(() => {
const now = this.now();
const callbacks = Array.from(map.values());
map.clear();
for (const callback of callbacks) {
callback(now);
}
}, message.frame);
}
};
return { animate, delegate };
}
createDelegates() {
let lastHandle = 0;
const scheduleLookup = new Map();
const run = () => {
const now = this.now();
const scheduledRecords = Array.from(scheduleLookup.values());
const scheduledRecordsDue = scheduledRecords.filter(({ due }) => due <= now);
const dueImmediates = scheduledRecordsDue.filter(({ type }) => type === 'immediate');
if (dueImmediates.length > 0) {
const { handle, handler } = dueImmediates[0];
scheduleLookup.delete(handle);
handler();
return;
}
const dueIntervals = scheduledRecordsDue.filter(({ type }) => type === 'interval');
if (dueIntervals.length > 0) {
const firstDueInterval = dueIntervals[0];
const { duration, handler } = firstDueInterval;
firstDueInterval.due = now + duration;
firstDueInterval.subscription = this.schedule(run, duration);
handler();
return;
}
const dueTimeouts = scheduledRecordsDue.filter(({ type }) => type === 'timeout');
if (dueTimeouts.length > 0) {
const { handle, handler } = dueTimeouts[0];
scheduleLookup.delete(handle);
handler();
return;
}
throw new Error('Expected a due immediate or interval');
};
const immediate = {
setImmediate: (handler) => {
const handle = ++lastHandle;
scheduleLookup.set(handle, {
due: this.now(),
duration: 0,
handle,
handler,
subscription: this.schedule(run, 0),
type: 'immediate',
});
return handle;
},
clearImmediate: (handle) => {
const value = scheduleLookup.get(handle);
if (value) {
value.subscription.unsubscribe();
scheduleLookup.delete(handle);
}
},
};
const interval = {
setInterval: (handler, duration = 0) => {
const handle = ++lastHandle;
scheduleLookup.set(handle, {
due: this.now() + duration,
duration,
handle,
handler,
subscription: this.schedule(run, duration),
type: 'interval',
});
return handle;
},
clearInterval: (handle) => {
const value = scheduleLookup.get(handle);
if (value) {
value.subscription.unsubscribe();
scheduleLookup.delete(handle);
}
},
};
const timeout = {
setTimeout: (handler, duration = 0) => {
const handle = ++lastHandle;
scheduleLookup.set(handle, {
due: this.now() + duration,
duration,
handle,
handler,
subscription: this.schedule(run, duration),
type: 'timeout',
});
return handle;
},
clearTimeout: (handle) => {
const value = scheduleLookup.get(handle);
if (value) {
value.subscription.unsubscribe();
scheduleLookup.delete(handle);
}
},
};
return { immediate, interval, timeout };
}
run(callback) {
const prevFrameTimeFactor = TestScheduler.frameTimeFactor;
const prevMaxFrames = this.maxFrames;
TestScheduler.frameTimeFactor = 1;
this.maxFrames = Infinity;
this.runMode = true;
const animator = this.createAnimator();
const delegates = this.createDelegates();
animationFrameProvider.delegate = animator.delegate;
dateTimestampProvider.delegate = this;
immediateProvider.delegate = delegates.immediate;
intervalProvider.delegate = delegates.interval;
timeoutProvider.delegate = delegates.timeout;
performanceTimestampProvider.delegate = this;
const helpers = {
cold: this.createColdObservable.bind(this),
hot: this.createHotObservable.bind(this),
flush: this.flush.bind(this),
time: this.createTime.bind(this),
expectObservable: this.expectObservable.bind(this),
expectSubscriptions: this.expectSubscriptions.bind(this),
animate: animator.animate,
};
try {
const ret = callback(helpers);
this.flush();
return ret;
}
finally {
TestScheduler.frameTimeFactor = prevFrameTimeFactor;
this.maxFrames = prevMaxFrames;
this.runMode = false;
animationFrameProvider.delegate = undefined;
dateTimestampProvider.delegate = undefined;
immediateProvider.delegate = undefined;
intervalProvider.delegate = undefined;
timeoutProvider.delegate = undefined;
performanceTimestampProvider.delegate = undefined;
}
}
}
TestScheduler.frameTimeFactor = 10;
//# sourceMappingURL=TestScheduler.js.map

View File

@@ -0,0 +1,33 @@
// Returns a wrapper function that returns a wrapped callback
// The wrapper function should do some stuff, and return a
// presumably different callback function.
// This makes sure that own properties are retained, so that
// decorations and such are not lost along the way.
module.exports = wrappy
function wrappy (fn, cb) {
if (fn && cb) return wrappy(fn)(cb)
if (typeof fn !== 'function')
throw new TypeError('need wrapper function')
Object.keys(fn).forEach(function (k) {
wrapper[k] = fn[k]
})
return wrapper
function wrapper() {
var args = new Array(arguments.length)
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
var ret = fn.apply(this, args)
var cb = args[args.length-1]
if (typeof ret === 'function' && ret !== cb) {
Object.keys(cb).forEach(function (k) {
ret[k] = cb[k]
})
}
return ret
}
}

View File

@@ -0,0 +1,32 @@
"use strict";
var assert = require("chai").assert
, safeToString = require("../../lib/safe-to-string");
describe("lib/safe-to-string", function () {
it("Should return input string", function () { assert.equal(safeToString("foo"), "foo"); });
it("Should coerce numbers", function () { assert.equal(safeToString(12), "12"); });
it("Should coerce booleans", function () { assert.equal(safeToString(true), "true"); });
it("Should coerce string objects", function () {
assert.equal(safeToString(new String("bar")), "bar");
});
it("Should coerce objects", function () {
assert.equal(
safeToString({ toString: function () { return "Some object"; } }), "Some object"
);
});
it("Should coerce null", function () { assert.equal(safeToString(null), "null"); });
it("Should coerce undefined", function () {
assert.equal(safeToString(undefined), "undefined");
});
if (typeof Symbol === "function") {
it("Should coerce symbols", function () {
// eslint-disable-next-line no-undef
assert.equal(safeToString(Symbol()), "Symbol()");
});
}
it("Should return null for non coercible values", function () {
assert.equal(safeToString({ toString: null }), null);
});
});

View File

@@ -0,0 +1,412 @@
[![Build status][build-image]][build-url]
[![Tests coverage][cov-image]][cov-url]
[![npm version][npm-image]][npm-url]
# cli-color
## Yet another colors and formatting for the console solution
Colors, formatting and other goodies for the console. This package won't mess with built-ins and provides neat way to predefine formatting patterns, see below.
## Installation
$ npm install cli-color
## Usage
Usage:
```javascript
var clc = require("cli-color");
```
Output colored text:
```javascript
console.log(clc.red("Text in red"));
```
Styles can be mixed:
```javascript
console.log(clc.red.bgWhite.underline("Underlined red text on white background."));
```
Styled text can be mixed with unstyled:
```javascript
console.log(clc.red("red") + " plain " + clc.blue("blue"));
```
Styled text can be nested:
```javascript
console.log(clc.red("red " + clc.blue("blue") + " red"));
```
**Best way is to predefine needed stylings and then use it**:
```javascript
var error = clc.red.bold;
var warn = clc.yellow;
var notice = clc.blue;
console.log(error("Error!"));
console.log(warn("Warning"));
console.log(notice("Notice"));
```
_Note: No colors or styles are output when [`NO_COLOR` env var](https://no-color.org/) is set_
Supported are all ANSI colors and styles:
#### Styles
Styles will display correctly if font used in your console supports them.
- bold
- italic
- underline
- blink
- inverse
- strike
#### Colors
<table>
<thead><th>Foreground</th><th>Background</th><th></th></thead>
<tbody>
<tr><td>black</td><td>bgBlack</td><td><img src="http://medyk.org/colors/000000.png" width="30" height="30" /></td></tr>
<tr><td>red</td><td>bgRed</td><td><img src="http://medyk.org/colors/800000.png" width="30" height="30" /></td></tr>
<tr><td>green</td><td>bgGreen</td><td><img src="http://medyk.org/colors/008000.png" width="30" height="30" /></td></tr>
<tr><td>yellow</td><td>bgYellow</td><td><img src="http://medyk.org/colors/808000.png" width="30" height="30" /></td></tr>
<tr><td>blue</td><td>bgBlue</td><td><img src="http://medyk.org/colors/000080.png" width="30" height="30" /></td></tr>
<tr><td>magenta</td><td>bgMagenta</td><td><img src="http://medyk.org/colors/800080.png" width="30" height="30" /></td></tr>
<tr><td>cyan</td><td>bgCyan</td><td><img src="http://medyk.org/colors/008080.png" width="30" height="30" /></td></tr>
<tr><td>white</td><td>bgWhite</td><td><img src="http://medyk.org/colors/c0c0c0.png" width="30" height="30" /></td></tr>
</tbody>
</table>
##### Bright variants
<table>
<thead><th>Foreground</th><th>Background</th><th></th></thead>
<tbody>
<tr><td>blackBright</td><td>bgBlackBright</td><td><img src="http://medyk.org/colors/808080.png" width="30" height="30" /></td></tr>
<tr><td>redBright</td><td>bgRedBright</td><td><img src="http://medyk.org/colors/ff0000.png" width="30" height="30" /></td></tr>
<tr><td>greenBright</td><td>bgGreenBright</td><td><img src="http://medyk.org/colors/00ff00.png" width="30" height="30" /></td></tr>
<tr><td>yellowBright</td><td>bgYellowBright</td><td><img src="http://medyk.org/colors/ffff00.png" width="30" height="30" /></td></tr>
<tr><td>blueBright</td><td>bgBlueBright</td><td><img src="http://medyk.org/colors/0000ff.png" width="30" height="30" /></td></tr>
<tr><td>magentaBright</td><td>bgMagentaBright</td><td><img src="http://medyk.org/colors/ff00ff.png" width="30" height="30" /></td></tr>
<tr><td>cyanBright</td><td>bgCyanBright</td><td><img src="http://medyk.org/colors/00ffff.png" width="30" height="30" /></td></tr>
<tr><td>whiteBright</td><td>bgWhiteBright</td><td><img src="http://medyk.org/colors/ffffff.png" width="30" height="30" /></td></tr>
</tbody>
</table>
##### xTerm colors (256 colors table)
**Not supported on Windows and some terminals**. However if used in not supported environment, the closest color from basic (16 colors) palette is chosen.
Usage:
```javascript
var msg = clc.xterm(202).bgXterm(236);
console.log(msg("Orange text on dark gray background"));
```
Color table:
<img width="634" alt="Screenshot 2022-07-04 at 12 28 18" src="https://user-images.githubusercontent.com/122434/177136739-64a4bdd1-a1f5-453e-a7a0-55107bbd7922.png">
#### Reset
Terminal can be cleared with `clc.reset`
```javascript
process.stdout.write(clc.reset);
```
#### Erase
##### clc.erase.screen
Entire screen
```javascript
process.stdout.write(clc.erase.screen);
```
##### clc.erase.screenLeft
Left portion of a screen
```javascript
process.stdout.write(clc.erase.screenLeft);
```
##### clc.erase.screenRight
Right portion of a screen
```javascript
process.stdout.write(clc.erase.screenRight);
```
##### clc.erase.line
Current line
```javascript
process.stdout.write(clc.erase.line);
```
##### clc.erase.lineRight
Right portion of current line
```javascript
process.stdout.write(clc.erase.lineRight);
```
##### clc.erase.lineLeft
Left portion of current line
```javascript
process.stdout.write(clc.erase.lineLeft);
```
#### Move around functions
##### clc.move(x, y)
Move cursor _x_ columns and _y_ rows away. Values can be positive or negative, e.g.:
```javascript
process.stdout.write(clc.move(-2, -2)); // Move cursors two columns and two rows back
```
##### clc.move.to(x, y)
Absolute move. Sets cursor position at _x_ column and _y_ row
```javascript
process.stdout.write(clc.move.to(0, 0)); // Move cursor to first row and first column in terminal window
```
##### clc.move.up(n)
Move cursor up _n_ rows
```javascript
process.stdout.write(clc.move.up(2));
```
##### clc.move.down(n)
Move cursor down _n_ rows
```javascript
process.stdout.write(clc.move.down(2));
```
##### clc.move.right(n)
Move cursor right _n_ columns
```javascript
process.stdout.write(clc.move.right(2));
```
##### clc.move.left(n)
Move cursor left _n_ columns
```javascript
process.stdout.write(clc.move.left(2));
```
##### clc.move.lines(n)
Move cursor `n` lines forward if `n` is positive, otherwise `n` lines backward, and place it at line beginning
```javascript
process.stdout.write(clc.move.lines(2));
```
##### clc.move.top
Move cursor to top of a screen
```javascript
process.stdout.write(clc.move.top);
```
##### clc.move.bottom
Move cursor to bottom of a screen
```javascript
process.stdout.write(clc.move.bottom);
```
##### clc.move.lineBegin
Move cursor to begin of a line
```javascript
process.stdout.write(clc.move.lineBegin);
```
##### clc.move.lineEnd
Move cursor to end of a line
```javascript
process.stdout.write(clc.move.lineEnd);
```
#### Terminal characteristics
##### clc.windowSize.width
Returns terminal width
##### clc.windowSize.height
Returns terminal height
### Additional functionalities
#### clc.slice(str[, begin[, end]])
Slice provided string with preservation of eventual ANSI formatting
```javascript
var clc = require("cli-color");
var str = clc.bold("foo") + "bar" + clc.red("elo");
var sliced = clc.slice(str, 1, 7); // Same as: clc.bold('oo') + 'bar' + clc.red('e')
```
#### clc.strip(formatedText)
Strips ANSI formatted string to plain text
```javascript
var ansiStrip = require("cli-color/strip");
var plain = ansiStrip(formatted);
```
#### clc.getStrippedLength(str)
Get actual length of ANSI-formatted string
```javascript
var clc = require("cli-color");
var str = clc.bold("foo") + "bar" + clc.red("elo");
clc.getStrippedLength(str); // 9
```
#### clc.art(text, styleConf)
Create a text-graphical art. Within `styleConf`, string replacements needs to be defined, which are then used to convert `text` to styled graphical text.
```javascript
var text = ".........\n" + ". Hello .\n" + ".........\n";
var style = { ".": clc.yellowBright("X") };
process.stdout.write(clc.art(text, style));
```
#### clc.columns(data[, options])
Outputs aligned table of columns.
`data` is expected to be an array (or other iterable structure) of rows, where each row is also an array (or other iterable structure) of content to display.
Supported `options`:
- `sep`: Custom colums separator (defaults to `|`)
- `columns`: Per column customizations, as e.g. `[{ align: 'right' }, null, { align: 'left' }]`:
- `align`: Possible options: `'left'`, `'right` (efaults to `'left'`)
```javascript
var clc = require("cli-color");
process.stdout.write(
clc.columns([
[clc.bold("First Name"), clc.bold("Last Name"), clc.bold("Age")],
["John", "Doe", 34],
["Martha", "Smith", 20],
["Jan", "Kowalski", 30]
])
);
/* Outputs:
First Name | Last Name | Age
John | Doe | 34
Martha | Smith | 20
Jan | Kowalski | 30
*/
```
##### throbber(write, interval[, format])
Writes throbber string to _write_ function at given _interval_. Optionally throbber output can be formatted with given _format_ function
```javascript
var setupThrobber = require("cli-color/throbber");
var throbber = setupThrobber(function (str) { process.stdout.write(str); }, 200);
throbber.start();
// at any time you can stop/start throbber
throbber.stop();
```
## Tests
$ npm test
## 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.
## Contributors
- [@rentalhost](https://github.com/rentalhost) (David Rodrigues)
- Help with support for nested styles. Introduction of `clc.art` module, and significant improvements to tests coverage
- [@StreetStrider](https://github.com/StreetStrider)
- Implementation of sophistcated `clc.slice` functionality, and introduction of `clc.getStrippedLength` utility
[nix-build-image]: https://semaphoreci.com/api/v1/medikoo-org/cli-color/branches/master/shields_badge.svg
[nix-build-url]: https://semaphoreci.com/medikoo-org/cli-color
[win-build-image]: https://ci.appveyor.com/api/projects/status/mnd4catkeu181ll5?svg=true
[win-build-url]: https://ci.appveyor.com/project/medikoo/cli-color
[transpilation-image]: https://img.shields.io/badge/transpilation-free-brightgreen.svg
[npm-image]: https://img.shields.io/npm/v/cli-color.svg
[npm-url]: https://www.npmjs.com/package/cli-color
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-cli-color?utm_source=npm-cli-color&utm_medium=referral&utm_campaign=readme">Get professional support for cli-color with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
[build-image]: https://github.com/medikoo/cli-color/workflows/Integrate/badge.svg
[build-url]: https://github.com/medikoo/cli-color/actions?query=workflow%3AIntegrate
[cov-image]: https://img.shields.io/codecov/c/github/medikoo/cli-color.svg
[cov-url]: https://codecov.io/gh/medikoo/cli-color
[npm-image]: https://img.shields.io/npm/v/cli-color.svg
[npm-url]: https://www.npmjs.com/package/cli-color

View File

@@ -0,0 +1,32 @@
var listCacheClear = require('./_listCacheClear'),
listCacheDelete = require('./_listCacheDelete'),
listCacheGet = require('./_listCacheGet'),
listCacheHas = require('./_listCacheHas'),
listCacheSet = require('./_listCacheSet');
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;

View File

@@ -0,0 +1,26 @@
let Selector = require('../selector')
let utils = require('../utils')
class FileSelectorButton extends Selector {
constructor(name, prefixes, all) {
super(name, prefixes, all)
if (this.prefixes) {
this.prefixes = utils.uniq(this.prefixes.map(() => '-webkit-'))
}
}
/**
* Return different selectors depend on prefix
*/
prefixed(prefix) {
if (prefix === '-webkit-') {
return '::-webkit-file-upload-button'
}
return `::${prefix}file-selector-button`
}
}
FileSelectorButton.names = ['::file-selector-button']
module.exports = FileSelectorButton

View File

@@ -0,0 +1,41 @@
<p align="center">
<a href="https://tailwindcss.com" target="_blank">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/tailwindlabs/tailwindcss/HEAD/.github/logo-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/tailwindlabs/tailwindcss/HEAD/.github/logo-light.svg">
<img alt="Tailwind CSS" src="https://raw.githubusercontent.com/tailwindlabs/tailwindcss/HEAD/.github/logo-light.svg" width="350" height="70" style="max-width: 100%;">
</picture>
</a>
</p>
<p align="center">
A utility-first CSS framework for rapidly building custom user interfaces.
</p>
<p align="center">
<a href="https://github.com/tailwindlabs/tailwindcss/actions"><img src="https://img.shields.io/github/actions/workflow/status/tailwindlabs/tailwindcss/ci-stable.yml?branch=master" alt="Build Status"></a>
<a href="https://www.npmjs.com/package/tailwindcss"><img src="https://img.shields.io/npm/dt/tailwindcss.svg" alt="Total Downloads"></a>
<a href="https://github.com/tailwindcss/tailwindcss/releases"><img src="https://img.shields.io/npm/v/tailwindcss.svg" alt="Latest Release"></a>
<a href="https://github.com/tailwindcss/tailwindcss/blob/master/LICENSE"><img src="https://img.shields.io/npm/l/tailwindcss.svg" alt="License"></a>
</p>
------
## Documentation
For full documentation, visit [tailwindcss.com](https://tailwindcss.com/).
## Community
For help, discussion about best practices, or any other conversation that would benefit from being searchable:
[Discuss Tailwind CSS on GitHub](https://github.com/tailwindcss/tailwindcss/discussions)
For casual chit-chat with others using the framework:
[Join the Tailwind CSS Discord Server](https://discord.gg/7NF8GNe)
## Contributing
If you're interested in contributing to Tailwind CSS, please read our [contributing docs](https://github.com/tailwindcss/tailwindcss/blob/master/.github/CONTRIBUTING.md) **before submitting a pull request**.

View File

@@ -0,0 +1,9 @@
"use strict";
var isObject = require("../object/is");
module.exports = function (value) {
if (!isObject(value)) return false;
try { return typeof value.then === "function"; }
catch (error) { return false; }
};

View File

@@ -0,0 +1,4 @@
export type TrackIdsNotMatchingError = {
name: string;
message: string;
};

View File

@@ -0,0 +1,35 @@
var baseClone = require('./_baseClone'),
baseConforms = require('./_baseConforms');
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a function that invokes the predicate properties of `source` with
* the corresponding property values of a given object, returning `true` if
* all predicates return truthy, else `false`.
*
* **Note:** The created function is equivalent to `_.conformsTo` with
* `source` partially applied.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 2, 'b': 1 },
* { 'a': 1, 'b': 2 }
* ];
*
* _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
* // => [{ 'a': 1, 'b': 2 }]
*/
function conforms(source) {
return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
}
module.exports = conforms;

View File

@@ -0,0 +1,75 @@
// We define these manually to ensure they're always copied
// even if they would move up the prototype chain
// https://nodejs.org/api/http.html#http_class_http_incomingmessage
const knownProperties = [
'aborted',
'complete',
'headers',
'httpVersion',
'httpVersionMinor',
'httpVersionMajor',
'method',
'rawHeaders',
'rawTrailers',
'setTimeout',
'socket',
'statusCode',
'statusMessage',
'trailers',
'url',
];
export default function mimicResponse(fromStream, toStream) {
if (toStream._readableState.autoDestroy) {
throw new Error('The second stream must have the `autoDestroy` option set to `false`');
}
const fromProperties = new Set([...Object.keys(fromStream), ...knownProperties]);
const properties = {};
for (const property of fromProperties) {
// Don't overwrite existing properties.
if (property in toStream) {
continue;
}
properties[property] = {
get() {
const value = fromStream[property];
const isFunction = typeof value === 'function';
return isFunction ? value.bind(fromStream) : value;
},
set(value) {
fromStream[property] = value;
},
enumerable: true,
configurable: false,
};
}
Object.defineProperties(toStream, properties);
fromStream.once('aborted', () => {
toStream.destroy();
toStream.emit('aborted');
});
fromStream.once('close', () => {
if (fromStream.complete) {
if (toStream.readable) {
toStream.once('end', () => {
toStream.emit('close');
});
} else {
toStream.emit('close');
}
} else {
toStream.emit('close');
}
});
return toStream;
}

View File

@@ -0,0 +1,7 @@
var IMPORT_PREFIX_PATTERN = /^@import/i;
function isImport(value) {
return IMPORT_PREFIX_PATTERN.test(value);
}
module.exports = isImport;

View File

@@ -0,0 +1,116 @@
import { async } from '../scheduler/async';
import { isValidDate } from '../util/isDate';
import { ObservableInput, OperatorFunction, SchedulerLike } from '../types';
import { timeout } from './timeout';
/** @deprecated Replaced with {@link timeout}. Instead of `timeoutWith(someDate, a$, scheduler)`, use the configuration object
* `timeout({ first: someDate, with: () => a$, scheduler })`. Will be removed in v8. */
export function timeoutWith<T, R>(dueBy: Date, switchTo: ObservableInput<R>, scheduler?: SchedulerLike): OperatorFunction<T, T | R>;
/** @deprecated Replaced with {@link timeout}. Instead of `timeoutWith(100, a$, scheduler)`, use the configuration object
* `timeout({ each: 100, with: () => a$, scheduler })`. Will be removed in v8. */
export function timeoutWith<T, R>(waitFor: number, switchTo: ObservableInput<R>, scheduler?: SchedulerLike): OperatorFunction<T, T | R>;
/**
* When the passed timespan elapses before the source emits any given value, it will unsubscribe from the source,
* and switch the subscription to another observable.
*
* <span class="informal">Used to switch to a different observable if your source is being slow.</span>
*
* Useful in cases where:
*
* - You want to switch to a different source that may be faster.
* - You want to notify a user that the data stream is slow.
* - You want to emit a custom error rather than the {@link TimeoutError} emitted
* by the default usage of {@link timeout}.
*
* If the first parameter is passed as Date and the time of the Date arrives before the first value arrives from the source,
* it will unsubscribe from the source and switch the subscription to another observable.
*
* <span class="informal">Use Date object to switch to a different observable if the first value doesn't arrive by a specific time.</span>
*
* Can be used to set a timeout only for the first value, however it's recommended to use the {@link timeout} operator with
* the `first` configuration to get the same effect.
*
* ## Examples
*
* Fallback to a faster observable
*
* ```ts
* import { interval, timeoutWith } from 'rxjs';
*
* const slow$ = interval(1000);
* const faster$ = interval(500);
*
* slow$
* .pipe(timeoutWith(900, faster$))
* .subscribe(console.log);
* ```
*
* Emit your own custom timeout error
*
* ```ts
* import { interval, timeoutWith, throwError } from 'rxjs';
*
* class CustomTimeoutError extends Error {
* constructor() {
* super('It was too slow');
* this.name = 'CustomTimeoutError';
* }
* }
*
* const slow$ = interval(1000);
*
* slow$
* .pipe(timeoutWith(900, throwError(() => new CustomTimeoutError())))
* .subscribe({
* error: err => console.error(err.message)
* });
* ```
*
* @see {@link timeout}
*
* @param due When passed a number, used as the time (in milliseconds) allowed between each value from the source before timeout
* is triggered. When passed a Date, used as the exact time at which the timeout will be triggered if the first value does not arrive.
* @param withObservable The observable to switch to when timeout occurs.
* @param scheduler The scheduler to use with time-related operations within this operator. Defaults to {@link asyncScheduler}
* @return A function that returns an Observable that mirrors behaviour of the
* source Observable, unless timeout happens when it starts emitting values
* from the `ObservableInput` passed as a second parameter.
* @deprecated Replaced with {@link timeout}. Instead of `timeoutWith(100, a$, scheduler)`, use {@link timeout} with the configuration
* object: `timeout({ each: 100, with: () => a$, scheduler })`. Instead of `timeoutWith(someDate, a$, scheduler)`, use {@link timeout}
* with the configuration object: `timeout({ first: someDate, with: () => a$, scheduler })`. Will be removed in v8.
*/
export function timeoutWith<T, R>(
due: number | Date,
withObservable: ObservableInput<R>,
scheduler?: SchedulerLike
): OperatorFunction<T, T | R> {
let first: number | Date | undefined;
let each: number | undefined;
let _with: () => ObservableInput<R>;
scheduler = scheduler ?? async;
if (isValidDate(due)) {
first = due;
} else if (typeof due === 'number') {
each = due;
}
if (withObservable) {
_with = () => withObservable;
} else {
throw new TypeError('No observable provided to switch to');
}
if (first == null && each == null) {
// Ensure timeout was provided at runtime.
throw new TypeError('No timeout provided.');
}
return timeout<T, ObservableInput<R>>({
first,
each,
scheduler,
with: _with,
});
}

View File

@@ -0,0 +1,44 @@
import type {ConditionalKeys} from './conditional-keys';
/**
Pick keys from the shape that matches the given `Condition`.
This is useful when you want to create a new type from a specific subset of an existing type. For example, you might want to pick all the primitive properties from a class and form a new automatically derived type.
@example
```
import type {Primitive, ConditionalPick} from 'type-fest';
class Awesome {
name: string;
successes: number;
failures: bigint;
run() {}
}
type PickPrimitivesFromAwesome = ConditionalPick<Awesome, Primitive>;
//=> {name: string; successes: number; failures: bigint}
```
@example
```
import type {ConditionalPick} from 'type-fest';
interface Example {
a: string;
b: string | number;
c: () => void;
d: {};
}
type StringKeysOnly = ConditionalPick<Example, string>;
//=> {a: string}
```
@category Object
*/
export type ConditionalPick<Base, Condition> = Pick<
Base,
ConditionalKeys<Base, Condition>
>;

View File

@@ -0,0 +1,9 @@
"use strict";
var fn = function (value) { return value > 3; };
module.exports = function () {
var arr = [1, 2, 3, 4, 5, 6];
if (typeof arr.find !== "function") return false;
return arr.find(fn) === 4;
};

View File

@@ -0,0 +1,295 @@
import { __assign } from "tslib";
import { WHITE_SPACE_REGEX } from './regex.generated';
export function parseNumberSkeletonFromString(skeleton) {
if (skeleton.length === 0) {
throw new Error('Number skeleton cannot be empty');
}
// Parse the skeleton
var stringTokens = skeleton
.split(WHITE_SPACE_REGEX)
.filter(function (x) { return x.length > 0; });
var tokens = [];
for (var _i = 0, stringTokens_1 = stringTokens; _i < stringTokens_1.length; _i++) {
var stringToken = stringTokens_1[_i];
var stemAndOptions = stringToken.split('/');
if (stemAndOptions.length === 0) {
throw new Error('Invalid number skeleton');
}
var stem = stemAndOptions[0], options = stemAndOptions.slice(1);
for (var _a = 0, options_1 = options; _a < options_1.length; _a++) {
var option = options_1[_a];
if (option.length === 0) {
throw new Error('Invalid number skeleton');
}
}
tokens.push({ stem: stem, options: options });
}
return tokens;
}
function icuUnitToEcma(unit) {
return unit.replace(/^(.*?)-/, '');
}
var FRACTION_PRECISION_REGEX = /^\.(?:(0+)(\*)?|(#+)|(0+)(#+))$/g;
var SIGNIFICANT_PRECISION_REGEX = /^(@+)?(\+|#+)?[rs]?$/g;
var INTEGER_WIDTH_REGEX = /(\*)(0+)|(#+)(0+)|(0+)/g;
var CONCISE_INTEGER_WIDTH_REGEX = /^(0+)$/;
function parseSignificantPrecision(str) {
var result = {};
if (str[str.length - 1] === 'r') {
result.roundingPriority = 'morePrecision';
}
else if (str[str.length - 1] === 's') {
result.roundingPriority = 'lessPrecision';
}
str.replace(SIGNIFICANT_PRECISION_REGEX, function (_, g1, g2) {
// @@@ case
if (typeof g2 !== 'string') {
result.minimumSignificantDigits = g1.length;
result.maximumSignificantDigits = g1.length;
}
// @@@+ case
else if (g2 === '+') {
result.minimumSignificantDigits = g1.length;
}
// .### case
else if (g1[0] === '#') {
result.maximumSignificantDigits = g1.length;
}
// .@@## or .@@@ case
else {
result.minimumSignificantDigits = g1.length;
result.maximumSignificantDigits =
g1.length + (typeof g2 === 'string' ? g2.length : 0);
}
return '';
});
return result;
}
function parseSign(str) {
switch (str) {
case 'sign-auto':
return {
signDisplay: 'auto',
};
case 'sign-accounting':
case '()':
return {
currencySign: 'accounting',
};
case 'sign-always':
case '+!':
return {
signDisplay: 'always',
};
case 'sign-accounting-always':
case '()!':
return {
signDisplay: 'always',
currencySign: 'accounting',
};
case 'sign-except-zero':
case '+?':
return {
signDisplay: 'exceptZero',
};
case 'sign-accounting-except-zero':
case '()?':
return {
signDisplay: 'exceptZero',
currencySign: 'accounting',
};
case 'sign-never':
case '+_':
return {
signDisplay: 'never',
};
}
}
function parseConciseScientificAndEngineeringStem(stem) {
// Engineering
var result;
if (stem[0] === 'E' && stem[1] === 'E') {
result = {
notation: 'engineering',
};
stem = stem.slice(2);
}
else if (stem[0] === 'E') {
result = {
notation: 'scientific',
};
stem = stem.slice(1);
}
if (result) {
var signDisplay = stem.slice(0, 2);
if (signDisplay === '+!') {
result.signDisplay = 'always';
stem = stem.slice(2);
}
else if (signDisplay === '+?') {
result.signDisplay = 'exceptZero';
stem = stem.slice(2);
}
if (!CONCISE_INTEGER_WIDTH_REGEX.test(stem)) {
throw new Error('Malformed concise eng/scientific notation');
}
result.minimumIntegerDigits = stem.length;
}
return result;
}
function parseNotationOptions(opt) {
var result = {};
var signOpts = parseSign(opt);
if (signOpts) {
return signOpts;
}
return result;
}
/**
* https://github.com/unicode-org/icu/blob/master/docs/userguide/format_parse/numbers/skeletons.md#skeleton-stems-and-options
*/
export function parseNumberSkeleton(tokens) {
var result = {};
for (var _i = 0, tokens_1 = tokens; _i < tokens_1.length; _i++) {
var token = tokens_1[_i];
switch (token.stem) {
case 'percent':
case '%':
result.style = 'percent';
continue;
case '%x100':
result.style = 'percent';
result.scale = 100;
continue;
case 'currency':
result.style = 'currency';
result.currency = token.options[0];
continue;
case 'group-off':
case ',_':
result.useGrouping = false;
continue;
case 'precision-integer':
case '.':
result.maximumFractionDigits = 0;
continue;
case 'measure-unit':
case 'unit':
result.style = 'unit';
result.unit = icuUnitToEcma(token.options[0]);
continue;
case 'compact-short':
case 'K':
result.notation = 'compact';
result.compactDisplay = 'short';
continue;
case 'compact-long':
case 'KK':
result.notation = 'compact';
result.compactDisplay = 'long';
continue;
case 'scientific':
result = __assign(__assign(__assign({}, result), { notation: 'scientific' }), token.options.reduce(function (all, opt) { return (__assign(__assign({}, all), parseNotationOptions(opt))); }, {}));
continue;
case 'engineering':
result = __assign(__assign(__assign({}, result), { notation: 'engineering' }), token.options.reduce(function (all, opt) { return (__assign(__assign({}, all), parseNotationOptions(opt))); }, {}));
continue;
case 'notation-simple':
result.notation = 'standard';
continue;
// https://github.com/unicode-org/icu/blob/master/icu4c/source/i18n/unicode/unumberformatter.h
case 'unit-width-narrow':
result.currencyDisplay = 'narrowSymbol';
result.unitDisplay = 'narrow';
continue;
case 'unit-width-short':
result.currencyDisplay = 'code';
result.unitDisplay = 'short';
continue;
case 'unit-width-full-name':
result.currencyDisplay = 'name';
result.unitDisplay = 'long';
continue;
case 'unit-width-iso-code':
result.currencyDisplay = 'symbol';
continue;
case 'scale':
result.scale = parseFloat(token.options[0]);
continue;
// https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#integer-width
case 'integer-width':
if (token.options.length > 1) {
throw new RangeError('integer-width stems only accept a single optional option');
}
token.options[0].replace(INTEGER_WIDTH_REGEX, function (_, g1, g2, g3, g4, g5) {
if (g1) {
result.minimumIntegerDigits = g2.length;
}
else if (g3 && g4) {
throw new Error('We currently do not support maximum integer digits');
}
else if (g5) {
throw new Error('We currently do not support exact integer digits');
}
return '';
});
continue;
}
// https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#integer-width
if (CONCISE_INTEGER_WIDTH_REGEX.test(token.stem)) {
result.minimumIntegerDigits = token.stem.length;
continue;
}
if (FRACTION_PRECISION_REGEX.test(token.stem)) {
// Precision
// https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#fraction-precision
// precision-integer case
if (token.options.length > 1) {
throw new RangeError('Fraction-precision stems only accept a single optional option');
}
token.stem.replace(FRACTION_PRECISION_REGEX, function (_, g1, g2, g3, g4, g5) {
// .000* case (before ICU67 it was .000+)
if (g2 === '*') {
result.minimumFractionDigits = g1.length;
}
// .### case
else if (g3 && g3[0] === '#') {
result.maximumFractionDigits = g3.length;
}
// .00## case
else if (g4 && g5) {
result.minimumFractionDigits = g4.length;
result.maximumFractionDigits = g4.length + g5.length;
}
else {
result.minimumFractionDigits = g1.length;
result.maximumFractionDigits = g1.length;
}
return '';
});
var opt = token.options[0];
// https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#trailing-zero-display
if (opt === 'w') {
result = __assign(__assign({}, result), { trailingZeroDisplay: 'stripIfInteger' });
}
else if (opt) {
result = __assign(__assign({}, result), parseSignificantPrecision(opt));
}
continue;
}
// https://unicode-org.github.io/icu/userguide/format_parse/numbers/skeletons.html#significant-digits-precision
if (SIGNIFICANT_PRECISION_REGEX.test(token.stem)) {
result = __assign(__assign({}, result), parseSignificantPrecision(token.stem));
continue;
}
var signOpts = parseSign(token.stem);
if (signOpts) {
result = __assign(__assign({}, result), signOpts);
}
var conciseScientificAndEngineeringOpts = parseConciseScientificAndEngineeringStem(token.stem);
if (conciseScientificAndEngineeringOpts) {
result = __assign(__assign({}, result), conciseScientificAndEngineeringOpts);
}
}
return result;
}

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"1":"A B","2":"J D E F CC"},B:{"1":"C K L G M N O","322":"P Q R S T U V W X Y Z a b c d e i j k l m n o p q r s t u f H"},C:{"2":"0 1 2 3 4 5 6 7 8 DC tB I v J D E F A B C K L G M N O w g x y z EC FC","194":"9 AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB uB ZB vB aB bB cB dB eB fB gB hB iB jB kB h lB mB nB oB pB P Q R wB S T U V W X Y Z a b c d e i j k l m n o p q r s t u f H xB yB"},D:{"2":"0 1 2 3 4 5 6 7 8 9 I v J D E F A B C K L G M N O w g x y z AB BB CB DB EB FB GB HB IB JB KB","322":"LB MB NB OB PB QB RB SB TB UB VB WB XB YB uB ZB vB aB bB cB dB eB fB gB hB iB jB kB h lB mB nB oB pB P Q R S T U V W X Y Z a b c d e i j k l m n o p q r s t u f H xB yB GC"},E:{"1":"D E F A B C K L G JC KC LC 0B qB rB 1B MC NC 2B 3B 4B 5B sB 6B 7B 8B 9B OC","2":"I v J HC zB IC"},F:{"2":"0 1 2 3 4 5 6 7 F B C G M N O w g x y z PC QC RC SC qB AC TC rB","322":"8 9 AB 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 aB bB cB dB eB fB gB hB iB jB kB h lB mB nB oB pB P Q R wB S T U V W X Y Z a b c d e"},G:{"1":"E XC YC ZC aC bC cC dC eC fC gC hC iC jC kC lC mC nC 2B 3B 4B 5B sB 6B 7B 8B 9B","2":"zB UC BC VC WC"},H:{"2":"oC"},I:{"2":"tB I f pC qC rC sC BC tC uC"},J:{"2":"D A"},K:{"2":"A B C qB AC rB","322":"h"},L:{"322":"H"},M:{"2":"H"},N:{"1":"A B"},O:{"322":"vC"},P:{"2":"I g wC xC yC zC 0C 0B 1C 2C 3C 4C 5C sB 6C 7C 8C"},Q:{"322":"1B"},R:{"322":"9C"},S:{"194":"AD BD"}},B:1,C:"Audio Tracks"};

View File

@@ -0,0 +1,13 @@
var test = require('tape');
var resolve = require('../');
var path = require('path');
test('subdirs', function (t) {
t.plan(2);
var dir = path.join(__dirname, '/subdirs');
resolve('a/b/c/x.json', { basedir: dir }, function (err, res) {
t.ifError(err);
t.equal(res, path.join(dir, 'node_modules/a/b/c/x.json'));
});
});

View File

@@ -0,0 +1,6 @@
var overArg = require('./_overArg');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;

View File

@@ -0,0 +1,22 @@
'use strict';
var getDay = Date.prototype.getDay;
var tryDateObject = function tryDateGetDayCall(value) {
try {
getDay.call(value);
return true;
} catch (e) {
return false;
}
};
var toStr = Object.prototype.toString;
var dateClass = '[object Date]';
var hasToStringTag = require('has-tostringtag/shams')();
module.exports = function isDateObject(value) {
if (typeof value !== 'object' || value === null) {
return false;
}
return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass;
};

View File

@@ -0,0 +1,22 @@
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
import assertString from './util/assertString';
/* eslint-disable prefer-rest-params */
export default function isByteLength(str, options) {
assertString(str);
var min;
var max;
if (_typeof(options) === 'object') {
min = options.min || 0;
max = options.max;
} else {
// backwards compatibility: isByteLength(str, min [, max])
min = arguments[1];
max = arguments[2];
}
var len = encodeURI(str).split(/%..|./).length - 1;
return len >= min && (typeof max === 'undefined' || len <= max);
}

View File

@@ -0,0 +1,17 @@
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
module.exports = noop;

View File

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

View File

@@ -0,0 +1,2 @@
var r=require("preact"),e=0;function _(_,n,o,t,u,l){var f,i,c={};for(i in n)"ref"==i?f=n[i]:c[i]=n[i];var p={type:_,props:c,key:o,ref:f,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:--e,__source:u,__self:l};if("function"==typeof _&&(f=_.defaultProps))for(i in f)void 0===c[i]&&(c[i]=f[i]);return r.options.vnode&&r.options.vnode(p),p}Object.defineProperty(exports,"Fragment",{enumerable:!0,get:function(){return r.Fragment}}),exports.jsx=_,exports.jsxDEV=_,exports.jsxs=_;
//# sourceMappingURL=jsxRuntime.js.map

View File

@@ -0,0 +1,771 @@
/// <reference lib="esnext.asynciterable" />
/**
* A signal object that allows you to communicate with a request and abort it if required
* via its associated `AbortController` object.
*
* @remarks
* This interface is compatible with the `AbortSignal` interface defined in TypeScript's DOM types.
* It is redefined here, so it can be polyfilled without a DOM, for example with
* {@link https://www.npmjs.com/package/abortcontroller-polyfill | abortcontroller-polyfill} in a Node environment.
*
* @public
*/
export declare interface AbortSignal {
/**
* Whether the request is aborted.
*/
readonly aborted: boolean;
/**
* Add an event listener to be triggered when this signal becomes aborted.
*/
addEventListener(type: 'abort', listener: () => void): void;
/**
* Remove an event listener that was previously added with {@link AbortSignal.addEventListener}.
*/
removeEventListener(type: 'abort', listener: () => void): void;
}
/**
* A queuing strategy that counts the number of bytes in each chunk.
*
* @public
*/
export declare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {
constructor(options: QueuingStrategyInit);
/**
* Returns the high water mark provided to the constructor.
*/
readonly highWaterMark: number;
/**
* Measures the size of `chunk` by returning the value of its `byteLength` property.
*/
readonly size: (chunk: ArrayBufferView) => number;
}
/**
* A queuing strategy that counts the number of chunks.
*
* @public
*/
export declare class CountQueuingStrategy implements QueuingStrategy<any> {
constructor(options: QueuingStrategyInit);
/**
* Returns the high water mark provided to the constructor.
*/
readonly highWaterMark: number;
/**
* Measures the size of `chunk` by always returning 1.
* This ensures that the total queue size is a count of the number of chunks in the queue.
*/
readonly size: (chunk: any) => 1;
}
/**
* A queuing strategy.
*
* @public
*/
export declare interface QueuingStrategy<T = any> {
/**
* A non-negative number indicating the high water mark of the stream using this queuing strategy.
*/
highWaterMark?: number;
/**
* A function that computes and returns the finite non-negative size of the given chunk value.
*/
size?: QueuingStrategySizeCallback<T>;
}
/**
* @public
*/
export declare interface QueuingStrategyInit {
/**
* {@inheritDoc QueuingStrategy.highWaterMark}
*/
highWaterMark: number;
}
declare type QueuingStrategySizeCallback<T = any> = (chunk: T) => number;
declare type ReadableByteStream = ReadableStream<Uint8Array> & {
_readableStreamController: ReadableByteStreamController;
};
/**
* Allows control of a {@link ReadableStream | readable byte stream}'s state and internal queue.
*
* @public
*/
export declare class ReadableByteStreamController {
private constructor();
/**
* Returns the current BYOB pull request, or `null` if there isn't one.
*/
readonly byobRequest: ReadableStreamBYOBRequest | null;
/**
* Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
* over-full. An underlying byte source ought to use this information to determine when and how to apply backpressure.
*/
readonly desiredSize: number | null;
/**
* Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
* the stream, but once those are read, the stream will become closed.
*/
close(): void;
/**
* Enqueues the given chunk chunk in the controlled readable stream.
* The chunk has to be an `ArrayBufferView` instance, or else a `TypeError` will be thrown.
*/
enqueue(chunk: ArrayBufferView): void;
/**
* Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
*/
error(e?: any): void;
}
/**
* A readable stream represents a source of data, from which you can read.
*
* @public
*/
export declare class ReadableStream<R = any> {
constructor(underlyingSource: UnderlyingByteSource, strategy?: {
highWaterMark?: number;
size?: undefined;
});
constructor(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>);
/**
* Whether or not the readable stream is locked to a {@link ReadableStreamDefaultReader | reader}.
*/
readonly locked: boolean;
/**
* Cancels the stream, signaling a loss of interest in the stream by a consumer.
*
* The supplied `reason` argument will be given to the underlying source's {@link UnderlyingSource.cancel | cancel()}
* method, which might or might not use it.
*/
cancel(reason?: any): Promise<void>;
/**
* Creates a {@link ReadableStreamBYOBReader} and locks the stream to the new reader.
*
* This call behaves the same way as the no-argument variant, except that it only works on readable byte streams,
* i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading.
* The returned BYOB reader provides the ability to directly read individual chunks from the stream via its
* {@link ReadableStreamBYOBReader.read | read()} method, into developer-supplied buffers, allowing more precise
* control over allocation.
*/
getReader({ mode }: {
mode: 'byob';
}): ReadableStreamBYOBReader;
/**
* Creates a {@link ReadableStreamDefaultReader} and locks the stream to the new reader.
* While the stream is locked, no other reader can be acquired until this one is released.
*
* This functionality is especially useful for creating abstractions that desire the ability to consume a stream
* in its entirety. By getting a reader for the stream, you can ensure nobody else can interleave reads with yours
* or cancel the stream, which would interfere with your abstraction.
*/
getReader(): ReadableStreamDefaultReader<R>;
/**
* Provides a convenient, chainable way of piping this readable stream through a transform stream
* (or any other `{ writable, readable }` pair). It simply {@link ReadableStream.pipeTo | pipes} the stream
* into the writable side of the supplied pair, and returns the readable side for further use.
*
* Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
*/
pipeThrough<RS extends ReadableStream>(transform: {
readable: RS;
writable: WritableStream<R>;
}, options?: StreamPipeOptions): RS;
/**
* Pipes this readable stream to a given writable stream. The way in which the piping process behaves under
* various error conditions can be customized with a number of passed options. It returns a promise that fulfills
* when the piping process completes successfully, or rejects if any errors were encountered.
*
* Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
*/
pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
/**
* Tees this readable stream, returning a two-element array containing the two resulting branches as
* new {@link ReadableStream} instances.
*
* Teeing a stream will lock it, preventing any other consumer from acquiring a reader.
* To cancel the stream, cancel both of the resulting branches; a composite cancellation reason will then be
* propagated to the stream's underlying source.
*
* Note that the chunks seen in each branch will be the same object. If the chunks are not immutable,
* this could allow interference between the two branches.
*/
tee(): [ReadableStream<R>, ReadableStream<R>];
/**
* Asynchronously iterates over the chunks in the stream's internal queue.
*
* Asynchronously iterating over the stream will lock it, preventing any other consumer from acquiring a reader.
* The lock will be released if the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method
* is called, e.g. by breaking out of the loop.
*
* By default, calling the async iterator's {@link ReadableStreamAsyncIterator.return | return()} method will also
* cancel the stream. To prevent this, use the stream's {@link ReadableStream.values | values()} method, passing
* `true` for the `preventCancel` option.
*/
values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
/**
* {@inheritDoc ReadableStream.values}
*/
[Symbol.asyncIterator]: (options?: ReadableStreamIteratorOptions) => ReadableStreamAsyncIterator<R>;
}
/**
* An async iterator returned by {@link ReadableStream.values}.
*
* @public
*/
export declare interface ReadableStreamAsyncIterator<R> extends AsyncIterator<R> {
next(): Promise<IteratorResult<R, undefined>>;
return(value?: any): Promise<IteratorResult<any>>;
}
/**
* A BYOB reader vended by a {@link ReadableStream}.
*
* @public
*/
export declare class ReadableStreamBYOBReader {
constructor(stream: ReadableByteStream);
/**
* Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
* the reader's lock is released before the stream finishes closing.
*/
readonly closed: Promise<undefined>;
/**
* If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
*/
cancel(reason?: any): Promise<void>;
/**
* Attempts to reads bytes into view, and returns a promise resolved with the result.
*
* If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
*/
read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamBYOBReadResult<T>>;
/**
* Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
* If the associated stream is errored when the lock is released, the reader will appear errored in the same way
* from now on; otherwise, the reader will appear closed.
*
* A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
* the reader's {@link ReadableStreamBYOBReader.read | read()} method has not yet been settled. Attempting to
* do so will throw a `TypeError` and leave the reader locked to the stream.
*/
releaseLock(): void;
}
/**
* A result returned by {@link ReadableStreamBYOBReader.read}.
*
* @public
*/
export declare type ReadableStreamBYOBReadResult<T extends ArrayBufferView> = {
done: false;
value: T;
} | {
done: true;
value: T | undefined;
};
/**
* A pull-into request in a {@link ReadableByteStreamController}.
*
* @public
*/
export declare class ReadableStreamBYOBRequest {
private constructor();
/**
* Returns the view for writing in to, or `null` if the BYOB request has already been responded to.
*/
readonly view: ArrayBufferView | null;
/**
* Indicates to the associated readable byte stream that `bytesWritten` bytes were written into
* {@link ReadableStreamBYOBRequest.view | view}, causing the result be surfaced to the consumer.
*
* After this method is called, {@link ReadableStreamBYOBRequest.view | view} will be transferred and no longer
* modifiable.
*/
respond(bytesWritten: number): void;
/**
* Indicates to the associated readable byte stream that instead of writing into
* {@link ReadableStreamBYOBRequest.view | view}, the underlying byte source is providing a new `ArrayBufferView`,
* which will be given to the consumer of the readable byte stream.
*
* After this method is called, `view` will be transferred and no longer modifiable.
*/
respondWithNewView(view: ArrayBufferView): void;
}
/**
* Allows control of a {@link ReadableStream | readable stream}'s state and internal queue.
*
* @public
*/
export declare class ReadableStreamDefaultController<R> {
private constructor();
/**
* Returns the desired size to fill the controlled stream's internal queue. It can be negative, if the queue is
* over-full. An underlying source ought to use this information to determine when and how to apply backpressure.
*/
readonly desiredSize: number | null;
/**
* Closes the controlled readable stream. Consumers will still be able to read any previously-enqueued chunks from
* the stream, but once those are read, the stream will become closed.
*/
close(): void;
/**
* Enqueues the given chunk `chunk` in the controlled readable stream.
*/
enqueue(chunk: R): void;
/**
* Errors the controlled readable stream, making all future interactions with it fail with the given error `e`.
*/
error(e?: any): void;
}
/**
* A default reader vended by a {@link ReadableStream}.
*
* @public
*/
export declare class ReadableStreamDefaultReader<R = any> {
constructor(stream: ReadableStream<R>);
/**
* Returns a promise that will be fulfilled when the stream becomes closed,
* or rejected if the stream ever errors or the reader's lock is released before the stream finishes closing.
*/
readonly closed: Promise<undefined>;
/**
* If the reader is active, behaves the same as {@link ReadableStream.cancel | stream.cancel(reason)}.
*/
cancel(reason?: any): Promise<void>;
/**
* Returns a promise that allows access to the next chunk from the stream's internal queue, if available.
*
* If reading a chunk causes the queue to become empty, more data will be pulled from the underlying source.
*/
read(): Promise<ReadableStreamDefaultReadResult<R>>;
/**
* Releases the reader's lock on the corresponding stream. After the lock is released, the reader is no longer active.
* If the associated stream is errored when the lock is released, the reader will appear errored in the same way
* from now on; otherwise, the reader will appear closed.
*
* A reader's lock cannot be released while it still has a pending read request, i.e., if a promise returned by
* the reader's {@link ReadableStreamDefaultReader.read | read()} method has not yet been settled. Attempting to
* do so will throw a `TypeError` and leave the reader locked to the stream.
*/
releaseLock(): void;
}
/**
* A result returned by {@link ReadableStreamDefaultReader.read}.
*
* @public
*/
export declare type ReadableStreamDefaultReadResult<T> = {
done: false;
value: T;
} | {
done: true;
value?: undefined;
};
/**
* Options for {@link ReadableStream.values | async iterating} a stream.
*
* @public
*/
export declare interface ReadableStreamIteratorOptions {
preventCancel?: boolean;
}
/**
* A pair of a {@link ReadableStream | readable stream} and {@link WritableStream | writable stream} that can be passed
* to {@link ReadableStream.pipeThrough}.
*
* @public
*/
export declare interface ReadableWritablePair<R, W> {
readable: ReadableStream<R>;
writable: WritableStream<W>;
}
/**
* Options for {@link ReadableStream.pipeTo | piping} a stream.
*
* @public
*/
export declare interface StreamPipeOptions {
/**
* If set to true, {@link ReadableStream.pipeTo} will not abort the writable stream if the readable stream errors.
*/
preventAbort?: boolean;
/**
* If set to true, {@link ReadableStream.pipeTo} will not cancel the readable stream if the writable stream closes
* or errors.
*/
preventCancel?: boolean;
/**
* If set to true, {@link ReadableStream.pipeTo} will not close the writable stream if the readable stream closes.
*/
preventClose?: boolean;
/**
* Can be set to an {@link AbortSignal} to allow aborting an ongoing pipe operation via the corresponding
* `AbortController`. In this case, the source readable stream will be canceled, and the destination writable stream
* aborted, unless the respective options `preventCancel` or `preventAbort` are set.
*/
signal?: AbortSignal;
}
/**
* A transformer for constructing a {@link TransformStream}.
*
* @public
*/
export declare interface Transformer<I = any, O = any> {
/**
* A function that is called immediately during creation of the {@link TransformStream}.
*/
start?: TransformerStartCallback<O>;
/**
* A function called when a new chunk originally written to the writable side is ready to be transformed.
*/
transform?: TransformerTransformCallback<I, O>;
/**
* A function called after all chunks written to the writable side have been transformed by successfully passing
* through {@link Transformer.transform | transform()}, and the writable side is about to be closed.
*/
flush?: TransformerFlushCallback<O>;
readableType?: undefined;
writableType?: undefined;
}
/** @public */
export declare type TransformerFlushCallback<O> = (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
/** @public */
export declare type TransformerStartCallback<O> = (controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
/** @public */
export declare type TransformerTransformCallback<I, O> = (chunk: I, controller: TransformStreamDefaultController<O>) => void | PromiseLike<void>;
/**
* A transform stream consists of a pair of streams: a {@link WritableStream | writable stream},
* known as its writable side, and a {@link ReadableStream | readable stream}, known as its readable side.
* In a manner specific to the transform stream in question, writes to the writable side result in new data being
* made available for reading from the readable side.
*
* @public
*/
export declare class TransformStream<I = any, O = any> {
constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);
/**
* The readable side of the transform stream.
*/
readonly readable: ReadableStream<O>;
/**
* The writable side of the transform stream.
*/
readonly writable: WritableStream<I>;
}
/**
* Allows control of the {@link ReadableStream} and {@link WritableStream} of the associated {@link TransformStream}.
*
* @public
*/
export declare class TransformStreamDefaultController<O> {
private constructor();
/**
* Returns the desired size to fill the readable sides internal queue. It can be negative, if the queue is over-full.
*/
readonly desiredSize: number | null;
/**
* Enqueues the given chunk `chunk` in the readable side of the controlled transform stream.
*/
enqueue(chunk: O): void;
/**
* Errors both the readable side and the writable side of the controlled transform stream, making all future
* interactions with it fail with the given error `e`. Any chunks queued for transformation will be discarded.
*/
error(reason?: any): void;
/**
* Closes the readable side and errors the writable side of the controlled transform stream. This is useful when the
* transformer only needs to consume a portion of the chunks written to the writable side.
*/
terminate(): void;
}
/**
* An underlying byte source for constructing a {@link ReadableStream}.
*
* @public
*/
export declare interface UnderlyingByteSource {
/**
* {@inheritDoc UnderlyingSource.start}
*/
start?: UnderlyingByteSourceStartCallback;
/**
* {@inheritDoc UnderlyingSource.pull}
*/
pull?: UnderlyingByteSourcePullCallback;
/**
* {@inheritDoc UnderlyingSource.cancel}
*/
cancel?: UnderlyingSourceCancelCallback;
/**
* Can be set to "bytes" to signal that the constructed {@link ReadableStream} is a readable byte stream.
* This ensures that the resulting {@link ReadableStream} will successfully be able to vend BYOB readers via its
* {@link ReadableStream.(getReader:1) | getReader()} method.
* It also affects the controller argument passed to the {@link UnderlyingByteSource.start | start()}
* and {@link UnderlyingByteSource.pull | pull()} methods.
*/
type: 'bytes';
/**
* Can be set to a positive integer to cause the implementation to automatically allocate buffers for the
* underlying source code to write into. In this case, when a consumer is using a default reader, the stream
* implementation will automatically allocate an ArrayBuffer of the given size, so that
* {@link ReadableByteStreamController.byobRequest | controller.byobRequest} is always present,
* as if the consumer was using a BYOB reader.
*/
autoAllocateChunkSize?: number;
}
/** @public */
export declare type UnderlyingByteSourcePullCallback = (controller: ReadableByteStreamController) => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingByteSourceStartCallback = (controller: ReadableByteStreamController) => void | PromiseLike<void>;
/**
* An underlying sink for constructing a {@link WritableStream}.
*
* @public
*/
export declare interface UnderlyingSink<W = any> {
/**
* A function that is called immediately during creation of the {@link WritableStream}.
*/
start?: UnderlyingSinkStartCallback;
/**
* A function that is called when a new chunk of data is ready to be written to the underlying sink. The stream
* implementation guarantees that this function will be called only after previous writes have succeeded, and never
* before {@link UnderlyingSink.start | start()} has succeeded or after {@link UnderlyingSink.close | close()} or
* {@link UnderlyingSink.abort | abort()} have been called.
*
* This function is used to actually send the data to the resource presented by the underlying sink, for example by
* calling a lower-level API.
*/
write?: UnderlyingSinkWriteCallback<W>;
/**
* A function that is called after the producer signals, via
* {@link WritableStreamDefaultWriter.close | writer.close()}, that they are done writing chunks to the stream, and
* subsequently all queued-up writes have successfully completed.
*
* This function can perform any actions necessary to finalize or flush writes to the underlying sink, and release
* access to any held resources.
*/
close?: UnderlyingSinkCloseCallback;
/**
* A function that is called after the producer signals, via {@link WritableStream.abort | stream.abort()} or
* {@link WritableStreamDefaultWriter.abort | writer.abort()}, that they wish to abort the stream. It takes as its
* argument the same value as was passed to those methods by the producer.
*
* Writable streams can additionally be aborted under certain conditions during piping; see the definition of the
* {@link ReadableStream.pipeTo | pipeTo()} method for more details.
*
* This function can clean up any held resources, much like {@link UnderlyingSink.close | close()}, but perhaps with
* some custom handling.
*/
abort?: UnderlyingSinkAbortCallback;
type?: undefined;
}
/** @public */
export declare type UnderlyingSinkAbortCallback = (reason: any) => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingSinkCloseCallback = () => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingSinkStartCallback = (controller: WritableStreamDefaultController) => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingSinkWriteCallback<W> = (chunk: W, controller: WritableStreamDefaultController) => void | PromiseLike<void>;
/**
* An underlying source for constructing a {@link ReadableStream}.
*
* @public
*/
export declare interface UnderlyingSource<R = any> {
/**
* A function that is called immediately during creation of the {@link ReadableStream}.
*/
start?: UnderlyingSourceStartCallback<R>;
/**
* A function that is called whenever the streams internal queue of chunks becomes not full,
* i.e. whenever the queues desired size becomes positive. Generally, it will be called repeatedly
* until the queue reaches its high water mark (i.e. until the desired size becomes non-positive).
*/
pull?: UnderlyingSourcePullCallback<R>;
/**
* A function that is called whenever the consumer cancels the stream, via
* {@link ReadableStream.cancel | stream.cancel()},
* {@link ReadableStreamDefaultReader.cancel | defaultReader.cancel()}, or
* {@link ReadableStreamBYOBReader.cancel | byobReader.cancel()}.
* It takes as its argument the same value as was passed to those methods by the consumer.
*/
cancel?: UnderlyingSourceCancelCallback;
type?: undefined;
}
/** @public */
export declare type UnderlyingSourceCancelCallback = (reason: any) => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingSourcePullCallback<R> = (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
/** @public */
export declare type UnderlyingSourceStartCallback<R> = (controller: ReadableStreamDefaultController<R>) => void | PromiseLike<void>;
/**
* A writable stream represents a destination for data, into which you can write.
*
* @public
*/
export declare class WritableStream<W = any> {
constructor(underlyingSink?: UnderlyingSink<W>, strategy?: QueuingStrategy<W>);
/**
* Returns whether or not the writable stream is locked to a writer.
*/
readonly locked: boolean;
/**
* Aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be
* immediately moved to an errored state, with any queued-up writes discarded. This will also execute any abort
* mechanism of the underlying sink.
*
* The returned promise will fulfill if the stream shuts down successfully, or reject if the underlying sink signaled
* that there was an error doing so. Additionally, it will reject with a `TypeError` (without attempting to cancel
* the stream) if the stream is currently locked.
*/
abort(reason?: any): Promise<void>;
/**
* Closes the stream. The underlying sink will finish processing any previously-written chunks, before invoking its
* close behavior. During this time any further attempts to write will fail (without erroring the stream).
*
* The method returns a promise that will fulfill if all remaining chunks are successfully written and the stream
* successfully closes, or rejects if an error is encountered during this process. Additionally, it will reject with
* a `TypeError` (without attempting to cancel the stream) if the stream is currently locked.
*/
close(): Promise<undefined>;
/**
* Creates a {@link WritableStreamDefaultWriter | writer} and locks the stream to the new writer. While the stream
* is locked, no other writer can be acquired until this one is released.
*
* This functionality is especially useful for creating abstractions that desire the ability to write to a stream
* without interruption or interleaving. By getting a writer for the stream, you can ensure nobody else can write at
* the same time, which would cause the resulting written data to be unpredictable and probably useless.
*/
getWriter(): WritableStreamDefaultWriter<W>;
}
/**
* Allows control of a {@link WritableStream | writable stream}'s state and internal queue.
*
* @public
*/
export declare class WritableStreamDefaultController<W = any> {
private constructor();
/**
* The reason which was passed to `WritableStream.abort(reason)` when the stream was aborted.
*
* @deprecated
* This property has been removed from the specification, see https://github.com/whatwg/streams/pull/1177.
* Use {@link WritableStreamDefaultController.signal}'s `reason` instead.
*/
readonly abortReason: any;
/**
* An `AbortSignal` that can be used to abort the pending write or close operation when the stream is aborted.
*/
readonly signal: AbortSignal;
/**
* Closes the controlled writable stream, making all future interactions with it fail with the given error `e`.
*
* This method is rarely used, since usually it suffices to return a rejected promise from one of the underlying
* sink's methods. However, it can be useful for suddenly shutting down a stream in response to an event outside the
* normal lifecycle of interactions with the underlying sink.
*/
error(e?: any): void;
}
/**
* A default writer vended by a {@link WritableStream}.
*
* @public
*/
export declare class WritableStreamDefaultWriter<W = any> {
constructor(stream: WritableStream<W>);
/**
* Returns a promise that will be fulfilled when the stream becomes closed, or rejected if the stream ever errors or
* the writers lock is released before the stream finishes closing.
*/
readonly closed: Promise<undefined>;
/**
* Returns the desired size to fill the streams internal queue. It can be negative, if the queue is over-full.
* A producer can use this information to determine the right amount of data to write.
*
* It will be `null` if the stream cannot be successfully written to (due to either being errored, or having an abort
* queued up). It will return zero if the stream is closed. And the getter will throw an exception if invoked when
* the writers lock is released.
*/
readonly desiredSize: number | null;
/**
* Returns a promise that will be fulfilled when the desired size to fill the streams internal queue transitions
* from non-positive to positive, signaling that it is no longer applying backpressure. Once the desired size dips
* back to zero or below, the getter will return a new promise that stays pending until the next transition.
*
* If the stream becomes errored or aborted, or the writers lock is released, the returned promise will become
* rejected.
*/
readonly ready: Promise<undefined>;
/**
* If the reader is active, behaves the same as {@link WritableStream.abort | stream.abort(reason)}.
*/
abort(reason?: any): Promise<void>;
/**
* If the reader is active, behaves the same as {@link WritableStream.close | stream.close()}.
*/
close(): Promise<void>;
/**
* Releases the writers lock on the corresponding stream. After the lock is released, the writer is no longer active.
* If the associated stream is errored when the lock is released, the writer will appear errored in the same way from
* now on; otherwise, the writer will appear closed.
*
* Note that the lock can still be released even if some ongoing writes have not yet finished (i.e. even if the
* promises returned from previous calls to {@link WritableStreamDefaultWriter.write | write()} have not yet settled).
* Its not necessary to hold the lock on the writer for the duration of the write; the lock instead simply prevents
* other producers from writing in an interleaved manner.
*/
releaseLock(): void;
/**
* Writes the given chunk to the writable stream, by waiting until any previous writes have finished successfully,
* and then sending the chunk to the underlying sink's {@link UnderlyingSink.write | write()} method. It will return
* a promise that fulfills with undefined upon a successful write, or rejects if the write fails or stream becomes
* errored before the writing process is initiated.
*
* Note that what "success" means is up to the underlying sink; it might indicate simply that the chunk has been
* accepted, and not necessarily that it is safely saved to its ultimate destination.
*/
write(chunk: W): Promise<void>;
}
export { }

View File

@@ -0,0 +1,225 @@
/**
* `rawlist` type prompt
*/
import chalk from 'chalk';
import { map, takeUntil } from 'rxjs';
import Base from './base.js';
import Separator from '../objects/separator.js';
import observe from '../utils/events.js';
import Paginator from '../utils/paginator.js';
import incrementListIndex from '../utils/incrementListIndex.js';
export default class RawListPrompt extends Base {
constructor(questions, rl, answers) {
super(questions, rl, answers);
this.hiddenLine = '';
this.lastKey = '';
if (!this.opt.choices) {
this.throwParamError('choices');
}
this.opt.validChoices = this.opt.choices.filter(Separator.exclude);
this.selected = 0;
this.rawDefault = 0;
Object.assign(this.opt, {
validate(val) {
return val != null;
},
});
const def = this.opt.default;
if (typeof def === 'number' && def >= 0 && def < this.opt.choices.realLength) {
this.selected = def;
this.rawDefault = def;
} else if (typeof def !== 'number' && def != null) {
const index = this.opt.choices.realChoices.findIndex(({ value }) => value === def);
const safeIndex = Math.max(index, 0);
this.selected = safeIndex;
this.rawDefault = safeIndex;
}
// Make sure no default is set (so it won't be printed)
this.opt.default = null;
const shouldLoop = this.opt.loop === undefined ? true : this.opt.loop;
this.paginator = new Paginator(undefined, { isInfinite: shouldLoop });
}
/**
* Start the Inquiry session
* @param {Function} cb Callback when prompt is done
* @return {this}
*/
_run(cb) {
this.done = cb;
// Once user confirm (enter key)
const events = observe(this.rl);
const submit = events.line.pipe(map(this.getCurrentValue.bind(this)));
const validation = this.handleSubmitEvents(submit);
validation.success.forEach(this.onEnd.bind(this));
validation.error.forEach(this.onError.bind(this));
events.normalizedUpKey
.pipe(takeUntil(validation.success))
.forEach(this.onUpKey.bind(this));
events.normalizedDownKey
.pipe(takeUntil(validation.success))
.forEach(this.onDownKey.bind(this));
events.keypress
.pipe(takeUntil(validation.success))
.forEach(this.onKeypress.bind(this));
// Init the prompt
this.render();
return this;
}
/**
* Render the prompt to screen
* @return {RawListPrompt} self
*/
render(error) {
// Render question
let message = this.getQuestion();
let bottomContent = '';
if (this.status === 'answered') {
message += chalk.cyan(this.opt.choices.getChoice(this.selected).short);
} else {
const choicesStr = renderChoices(this.opt.choices, this.selected);
message +=
'\n' + this.paginator.paginate(choicesStr, this.selected, this.opt.pageSize);
message += '\n Answer: ';
}
message += this.rl.line;
if (error) {
bottomContent = '\n' + chalk.red('>> ') + error;
}
this.screen.render(message, bottomContent);
}
/**
* When user press `enter` key
*/
getCurrentValue(index) {
if (index == null) {
index = this.rawDefault;
} else if (index === '') {
this.selected = this.selected === undefined ? -1 : this.selected;
index = this.selected;
} else {
index -= 1;
}
const choice = this.opt.choices.getChoice(index);
return choice ? choice.value : null;
}
onEnd(state) {
this.status = 'answered';
this.answer = state.value;
// Re-render prompt
this.render();
this.screen.done();
this.done(state.value);
}
onError() {
this.render('Please enter a valid index');
}
/**
* When user press a key
*/
onKeypress() {
let index;
if (this.lastKey === 'arrow') {
index = this.hiddenLine.length ? Number(this.hiddenLine) - 1 : 0;
} else {
index = this.rl.line.length ? Number(this.rl.line) - 1 : 0;
}
this.lastKey = '';
if (this.opt.choices.getChoice(index)) {
this.selected = index;
} else {
this.selected = undefined;
}
this.render();
}
/**
* When user press up key
*/
onUpKey() {
this.onArrowKey('up');
}
/**
* When user press down key
*/
onDownKey() {
this.onArrowKey('down');
}
/**
* When user press up or down key
* @param {String} type Arrow type: up or down
*/
onArrowKey(type) {
this.selected = incrementListIndex(this.selected, type, this.opt) || 0;
this.hiddenLine = String(this.selected + 1);
this.rl.line = '';
this.lastKey = 'arrow';
}
}
/**
* Function for rendering list choices
* @param {Number} pointer Position of the pointer
* @return {String} Rendered content
*/
function renderChoices(choices, pointer) {
let output = '';
let separatorOffset = 0;
choices.forEach((choice, i) => {
output += output ? '\n ' : ' ';
if (choice.type === 'separator') {
separatorOffset++;
output += ' ' + choice;
return;
}
const index = i - separatorOffset;
let display = index + 1 + ') ' + choice.name;
if (index === pointer) {
display = chalk.cyan(display);
}
output += display;
});
return output;
}

View File

@@ -0,0 +1,86 @@
{
"name": "is-regex",
"version": "1.1.4",
"description": "Is this value a JS regex? Works cross-realm/iframe, and despite ES6 @@toStringTag",
"author": "Jordan Harband <ljharb@gmail.com>",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"license": "MIT",
"main": "index.js",
"scripts": {
"prepublishOnly": "safe-publish-latest",
"prepublish": "not-in-publish || npm run prepublishOnly",
"pretest": "npm run lint",
"test": "npm run tests-only && npm run test:harmony",
"tests-only": "nyc node test",
"test:harmony": "nyc node --harmony --es-staging test",
"test:corejs": "nyc tape test-corejs.js",
"posttest": "npx aud --production",
"lint": "eslint .",
"eccheck": "eclint check *.js **/*.js > /dev/null",
"version": "auto-changelog && git add CHANGELOG.md",
"postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""
},
"repository": {
"type": "git",
"url": "git://github.com/inspect-js/is-regex.git"
},
"bugs": {
"url": "https://github.com/inspect-js/is-regex/issues"
},
"homepage": "https://github.com/inspect-js/is-regex",
"keywords": [
"regex",
"regexp",
"is",
"regular expression",
"regular",
"expression"
],
"dependencies": {
"call-bind": "^1.0.2",
"has-tostringtag": "^1.0.0"
},
"devDependencies": {
"@ljharb/eslint-config": "^17.6.0",
"aud": "^1.1.5",
"auto-changelog": "^2.3.0",
"core-js": "^3.16.0",
"eclint": "^2.8.1",
"eslint": "^7.32.0",
"foreach": "^2.0.5",
"nyc": "^10.3.2",
"safe-publish-latest": "^1.1.4",
"tape": "^5.3.0"
},
"testling": {
"files": "test/index.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2"
]
},
"engines": {
"node": ">= 0.4"
},
"auto-changelog": {
"output": "CHANGELOG.md",
"template": "keepachangelog",
"unreleased": false,
"commitLimit": false,
"backfillLimit": false,
"hideCredit": true
}
}

View File

@@ -0,0 +1,654 @@
'use strict';
const fs = require('fs');
const sysPath = require('path');
const { promisify } = require('util');
const isBinaryPath = require('is-binary-path');
const {
isWindows,
isLinux,
EMPTY_FN,
EMPTY_STR,
KEY_LISTENERS,
KEY_ERR,
KEY_RAW,
HANDLER_KEYS,
EV_CHANGE,
EV_ADD,
EV_ADD_DIR,
EV_ERROR,
STR_DATA,
STR_END,
BRACE_START,
STAR
} = require('./constants');
const THROTTLE_MODE_WATCH = 'watch';
const open = promisify(fs.open);
const stat = promisify(fs.stat);
const lstat = promisify(fs.lstat);
const close = promisify(fs.close);
const fsrealpath = promisify(fs.realpath);
const statMethods = { lstat, stat };
// TODO: emit errors properly. Example: EMFILE on Macos.
const foreach = (val, fn) => {
if (val instanceof Set) {
val.forEach(fn);
} else {
fn(val);
}
};
const addAndConvert = (main, prop, item) => {
let container = main[prop];
if (!(container instanceof Set)) {
main[prop] = container = new Set([container]);
}
container.add(item);
};
const clearItem = cont => key => {
const set = cont[key];
if (set instanceof Set) {
set.clear();
} else {
delete cont[key];
}
};
const delFromSet = (main, prop, item) => {
const container = main[prop];
if (container instanceof Set) {
container.delete(item);
} else if (container === item) {
delete main[prop];
}
};
const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
/**
* @typedef {String} Path
*/
// fs_watch helpers
// object to hold per-process fs_watch instances
// (may be shared across chokidar FSWatcher instances)
/**
* @typedef {Object} FsWatchContainer
* @property {Set} listeners
* @property {Set} errHandlers
* @property {Set} rawEmitters
* @property {fs.FSWatcher=} watcher
* @property {Boolean=} watcherUnusable
*/
/**
* @type {Map<String,FsWatchContainer>}
*/
const FsWatchInstances = new Map();
/**
* Instantiates the fs_watch interface
* @param {String} path to be watched
* @param {Object} options to be passed to fs_watch
* @param {Function} listener main event handler
* @param {Function} errHandler emits info about errors
* @param {Function} emitRaw emits raw event data
* @returns {fs.FSWatcher} new fsevents instance
*/
function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
const handleEvent = (rawEvent, evPath) => {
listener(path);
emitRaw(rawEvent, evPath, {watchedPath: path});
// emit based on events occurring for files from a directory's watcher in
// case the file's watcher misses it (and rely on throttling to de-dupe)
if (evPath && path !== evPath) {
fsWatchBroadcast(
sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath)
);
}
};
try {
return fs.watch(path, options, handleEvent);
} catch (error) {
errHandler(error);
}
}
/**
* Helper for passing fs_watch event data to a collection of listeners
* @param {Path} fullPath absolute path bound to fs_watch instance
* @param {String} type listener type
* @param {*=} val1 arguments to be passed to listeners
* @param {*=} val2
* @param {*=} val3
*/
const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
const cont = FsWatchInstances.get(fullPath);
if (!cont) return;
foreach(cont[type], (listener) => {
listener(val1, val2, val3);
});
};
/**
* Instantiates the fs_watch interface or binds listeners
* to an existing one covering the same file system entry
* @param {String} path
* @param {String} fullPath absolute path
* @param {Object} options to be passed to fs_watch
* @param {Object} handlers container for event listener functions
*/
const setFsWatchListener = (path, fullPath, options, handlers) => {
const {listener, errHandler, rawEmitter} = handlers;
let cont = FsWatchInstances.get(fullPath);
/** @type {fs.FSWatcher=} */
let watcher;
if (!options.persistent) {
watcher = createFsWatchInstance(
path, options, listener, errHandler, rawEmitter
);
return watcher.close.bind(watcher);
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_ERR, errHandler);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
watcher = createFsWatchInstance(
path,
options,
fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
errHandler, // no need to use broadcast here
fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
);
if (!watcher) return;
watcher.on(EV_ERROR, async (error) => {
const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
cont.watcherUnusable = true; // documented since Node 10.4.1
// Workaround for https://github.com/joyent/node/issues/4337
if (isWindows && error.code === 'EPERM') {
try {
const fd = await open(path, 'r');
await close(fd);
broadcastErr(error);
} catch (err) {}
} else {
broadcastErr(error);
}
});
cont = {
listeners: listener,
errHandlers: errHandler,
rawEmitters: rawEmitter,
watcher
};
FsWatchInstances.set(fullPath, cont);
}
// const index = cont.listeners.indexOf(listener);
// removes this instance's listeners and closes the underlying fs_watch
// instance if there are no more listeners left
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_ERR, errHandler);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
// Check to protect against issue gh-730.
// if (cont.watcherUnusable) {
cont.watcher.close();
// }
FsWatchInstances.delete(fullPath);
HANDLER_KEYS.forEach(clearItem(cont));
cont.watcher = undefined;
Object.freeze(cont);
}
};
};
// fs_watchFile helpers
// object to hold per-process fs_watchFile instances
// (may be shared across chokidar FSWatcher instances)
const FsWatchFileInstances = new Map();
/**
* Instantiates the fs_watchFile interface or binds listeners
* to an existing one covering the same file system entry
* @param {String} path to be watched
* @param {String} fullPath absolute path
* @param {Object} options options to be passed to fs_watchFile
* @param {Object} handlers container for event listener functions
* @returns {Function} closer
*/
const setFsWatchFileListener = (path, fullPath, options, handlers) => {
const {listener, rawEmitter} = handlers;
let cont = FsWatchFileInstances.get(fullPath);
/* eslint-disable no-unused-vars, prefer-destructuring */
let listeners = new Set();
let rawEmitters = new Set();
const copts = cont && cont.options;
if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
// "Upgrade" the watcher to persistence or a quicker interval.
// This creates some unlikely edge case issues if the user mixes
// settings in a very weird way, but solving for those cases
// doesn't seem worthwhile for the added complexity.
listeners = cont.listeners;
rawEmitters = cont.rawEmitters;
fs.unwatchFile(fullPath);
cont = undefined;
}
/* eslint-enable no-unused-vars, prefer-destructuring */
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
// TODO
// listeners.add(listener);
// rawEmitters.add(rawEmitter);
cont = {
listeners: listener,
rawEmitters: rawEmitter,
options,
watcher: fs.watchFile(fullPath, options, (curr, prev) => {
foreach(cont.rawEmitters, (rawEmitter) => {
rawEmitter(EV_CHANGE, fullPath, {curr, prev});
});
const currmtime = curr.mtimeMs;
if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
foreach(cont.listeners, (listener) => listener(path, curr));
}
})
};
FsWatchFileInstances.set(fullPath, cont);
}
// const index = cont.listeners.indexOf(listener);
// Removes this instance's listeners and closes the underlying fs_watchFile
// instance if there are no more listeners left.
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
FsWatchFileInstances.delete(fullPath);
fs.unwatchFile(fullPath);
cont.options = cont.watcher = undefined;
Object.freeze(cont);
}
};
};
/**
* @mixin
*/
class NodeFsHandler {
/**
* @param {import("../index").FSWatcher} fsW
*/
constructor(fsW) {
this.fsw = fsW;
this._boundHandleError = (error) => fsW._handleError(error);
}
/**
* Watch file for changes with fs_watchFile or fs_watch.
* @param {String} path to file or dir
* @param {Function} listener on fs change
* @returns {Function} closer for the watcher instance
*/
_watchWithNodeFs(path, listener) {
const opts = this.fsw.options;
const directory = sysPath.dirname(path);
const basename = sysPath.basename(path);
const parent = this.fsw._getWatchedDir(directory);
parent.add(basename);
const absolutePath = sysPath.resolve(path);
const options = {persistent: opts.persistent};
if (!listener) listener = EMPTY_FN;
let closer;
if (opts.usePolling) {
options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
opts.binaryInterval : opts.interval;
closer = setFsWatchFileListener(path, absolutePath, options, {
listener,
rawEmitter: this.fsw._emitRaw
});
} else {
closer = setFsWatchListener(path, absolutePath, options, {
listener,
errHandler: this._boundHandleError,
rawEmitter: this.fsw._emitRaw
});
}
return closer;
}
/**
* Watch a file and emit add event if warranted.
* @param {Path} file Path
* @param {fs.Stats} stats result of fs_stat
* @param {Boolean} initialAdd was the file added at watch instantiation?
* @returns {Function} closer for the watcher instance
*/
_handleFile(file, stats, initialAdd) {
if (this.fsw.closed) {
return;
}
const dirname = sysPath.dirname(file);
const basename = sysPath.basename(file);
const parent = this.fsw._getWatchedDir(dirname);
// stats is always present
let prevStats = stats;
// if the file is already being watched, do nothing
if (parent.has(basename)) return;
const listener = async (path, newStats) => {
if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
if (!newStats || newStats.mtimeMs === 0) {
try {
const newStats = await stat(file);
if (this.fsw.closed) return;
// Check that change event was not fired because of changed only accessTime.
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV_CHANGE, file, newStats);
}
if (isLinux && prevStats.ino !== newStats.ino) {
this.fsw._closeFile(path)
prevStats = newStats;
this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
} else {
prevStats = newStats;
}
} catch (error) {
// Fix issues where mtime is null but file is still present
this.fsw._remove(dirname, basename);
}
// add is about to be emitted if file not already tracked in parent
} else if (parent.has(basename)) {
// Check that change event was not fired because of changed only accessTime.
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV_CHANGE, file, newStats);
}
prevStats = newStats;
}
}
// kick off the watcher
const closer = this._watchWithNodeFs(file, listener);
// emit an add event if we're supposed to
if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
if (!this.fsw._throttle(EV_ADD, file, 0)) return;
this.fsw._emit(EV_ADD, file, stats);
}
return closer;
}
/**
* Handle symlinks encountered while reading a dir.
* @param {Object} entry returned by readdirp
* @param {String} directory path of dir being read
* @param {String} path of this item
* @param {String} item basename of this item
* @returns {Promise<Boolean>} true if no more processing is needed for this entry.
*/
async _handleSymlink(entry, directory, path, item) {
if (this.fsw.closed) {
return;
}
const full = entry.fullPath;
const dir = this.fsw._getWatchedDir(directory);
if (!this.fsw.options.followSymlinks) {
// watch symlink directly (don't follow) and detect changes
this.fsw._incrReadyCount();
let linkPath;
try {
linkPath = await fsrealpath(path);
} catch (e) {
this.fsw._emitReady();
return true;
}
if (this.fsw.closed) return;
if (dir.has(item)) {
if (this.fsw._symlinkPaths.get(full) !== linkPath) {
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV_CHANGE, path, entry.stats);
}
} else {
dir.add(item);
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV_ADD, path, entry.stats);
}
this.fsw._emitReady();
return true;
}
// don't follow the same symlink more than once
if (this.fsw._symlinkPaths.has(full)) {
return true;
}
this.fsw._symlinkPaths.set(full, true);
}
_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
// Normalize the directory name on Windows
directory = sysPath.join(directory, EMPTY_STR);
if (!wh.hasGlob) {
throttler = this.fsw._throttle('readdir', directory, 1000);
if (!throttler) return;
}
const previous = this.fsw._getWatchedDir(wh.path);
const current = new Set();
let stream = this.fsw._readdirp(directory, {
fileFilter: entry => wh.filterPath(entry),
directoryFilter: entry => wh.filterDir(entry),
depth: 0
}).on(STR_DATA, async (entry) => {
if (this.fsw.closed) {
stream = undefined;
return;
}
const item = entry.path;
let path = sysPath.join(directory, item);
current.add(item);
if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
return;
}
if (this.fsw.closed) {
stream = undefined;
return;
}
// Files that present in current directory snapshot
// but absent in previous are added to watch list and
// emit `add` event.
if (item === target || !target && !previous.has(item)) {
this.fsw._incrReadyCount();
// ensure relativeness of path is preserved in case of watcher reuse
path = sysPath.join(dir, sysPath.relative(dir, path));
this._addToNodeFs(path, initialAdd, wh, depth + 1);
}
}).on(EV_ERROR, this._boundHandleError);
return new Promise(resolve =>
stream.once(STR_END, () => {
if (this.fsw.closed) {
stream = undefined;
return;
}
const wasThrottled = throttler ? throttler.clear() : false;
resolve();
// Files that absent in current directory snapshot
// but present in previous emit `remove` event
// and are removed from @watched[directory].
previous.getChildren().filter((item) => {
return item !== directory &&
!current.has(item) &&
// in case of intersecting globs;
// a path may have been filtered out of this readdir, but
// shouldn't be removed because it matches a different glob
(!wh.hasGlob || wh.filterPath({
fullPath: sysPath.resolve(directory, item)
}));
}).forEach((item) => {
this.fsw._remove(directory, item);
});
stream = undefined;
// one more time for any missed in case changes came in extremely quickly
if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
})
);
}
/**
* Read directory to add / remove files from `@watched` list and re-read it on change.
* @param {String} dir fs path
* @param {fs.Stats} stats
* @param {Boolean} initialAdd
* @param {Number} depth relative to user-supplied path
* @param {String} target child path targeted for watch
* @param {Object} wh Common watch helpers for this path
* @param {String} realpath
* @returns {Promise<Function>} closer for the watcher instance.
*/
async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
const tracked = parentDir.has(sysPath.basename(dir));
if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats);
}
// ensure dir is tracked (harmless if redundant)
parentDir.add(sysPath.basename(dir));
this.fsw._getWatchedDir(dir);
let throttler;
let closer;
const oDepth = this.fsw.options.depth;
if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
if (!target) {
await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
if (this.fsw.closed) return;
}
closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
// if current directory is removed, do nothing
if (stats && stats.mtimeMs === 0) return;
this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
});
}
return closer;
}
/**
* Handle added file, directory, or glob pattern.
* Delegates call to _handleFile / _handleDir after checks.
* @param {String} path to file or ir
* @param {Boolean} initialAdd was the file added at watch instantiation?
* @param {Object} priorWh depth relative to user-supplied path
* @param {Number} depth Child path actually targeted for watch
* @param {String=} target Child path actually targeted for watch
* @returns {Promise}
*/
async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
const ready = this.fsw._emitReady;
if (this.fsw._isIgnored(path) || this.fsw.closed) {
ready();
return false;
}
const wh = this.fsw._getWatchHelpers(path, depth);
if (!wh.hasGlob && priorWh) {
wh.hasGlob = priorWh.hasGlob;
wh.globFilter = priorWh.globFilter;
wh.filterPath = entry => priorWh.filterPath(entry);
wh.filterDir = entry => priorWh.filterDir(entry);
}
// evaluate what is at the path we're being asked to watch
try {
const stats = await statMethods[wh.statMethod](wh.watchPath);
if (this.fsw.closed) return;
if (this.fsw._isIgnored(wh.watchPath, stats)) {
ready();
return false;
}
const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START);
let closer;
if (stats.isDirectory()) {
const absPath = sysPath.resolve(path);
const targetPath = follow ? await fsrealpath(path) : path;
if (this.fsw.closed) return;
closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
if (this.fsw.closed) return;
// preserve this symlink's target path
if (absPath !== targetPath && targetPath !== undefined) {
this.fsw._symlinkPaths.set(absPath, targetPath);
}
} else if (stats.isSymbolicLink()) {
const targetPath = follow ? await fsrealpath(path) : path;
if (this.fsw.closed) return;
const parent = sysPath.dirname(wh.watchPath);
this.fsw._getWatchedDir(parent).add(wh.watchPath);
this.fsw._emit(EV_ADD, wh.watchPath, stats);
closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
if (this.fsw.closed) return;
// preserve this symlink's target path
if (targetPath !== undefined) {
this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
}
} else {
closer = this._handleFile(wh.watchPath, stats, initialAdd);
}
ready();
this.fsw._addPathCloser(path, closer);
return false;
} catch (error) {
if (this.fsw._handleError(error)) {
ready();
return path;
}
}
}
}
module.exports = NodeFsHandler;

View File

@@ -0,0 +1,81 @@
<!doctype html>
<html lang="en">
<head>
<title>Code coverage report for test.ts</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="prettify.css" />
<link rel="stylesheet" href="base.css" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type='text/css'>
.coverage-summary .sorter {
background-image: url(sort-arrow-sprite.png);
}
</style>
</head>
<body>
<div class='wrapper'>
<div class='pad1'>
<h1>
<a href="index.html">All files</a> test.ts
</h1>
<div class='clearfix'>
<div class='fl pad1y space-right2'>
<span class="strong">0% </span>
<span class="quiet">Statements</span>
<span class='fraction'>0/0</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">0% </span>
<span class="quiet">Branches</span>
<span class='fraction'>0/0</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">0% </span>
<span class="quiet">Functions</span>
<span class='fraction'>0/0</span>
</div>
<div class='fl pad1y space-right2'>
<span class="strong">0% </span>
<span class="quiet">Lines</span>
<span class='fraction'>0/0</span>
</div>
</div>
<p class="quiet">
Press <em>n</em> or <em>j</em> to go to the next uncovered block, <em>b</em>, <em>p</em> or <em>k</em> for the previous block.
</p>
</div>
<div class='status-line low'></div>
<pre><table class="coverage">
<tr><td class="line-count quiet"><a name='L1'></a><a href='#L1'>1</a>
<a name='L2'></a><a href='#L2'>2</a>
<a name='L3'></a><a href='#L3'>3</a>
<a name='L4'></a><a href='#L4'>4</a>
<a name='L5'></a><a href='#L5'>5</a></td><td class="line-coverage quiet"><span class="cline-any cline-neutral">&nbsp;</span>
<span class="cline-any cline-neutral">&nbsp;</span>
<span class="cline-any cline-neutral">&nbsp;</span>
<span class="cline-any cline-neutral">&nbsp;</span>
<span class="cline-any cline-neutral">&nbsp;</span></td><td class="text"><pre class="prettyprint lang-js">import a from "./index";
&nbsp;
&nbsp;
// a("sss","CCc");
&nbsp;</pre></td></tr>
</table></pre>
<div class='push'></div><!-- for sticky footer -->
</div><!-- /wrapper -->
<div class='footer quiet pad2 space-top1 center small'>
Code coverage
generated by <a href="https://istanbul.js.org/" target="_blank">istanbul</a> at Fri May 11 2018 21:39:11 GMT+0100 (IST)
</div>
</div>
<script src="prettify.js"></script>
<script>
window.onload = function () {
if (typeof prettyPrint === 'function') {
prettyPrint();
}
};
</script>
<script src="sorter.js"></script>
<script src="block-navigation.js"></script>
</body>
</html>

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"J D E F A B CC"},B:{"1":"P Q R S T U V W X Y Z a b c d e i j k l m n o p q r s t u f H","2":"C K L G M N O"},C:{"1":"hB iB jB kB h lB mB nB oB pB P Q R wB S T U V W X Y Z a b c d e i j k l m n o p q r s t u f H xB yB","2":"0 1 2 3 4 5 6 7 8 9 DC tB I v J D E F A B C K L G M N O w g x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB uB ZB vB aB bB cB dB eB fB gB EC FC"},D:{"1":"cB dB eB fB gB hB iB jB kB h lB mB nB oB pB P Q R S T U V W X Y Z a b c d e i j k l m n o p q r s t u f H xB yB GC","2":"0 1 2 3 4 5 6 7 8 9 I v J D E F A B C K L G M N O w g x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB","194":"UB VB WB XB YB uB ZB vB aB bB"},E:{"1":"L G 1B MC NC 2B 3B 4B 5B sB 6B 7B 8B 9B OC","2":"I v J D E F A B C HC zB IC JC KC LC 0B qB rB","66":"K"},F:{"1":"SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB h lB mB nB oB pB P Q R wB S T U V W X Y Z a b c d e","2":"0 1 2 3 4 5 6 7 8 9 F B C G M N O w g x y z AB BB CB DB EB FB GB PC QC RC SC qB AC TC rB","194":"HB IB JB KB LB MB NB OB PB QB RB"},G:{"1":"kC lC mC nC 2B 3B 4B 5B sB 6B 7B 8B 9B","2":"E zB UC BC VC WC XC YC ZC aC bC cC dC eC fC gC hC iC jC"},H:{"2":"oC"},I:{"1":"f","2":"tB I pC qC rC sC BC tC uC"},J:{"2":"D A"},K:{"1":"h","2":"A B C qB AC rB"},L:{"1":"H"},M:{"1":"H"},N:{"2":"A B"},O:{"1":"vC"},P:{"1":"g 0C 0B 1C 2C 3C 4C 5C sB 6C 7C 8C","2":"I wC xC yC zC"},Q:{"1":"1B"},R:{"1":"9C"},S:{"1":"BD","2":"AD"}},B:5,C:"Resize Observer"};

View File

@@ -0,0 +1,2 @@
export declare type TimerHandle = number | ReturnType<typeof setTimeout>;
//# sourceMappingURL=timerHandle.d.ts.map

View File

@@ -0,0 +1,248 @@
'use strict'
let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js')
let { fileURLToPath, pathToFileURL } = require('url')
let { resolve, isAbsolute } = require('path')
let { nanoid } = require('nanoid/non-secure')
let terminalHighlight = require('./terminal-highlight')
let CssSyntaxError = require('./css-syntax-error')
let PreviousMap = require('./previous-map')
let fromOffsetCache = Symbol('fromOffsetCache')
let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator)
let pathAvailable = Boolean(resolve && isAbsolute)
class Input {
constructor(css, opts = {}) {
if (
css === null ||
typeof css === 'undefined' ||
(typeof css === 'object' && !css.toString)
) {
throw new Error(`PostCSS received ${css} instead of CSS string`)
}
this.css = css.toString()
if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
this.hasBOM = true
this.css = this.css.slice(1)
} else {
this.hasBOM = false
}
if (opts.from) {
if (
!pathAvailable ||
/^\w+:\/\//.test(opts.from) ||
isAbsolute(opts.from)
) {
this.file = opts.from
} else {
this.file = resolve(opts.from)
}
}
if (pathAvailable && sourceMapAvailable) {
let map = new PreviousMap(this.css, opts)
if (map.text) {
this.map = map
let file = map.consumer().file
if (!this.file && file) this.file = this.mapResolve(file)
}
}
if (!this.file) {
this.id = '<input css ' + nanoid(6) + '>'
}
if (this.map) this.map.file = this.from
}
fromOffset(offset) {
let lastLine, lineToIndex
if (!this[fromOffsetCache]) {
let lines = this.css.split('\n')
lineToIndex = new Array(lines.length)
let prevIndex = 0
for (let i = 0, l = lines.length; i < l; i++) {
lineToIndex[i] = prevIndex
prevIndex += lines[i].length + 1
}
this[fromOffsetCache] = lineToIndex
} else {
lineToIndex = this[fromOffsetCache]
}
lastLine = lineToIndex[lineToIndex.length - 1]
let min = 0
if (offset >= lastLine) {
min = lineToIndex.length - 1
} else {
let max = lineToIndex.length - 2
let mid
while (min < max) {
mid = min + ((max - min) >> 1)
if (offset < lineToIndex[mid]) {
max = mid - 1
} else if (offset >= lineToIndex[mid + 1]) {
min = mid + 1
} else {
min = mid
break
}
}
}
return {
line: min + 1,
col: offset - lineToIndex[min] + 1
}
}
error(message, line, column, opts = {}) {
let result, endLine, endColumn
if (line && typeof line === 'object') {
let start = line
let end = column
if (typeof start.offset === 'number') {
let pos = this.fromOffset(start.offset)
line = pos.line
column = pos.col
} else {
line = start.line
column = start.column
}
if (typeof end.offset === 'number') {
let pos = this.fromOffset(end.offset)
endLine = pos.line
endColumn = pos.col
} else {
endLine = end.line
endColumn = end.column
}
} else if (!column) {
let pos = this.fromOffset(line)
line = pos.line
column = pos.col
}
let origin = this.origin(line, column, endLine, endColumn)
if (origin) {
result = new CssSyntaxError(
message,
origin.endLine === undefined
? origin.line
: { line: origin.line, column: origin.column },
origin.endLine === undefined
? origin.column
: { line: origin.endLine, column: origin.endColumn },
origin.source,
origin.file,
opts.plugin
)
} else {
result = new CssSyntaxError(
message,
endLine === undefined ? line : { line, column },
endLine === undefined ? column : { line: endLine, column: endColumn },
this.css,
this.file,
opts.plugin
)
}
result.input = { line, column, endLine, endColumn, source: this.css }
if (this.file) {
if (pathToFileURL) {
result.input.url = pathToFileURL(this.file).toString()
}
result.input.file = this.file
}
return result
}
origin(line, column, endLine, endColumn) {
if (!this.map) return false
let consumer = this.map.consumer()
let from = consumer.originalPositionFor({ line, column })
if (!from.source) return false
let to
if (typeof endLine === 'number') {
to = consumer.originalPositionFor({ line: endLine, column: endColumn })
}
let fromUrl
if (isAbsolute(from.source)) {
fromUrl = pathToFileURL(from.source)
} else {
fromUrl = new URL(
from.source,
this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile)
)
}
let result = {
url: fromUrl.toString(),
line: from.line,
column: from.column,
endLine: to && to.line,
endColumn: to && to.column
}
if (fromUrl.protocol === 'file:') {
if (fileURLToPath) {
result.file = fileURLToPath(fromUrl)
} else {
/* c8 ignore next 2 */
throw new Error(`file: protocol is not available in this PostCSS build`)
}
}
let source = consumer.sourceContentFor(from.source)
if (source) result.source = source
return result
}
mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file
}
return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file)
}
get from() {
return this.file || this.id
}
toJSON() {
let json = {}
for (let name of ['hasBOM', 'css', 'file', 'id']) {
if (this[name] != null) {
json[name] = this[name]
}
}
if (this.map) {
json.map = { ...this.map }
if (json.map.consumerCache) {
json.map.consumerCache = undefined
}
}
return json
}
}
module.exports = Input
Input.default = Input
if (terminalHighlight && terminalHighlight.registerInput) {
terminalHighlight.registerInput(Input)
}

View File

@@ -0,0 +1,88 @@
'use strict';
const {signalsByName} = require('human-signals');
const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {
if (timedOut) {
return `timed out after ${timeout} milliseconds`;
}
if (isCanceled) {
return 'was canceled';
}
if (errorCode !== undefined) {
return `failed with ${errorCode}`;
}
if (signal !== undefined) {
return `was killed with ${signal} (${signalDescription})`;
}
if (exitCode !== undefined) {
return `failed with exit code ${exitCode}`;
}
return 'failed';
};
const makeError = ({
stdout,
stderr,
all,
error,
signal,
exitCode,
command,
escapedCommand,
timedOut,
isCanceled,
killed,
parsed: {options: {timeout}}
}) => {
// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.
// We normalize them to `undefined`
exitCode = exitCode === null ? undefined : exitCode;
signal = signal === null ? undefined : signal;
const signalDescription = signal === undefined ? undefined : signalsByName[signal].description;
const errorCode = error && error.code;
const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});
const execaMessage = `Command ${prefix}: ${command}`;
const isError = Object.prototype.toString.call(error) === '[object Error]';
const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage;
const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n');
if (isError) {
error.originalMessage = error.message;
error.message = message;
} else {
error = new Error(message);
}
error.shortMessage = shortMessage;
error.command = command;
error.escapedCommand = escapedCommand;
error.exitCode = exitCode;
error.signal = signal;
error.signalDescription = signalDescription;
error.stdout = stdout;
error.stderr = stderr;
if (all !== undefined) {
error.all = all;
}
if ('bufferedData' in error) {
delete error.bufferedData;
}
error.failed = true;
error.timedOut = Boolean(timedOut);
error.isCanceled = isCanceled;
error.killed = killed && !timedOut;
return error;
};
module.exports = makeError;

View File

@@ -0,0 +1 @@
{"version":3,"file":"sampleTime.js","sourceRoot":"","sources":["../../../../src/internal/operators/sampleTime.ts"],"names":[],"mappings":";;;AAAA,4CAAoD;AAEpD,mCAAkC;AAClC,mDAAkD;AA6ClD,SAAgB,UAAU,CAAI,MAAc,EAAE,SAAyC;IAAzC,0BAAA,EAAA,YAA2B,sBAAc;IACrF,OAAO,eAAM,CAAC,mBAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;AAC7C,CAAC;AAFD,gCAEC"}

View File

@@ -0,0 +1,29 @@
/** Used as the internal argument placeholder. */
var PLACEHOLDER = '__lodash_placeholder__';
/**
* Replaces all `placeholder` elements in `array` with an internal placeholder
* and returns an array of their indexes.
*
* @private
* @param {Array} array The array to modify.
* @param {*} placeholder The placeholder to replace.
* @returns {Array} Returns the new array of placeholder indexes.
*/
function replaceHolders(array, placeholder) {
var index = -1,
length = array.length,
resIndex = 0,
result = [];
while (++index < length) {
var value = array[index];
if (value === placeholder || value === PLACEHOLDER) {
array[index] = PLACEHOLDER;
result[resIndex++] = index;
}
}
return result;
}
module.exports = replaceHolders;

View File

@@ -0,0 +1 @@
{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["src/pbkdf2.ts"],"names":[],"mappings":";;;AAAA,6CAAkC;AAClC,uCAAiC;AACjC,yCAA2F;AAQ3F,wDAAwD;AACxD,SAAS,UAAU,CAAC,IAAW,EAAE,SAAgB,EAAE,KAAY,EAAE,KAAgB;IAC/E,oBAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,MAAM,IAAI,GAAG,IAAA,oBAAS,EAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,oBAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACjB,oBAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACrB,oBAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACzB,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IACpE,MAAM,QAAQ,GAAG,IAAA,kBAAO,EAAC,SAAS,CAAC,CAAC;IACpC,MAAM,IAAI,GAAG,IAAA,kBAAO,EAAC,KAAK,CAAC,CAAC;IAC5B,8CAA8C;IAC9C,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACjC,0CAA0C;IAC1C,MAAM,GAAG,GAAG,cAAI,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACxC,MAAM,OAAO,GAAG,GAAG,CAAC,UAAU,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAC9C,OAAO,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC;AACnD,CAAC;AAED,SAAS,YAAY,CACnB,GAAY,EACZ,OAAgB,EAChB,EAAc,EACd,IAAa,EACb,CAAa;IAEb,GAAG,CAAC,OAAO,EAAE,CAAC;IACd,OAAO,CAAC,OAAO,EAAE,CAAC;IAClB,IAAI,IAAI;QAAE,IAAI,CAAC,OAAO,EAAE,CAAC;IACzB,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACV,OAAO,EAAE,CAAC;AACZ,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,MAAM,CAAC,IAAW,EAAE,QAAe,EAAE,IAAW,EAAE,IAAe;IAC/E,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,UAAU,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IAC9E,IAAI,IAAS,CAAC,CAAC,eAAe;IAC9B,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,IAAA,qBAAU,EAAC,GAAG,CAAC,CAAC;IAC7B,MAAM,CAAC,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACxC,iCAAiC;IACjC,KAAK,IAAI,EAAE,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,GAAG,CAAC,SAAS,EAAE;QACjE,+BAA+B;QAC/B,MAAM,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QAC5B,6CAA6C;QAC7C,0CAA0C;QAC1C,CAAC,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC5D,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACjC,KAAK,IAAI,EAAE,GAAG,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,EAAE,EAAE,EAAE;YAC7B,2BAA2B;YAC3B,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;SACnD;KACF;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC;AAtBD,wBAsBC;AAEM,KAAK,UAAU,WAAW,CAAC,IAAW,EAAE,QAAe,EAAE,IAAW,EAAE,IAAe;IAC1F,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,UAAU,CAAC,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IACzF,IAAI,IAAS,CAAC,CAAC,eAAe;IAC9B,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;IAC9B,MAAM,IAAI,GAAG,IAAA,qBAAU,EAAC,GAAG,CAAC,CAAC;IAC7B,MAAM,CAAC,GAAG,IAAI,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACxC,iCAAiC;IACjC,KAAK,IAAI,EAAE,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,KAAK,EAAE,EAAE,EAAE,EAAE,GAAG,IAAI,GAAG,CAAC,SAAS,EAAE;QACjE,+BAA+B;QAC/B,MAAM,EAAE,GAAG,EAAE,CAAC,QAAQ,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,CAAC,SAAS,CAAC,CAAC;QACjD,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;QAC5B,6CAA6C;QAC7C,0CAA0C;QAC1C,CAAC,IAAI,GAAG,OAAO,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC5D,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;QACjC,MAAM,IAAA,oBAAS,EAAC,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE;YACtC,2BAA2B;YAC3B,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;KACJ;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC;AAtBD,kCAsBC"}

View File

@@ -0,0 +1,2 @@
module.exports.web=require("./web");
module.exports.cli=require("./cli");

View File

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

View File

@@ -0,0 +1,147 @@
/* eslint max-statements: 0 */
// Support for functions returning promise
"use strict";
var objectMap = require("es5-ext/object/map")
, primitiveSet = require("es5-ext/object/primitive-set")
, ensureString = require("es5-ext/object/validate-stringifiable-value")
, toShortString = require("es5-ext/to-short-string-representation")
, isPromise = require("is-promise")
, nextTick = require("next-tick");
var create = Object.create
, supportedModes = primitiveSet("then", "then:finally", "done", "done:finally");
require("../lib/registered-extensions").promise = function (mode, conf) {
var waiting = create(null), cache = create(null), promises = create(null);
if (mode === true) {
mode = null;
} else {
mode = ensureString(mode);
if (!supportedModes[mode]) {
throw new TypeError("'" + toShortString(mode) + "' is not valid promise mode");
}
}
// After not from cache call
conf.on("set", function (id, ignore, promise) {
var isFailed = false;
if (!isPromise(promise)) {
// Non promise result
cache[id] = promise;
conf.emit("setasync", id, 1);
return;
}
waiting[id] = 1;
promises[id] = promise;
var onSuccess = function (result) {
var count = waiting[id];
if (isFailed) {
throw new Error(
"Memoizee error: Detected unordered then|done & finally resolution, which " +
"in turn makes proper detection of success/failure impossible (when in " +
"'done:finally' mode)\n" +
"Consider to rely on 'then' or 'done' mode instead."
);
}
if (!count) return; // Deleted from cache before resolved
delete waiting[id];
cache[id] = result;
conf.emit("setasync", id, count);
};
var onFailure = function () {
isFailed = true;
if (!waiting[id]) return; // Deleted from cache (or succeed in case of finally)
delete waiting[id];
delete promises[id];
conf.delete(id);
};
var resolvedMode = mode;
if (!resolvedMode) resolvedMode = "then";
if (resolvedMode === "then") {
var nextTickFailure = function () { nextTick(onFailure); };
// Eventual finally needs to be attached to non rejected promise
// (so we not force propagation of unhandled rejection)
promise = promise.then(function (result) {
nextTick(onSuccess.bind(this, result));
}, nextTickFailure);
// If `finally` is a function we attach to it to remove cancelled promises.
if (typeof promise.finally === "function") {
promise.finally(nextTickFailure);
}
} else if (resolvedMode === "done") {
// Not recommended, as it may mute any eventual "Unhandled error" events
if (typeof promise.done !== "function") {
throw new Error(
"Memoizee error: Retrieved promise does not implement 'done' " +
"in 'done' mode"
);
}
promise.done(onSuccess, onFailure);
} else if (resolvedMode === "done:finally") {
// The only mode with no side effects assuming library does not throw unconditionally
// for rejected promises.
if (typeof promise.done !== "function") {
throw new Error(
"Memoizee error: Retrieved promise does not implement 'done' " +
"in 'done:finally' mode"
);
}
if (typeof promise.finally !== "function") {
throw new Error(
"Memoizee error: Retrieved promise does not implement 'finally' " +
"in 'done:finally' mode"
);
}
promise.done(onSuccess);
promise.finally(onFailure);
}
});
// From cache (sync)
conf.on("get", function (id, args, context) {
var promise;
if (waiting[id]) {
++waiting[id]; // Still waiting
return;
}
promise = promises[id];
var emit = function () { conf.emit("getasync", id, args, context); };
if (isPromise(promise)) {
if (typeof promise.done === "function") promise.done(emit);
else {
promise.then(function () { nextTick(emit); });
}
} else {
emit();
}
});
// On delete
conf.on("delete", function (id) {
delete promises[id];
if (waiting[id]) {
delete waiting[id];
return; // Not yet resolved
}
if (!hasOwnProperty.call(cache, id)) return;
var result = cache[id];
delete cache[id];
conf.emit("deleteasync", id, [result]);
});
// On clear
conf.on("clear", function () {
var oldCache = cache;
cache = create(null);
waiting = create(null);
promises = create(null);
conf.emit("clearasync", objectMap(oldCache, function (data) { return [data]; }));
});
};

View File

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

View File

@@ -0,0 +1,27 @@
'use strict';
var possibleNames = [
'BigInt64Array',
'BigUint64Array',
'Float32Array',
'Float64Array',
'Int16Array',
'Int32Array',
'Int8Array',
'Uint16Array',
'Uint32Array',
'Uint8Array',
'Uint8ClampedArray'
];
var g = typeof globalThis === 'undefined' ? global : globalThis;
module.exports = function availableTypedArrays() {
var out = [];
for (var i = 0; i < possibleNames.length; i++) {
if (typeof g[possibleNames[i]] === 'function') {
out[out.length] = possibleNames[i];
}
}
return out;
};

View File

@@ -0,0 +1,61 @@
var path = require('path');
var common = require('./common');
var _ls = require('./ls');
common.register('find', _find, {});
//@
//@ ### find(path [, path ...])
//@ ### find(path_array)
//@
//@ Examples:
//@
//@ ```javascript
//@ find('src', 'lib');
//@ find(['src', 'lib']); // same as above
//@ find('.').filter(function(file) { return file.match(/\.js$/); });
//@ ```
//@
//@ Returns array of all files (however deep) in the given paths.
//@
//@ The main difference from `ls('-R', path)` is that the resulting file names
//@ include the base directories (e.g., `lib/resources/file1` instead of just `file1`).
function _find(options, paths) {
if (!paths) {
common.error('no path specified');
} else if (typeof paths === 'string') {
paths = [].slice.call(arguments, 1);
}
var list = [];
function pushFile(file) {
if (process.platform === 'win32') {
file = file.replace(/\\/g, '/');
}
list.push(file);
}
// why not simply do `ls('-R', paths)`? because the output wouldn't give the base dirs
// to get the base dir in the output, we need instead `ls('-R', 'dir/*')` for every directory
paths.forEach(function (file) {
var stat;
try {
stat = common.statFollowLinks(file);
} catch (e) {
common.error('no such file or directory: ' + file);
}
pushFile(file);
if (stat.isDirectory()) {
_ls({ recursive: true, all: true }, file).forEach(function (subfile) {
pushFile(path.join(file, subfile));
});
}
});
return list;
}
module.exports = _find;

View File

@@ -0,0 +1,10 @@
'use strict';
var arrayMethodBoxesProperly = require('es-array-method-boxes-properly');
var implementation = require('./implementation');
module.exports = function getPolyfill() {
var method = Array.prototype.map;
return arrayMethodBoxesProperly(method) ? method : implementation;
};

View File

@@ -0,0 +1,8 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var $Math = GetIntrinsic('%Math%');
var $Number = GetIntrinsic('%Number%');
module.exports = $Number.MAX_SAFE_INTEGER || $Math.pow(2, 53) - 1;

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"J D E F A B CC"},B:{"1":"Y Z a b c d e i j k l m n o p q r s t u f H","2":"C K L G M N O","66":"P Q R S T U V W X"},C:{"2":"0 1 2 3 4 5 6 7 8 9 DC tB I v J D E F A B C K L G M N O w g x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB uB ZB vB aB bB cB dB eB fB gB hB iB jB kB h lB mB nB oB pB P Q R wB S T U V W X Y Z a b c d e i j k l m n o p q r s t u f H xB yB EC FC"},D:{"1":"Y Z a b c d e i j k l m n o p q r s t u f H xB yB GC","2":"0 1 2 3 4 5 6 7 8 9 I v J D E F A B C K L G M N O w g x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB uB ZB vB aB bB cB dB eB fB gB hB iB jB kB h lB mB nB oB","66":"pB P Q R S T U V W X"},E:{"2":"I v J D E F A B C K L G HC zB IC JC KC LC 0B qB rB 1B MC NC 2B 3B 4B 5B sB 6B 7B 8B 9B OC"},F:{"1":"nB oB pB P Q R wB S T U V W X Y Z a b c d e","2":"0 1 2 3 4 5 6 7 8 9 F B C G M N O w g x y z AB 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 aB bB cB PC QC RC SC qB AC TC rB","66":"dB eB fB gB hB iB jB kB h lB mB"},G:{"2":"E zB UC BC VC WC XC YC ZC aC bC cC dC eC fC gC hC iC jC kC lC mC nC 2B 3B 4B 5B sB 6B 7B 8B 9B"},H:{"2":"oC"},I:{"2":"tB I f pC qC rC sC BC tC uC"},J:{"2":"D A"},K:{"2":"A B C h qB AC rB"},L:{"2":"H"},M:{"2":"H"},N:{"2":"A B"},O:{"2":"vC"},P:{"2":"I g wC xC yC zC 0C 0B 1C 2C 3C 4C 5C sB 6C 7C 8C"},Q:{"2":"1B"},R:{"2":"9C"},S:{"2":"AD BD"}},B:7,C:"Web Serial API"};

View File

@@ -0,0 +1,9 @@
import { observeNotification } from '../Notification';
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
export function dematerialize() {
return operate(function (source, subscriber) {
source.subscribe(createOperatorSubscriber(subscriber, function (notification) { return observeNotification(notification, subscriber); }));
});
}
//# sourceMappingURL=dematerialize.js.map

View File

@@ -0,0 +1,47 @@
{
"name": "@octokit/endpoint",
"description": "Turns REST API endpoints into generic request options",
"version": "7.0.5",
"license": "MIT",
"files": [
"dist-*/",
"bin/"
],
"source": "dist-src/index.js",
"types": "dist-types/index.d.ts",
"main": "dist-node/index.js",
"module": "dist-web/index.js",
"pika": true,
"sideEffects": false,
"keywords": [
"octokit",
"github",
"api",
"rest"
],
"repository": "github:octokit/endpoint.js",
"dependencies": {
"@octokit/types": "^9.0.0",
"is-plain-object": "^5.0.0",
"universal-user-agent": "^6.0.0"
},
"devDependencies": {
"@pika/pack": "^0.3.7",
"@pika/plugin-build-node": "^0.9.0",
"@pika/plugin-build-web": "^0.9.0",
"@pika/plugin-ts-standard-pkg": "^0.9.0",
"@types/jest": "^29.0.0",
"jest": "^29.0.0",
"prettier": "2.8.3",
"semantic-release": "^20.0.0",
"semantic-release-plugin-update-version-in-files": "^1.0.0",
"ts-jest": "^29.0.0",
"typescript": "^4.0.2"
},
"engines": {
"node": ">= 14"
},
"publishConfig": {
"access": "public"
}
}

View File

@@ -0,0 +1,51 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var $TypeError = GetIntrinsic('%TypeError%');
var Call = require('./Call');
var CompletionRecord = require('./CompletionRecord');
var GetMethod = require('./GetMethod');
var IsCallable = require('./IsCallable');
var Type = require('./Type');
// https://262.ecma-international.org/6.0/#sec-iteratorclose
module.exports = function IteratorClose(iterator, completion) {
if (Type(iterator) !== 'Object') {
throw new $TypeError('Assertion failed: Type(iterator) is not Object');
}
if (!IsCallable(completion) && !(completion instanceof CompletionRecord)) {
throw new $TypeError('Assertion failed: completion is not a thunk representing a Completion Record, nor a Completion Record instance');
}
var completionThunk = completion instanceof CompletionRecord ? function () { return completion['?'](); } : completion;
var iteratorReturn = GetMethod(iterator, 'return');
if (typeof iteratorReturn === 'undefined') {
return completionThunk();
}
var completionRecord;
try {
var innerResult = Call(iteratorReturn, iterator, []);
} catch (e) {
// if we hit here, then "e" is the innerResult completion that needs re-throwing
// if the completion is of type "throw", this will throw.
completionThunk();
completionThunk = null; // ensure it's not called twice.
// if not, then return the innerResult completion
throw e;
}
completionRecord = completionThunk(); // if innerResult worked, then throw if the completion does
completionThunk = null; // ensure it's not called twice.
if (Type(innerResult) !== 'Object') {
throw new $TypeError('iterator .return must return an object');
}
return completionRecord;
};

View File

@@ -0,0 +1 @@
{"version":3,"file":"publishReplay.js","sourceRoot":"","sources":["../../../../src/internal/operators/publishReplay.ts"],"names":[],"mappings":";;;AACA,kDAAiD;AACjD,yCAAwC;AAExC,iDAAgD;AA8EhD,SAAgB,aAAa,CAC3B,UAAmB,EACnB,UAAmB,EACnB,mBAAgE,EAChE,iBAAqC;IAErC,IAAI,mBAAmB,IAAI,CAAC,uBAAU,CAAC,mBAAmB,CAAC,EAAE;QAC3D,iBAAiB,GAAG,mBAAmB,CAAC;KACzC;IACD,IAAM,QAAQ,GAAG,uBAAU,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,SAAS,CAAC;IAGnF,OAAO,UAAC,MAAqB,IAAK,OAAA,qBAAS,CAAC,IAAI,6BAAa,CAAI,UAAU,EAAE,UAAU,EAAE,iBAAiB,CAAC,EAAE,QAAS,CAAC,CAAC,MAAM,CAAC,EAA7F,CAA6F,CAAC;AAClI,CAAC;AAbD,sCAaC"}

View File

@@ -0,0 +1,5 @@
var convert = require('./convert'),
func = convert('castArray', require('../castArray'));
func.placeholder = require('./placeholder');
module.exports = func;

View File

@@ -0,0 +1,68 @@
import { operate } from '../util/lift';
import { createOperatorSubscriber } from './OperatorSubscriber';
import { identity } from '../util/identity';
import { timer } from '../observable/timer';
import { innerFrom } from '../observable/innerFrom';
export function retry(configOrCount = Infinity) {
let config;
if (configOrCount && typeof configOrCount === 'object') {
config = configOrCount;
}
else {
config = {
count: configOrCount,
};
}
const { count = Infinity, delay, resetOnSuccess: resetOnSuccess = false } = config;
return count <= 0
? identity
: operate((source, subscriber) => {
let soFar = 0;
let innerSub;
const subscribeForRetry = () => {
let syncUnsub = false;
innerSub = source.subscribe(createOperatorSubscriber(subscriber, (value) => {
if (resetOnSuccess) {
soFar = 0;
}
subscriber.next(value);
}, undefined, (err) => {
if (soFar++ < count) {
const resub = () => {
if (innerSub) {
innerSub.unsubscribe();
innerSub = null;
subscribeForRetry();
}
else {
syncUnsub = true;
}
};
if (delay != null) {
const notifier = typeof delay === 'number' ? timer(delay) : innerFrom(delay(err, soFar));
const notifierSubscriber = createOperatorSubscriber(subscriber, () => {
notifierSubscriber.unsubscribe();
resub();
}, () => {
subscriber.complete();
});
notifier.subscribe(notifierSubscriber);
}
else {
resub();
}
}
else {
subscriber.error(err);
}
}));
if (syncUnsub) {
innerSub.unsubscribe();
innerSub = null;
subscribeForRetry();
}
};
subscribeForRetry();
});
}
//# sourceMappingURL=retry.js.map