replace jest with ava

This commit is contained in:
Robert Brignull 2020-05-04 18:50:13 +01:00
parent 27cc8b23fe
commit 0347b72305
11775 changed files with 84546 additions and 1440575 deletions

11
node_modules/ava/cli.js generated vendored Executable file
View file

@ -0,0 +1,11 @@
#!/usr/bin/env node
'use strict';
const debug = require('debug')('ava');
const importLocal = require('import-local');
// Prefer the local installation of AVA
if (importLocal(__filename)) {
debug('Using local install of AVA');
} else {
require('./lib/cli').run();
}

96
node_modules/ava/eslint-plugin-helper.js generated vendored Normal file
View file

@ -0,0 +1,96 @@
'use strict';
const normalizeExtensions = require('./lib/extensions');
const {classify, hasExtension, isHelperish, matches, normalizeFileForMatching, normalizeGlobs, normalizePatterns} = require('./lib/globs');
const loadConfig = require('./lib/load-config');
const providerManager = require('./lib/provider-manager');
const configCache = new Map();
const helperCache = new Map();
function load(projectDir, overrides) {
const cacheKey = `${JSON.stringify(overrides)}\n${projectDir}`;
if (helperCache.has(cacheKey)) {
return helperCache.get(cacheKey);
}
let conf;
let providers;
if (configCache.has(projectDir)) {
({conf, providers} = configCache.get(projectDir));
} else {
conf = loadConfig({resolveFrom: projectDir});
providers = [];
if (Reflect.has(conf, 'babel')) {
const {level, main} = providerManager.babel(projectDir);
providers.push({
level,
main: main({config: conf.babel}),
type: 'babel'
});
}
if (Reflect.has(conf, 'typescript')) {
const {level, main} = providerManager.typescript(projectDir);
providers.push({
level,
main: main({config: conf.typescript}),
type: 'typescript'
});
}
configCache.set(projectDir, {conf, providers});
}
const extensions = overrides && overrides.extensions ?
normalizeExtensions(overrides.extensions) :
normalizeExtensions(conf.extensions, providers);
let helperPatterns = [];
if (overrides && overrides.helpers !== undefined) {
if (!Array.isArray(overrides.helpers) || overrides.helpers.length === 0) {
throw new Error('The helpers override must be an array containing glob patterns.');
}
helperPatterns = normalizePatterns(overrides.helpers);
}
const globs = {
cwd: projectDir,
...normalizeGlobs({
extensions,
files: overrides && overrides.files ? overrides.files : conf.files,
providers
})
};
const classifyForESLint = file => {
const {isTest} = classify(file, globs);
let isHelper = false;
if (!isTest && hasExtension(globs.extensions, file)) {
file = normalizeFileForMatching(projectDir, file);
isHelper = isHelperish(file) || (helperPatterns.length > 0 && matches(file, helperPatterns));
}
return {isHelper, isTest};
};
const helper = Object.freeze({
classifyFile: classifyForESLint,
classifyImport: importPath => {
if (hasExtension(globs.extensions, importPath)) {
// The importPath has one of the test file extensions: we can classify
// it directly.
return classifyForESLint(importPath);
}
// Add the first extension. If multiple extensions are available, assume
// patterns are not biased to any particular extension.
return classifyForESLint(`${importPath}.${globs.extensions[0]}`);
}
});
helperCache.set(cacheKey, helper);
return helper;
}
exports.load = load;

811
node_modules/ava/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,811 @@
export interface Subscribable {
subscribe(observer: {
error(err: any): void;
complete(): void;
}): void;
}
export type Constructor = (new (...args: any[]) => any);
/** Specify one or more expectations the thrown error must satisfy. */
export type ThrowsExpectation = {
/** The thrown error must have a code that equals the given string or number. */
code?: string | number;
/** The thrown error must be an instance of this constructor. */
instanceOf?: Constructor;
/** The thrown error must be strictly equal to this value. */
is?: Error;
/** The thrown error must have a message that equals the given string, or matches the regular expression. */
message?: string | RegExp;
/** The thrown error must have a name that equals the given string. */
name?: string;
};
export type CommitDiscardOptions = {
/**
* Whether the logs should be included in those of the parent test.
*/
retainLogs?: boolean;
};
/** Options that can be passed to the `t.snapshot()` assertion. */
export type SnapshotOptions = {
/** If provided and not an empty string, used to select the snapshot to compare the `expected` value against. */
id?: string;
};
export interface Assertions {
/** Assert that `actual` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). Comes with power-assert. */
assert: AssertAssertion;
/** Assert that `actual` is [deeply equal](https://github.com/concordancejs/concordance#comparison-details) to `expected`. */
deepEqual: DeepEqualAssertion;
/** Fail the test. */
fail: FailAssertion;
/** Assert that `actual` is strictly false. */
false: FalseAssertion;
/** Assert that `actual` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). */
falsy: FalsyAssertion;
/**
* Assert that `actual` is [the same
* value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) as `expected`.
*/
is: IsAssertion;
/**
* Assert that `actual` is not [the same
* value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) as `expected`.
*/
not: NotAssertion;
/** Assert that `actual` is not [deeply equal](https://github.com/concordancejs/concordance#comparison-details) to `expected`. */
notDeepEqual: NotDeepEqualAssertion;
/** Assert that `string` does not match the regular expression. */
notRegex: NotRegexAssertion;
/** Assert that the function does not throw. */
notThrows: NotThrowsAssertion;
/** Assert that the async function does not throw, or that the promise does not reject. Must be awaited. */
notThrowsAsync: NotThrowsAsyncAssertion;
/** Count a passing assertion. */
pass: PassAssertion;
/** Assert that `string` matches the regular expression. */
regex: RegexAssertion;
/**
* Assert that `expected` is [deeply equal](https://github.com/concordancejs/concordance#comparison-details) to a
* previously recorded [snapshot](https://github.com/concordancejs/concordance#serialization-details), or if
* necessary record a new snapshot.
*/
snapshot: SnapshotAssertion;
/**
* Assert that the function throws [an error](https://www.npmjs.com/package/is-error). If so, returns the error value.
*/
throws: ThrowsAssertion;
/**
* Assert that the async function throws [an error](https://www.npmjs.com/package/is-error), or the promise rejects
* with one. If so, returns a promise for the error value, which must be awaited.
*/
throwsAsync: ThrowsAsyncAssertion;
/** Assert that `actual` is strictly true. */
true: TrueAssertion;
/** Assert that `actual` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). */
truthy: TruthyAssertion;
}
export interface AssertAssertion {
/** Assert that `actual` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). Comes with power-assert. */
(actual: any, message?: string): void;
/** Skip this assertion. */
skip(actual: any, message?: string): void;
}
export interface DeepEqualAssertion {
/** Assert that `actual` is [deeply equal](https://github.com/concordancejs/concordance#comparison-details) to `expected`. */
<ValueType = any>(actual: ValueType, expected: ValueType, message?: string): void;
/** Skip this assertion. */
skip(actual: any, expected: any, message?: string): void;
}
export interface FailAssertion {
/** Fail the test. */
(message?: string): void;
/** Skip this assertion. */
skip(message?: string): void;
}
export interface FalseAssertion {
/** Assert that `actual` is strictly false. */
(actual: any, message?: string): void;
/** Skip this assertion. */
skip(actual: any, message?: string): void;
}
export interface FalsyAssertion {
/** Assert that `actual` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). */
(actual: any, message?: string): void;
/** Skip this assertion. */
skip(actual: any, message?: string): void;
}
export interface IsAssertion {
/**
* Assert that `actual` is [the same
* value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) as `expected`.
*/
<ValueType = any>(actual: ValueType, expected: ValueType, message?: string): void;
/** Skip this assertion. */
skip(actual: any, expected: any, message?: string): void;
}
export interface NotAssertion {
/**
* Assert that `actual` is not [the same
* value](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) as `expected`.
*/
<ValueType = any>(actual: ValueType, expected: ValueType, message?: string): void;
/** Skip this assertion. */
skip(actual: any, expected: any, message?: string): void;
}
export interface NotDeepEqualAssertion {
/** Assert that `actual` is not [deeply equal](https://github.com/concordancejs/concordance#comparison-details) to `expected`. */
<ValueType = any>(actual: ValueType, expected: ValueType, message?: string): void;
/** Skip this assertion. */
skip(actual: any, expected: any, message?: string): void;
}
export interface NotRegexAssertion {
/** Assert that `string` does not match the regular expression. */
(string: string, regex: RegExp, message?: string): void;
/** Skip this assertion. */
skip(string: string, regex: RegExp, message?: string): void;
}
export interface NotThrowsAssertion {
/** Assert that the function does not throw. */
(fn: () => any, message?: string): void;
/** Skip this assertion. */
skip(fn: () => any, message?: string): void;
}
export interface NotThrowsAsyncAssertion {
/** Assert that the async function does not throw. You must await the result. */
(fn: () => PromiseLike<any>, message?: string): Promise<void>;
/** Assert that the promise does not reject. You must await the result. */
(promise: PromiseLike<any>, message?: string): Promise<void>;
/** Skip this assertion. */
skip(nonThrower: any, message?: string): void;
}
export interface PassAssertion {
/** Count a passing assertion. */
(message?: string): void;
/** Skip this assertion. */
skip(message?: string): void;
}
export interface RegexAssertion {
/** Assert that `string` matches the regular expression. */
(string: string, regex: RegExp, message?: string): void;
/** Skip this assertion. */
skip(string: string, regex: RegExp, message?: string): void;
}
export interface SnapshotAssertion {
/**
* Assert that `expected` is [deeply equal](https://github.com/concordancejs/concordance#comparison-details) to a
* previously recorded [snapshot](https://github.com/concordancejs/concordance#serialization-details), or if
* necessary record a new snapshot.
*/
(expected: any, message?: string): void;
/**
* Assert that `expected` is [deeply equal](https://github.com/concordancejs/concordance#comparison-details) to a
* previously recorded [snapshot](https://github.com/concordancejs/concordance#serialization-details) (selected
* through `options.id` if provided), or if necessary record a new snapshot.
*/
(expected: any, options: SnapshotOptions, message?: string): void;
/** Skip this assertion. */
skip(expected: any, message?: string): void;
/** Skip this assertion. */
skip(expected: any, options: SnapshotOptions, message?: string): void;
}
export interface ThrowsAssertion {
/**
* Assert that the function throws [an error](https://www.npmjs.com/package/is-error). If so, returns the error value.
* The error must satisfy all expectations.
*/
<ThrownError extends Error>(fn: () => any, expectations?: ThrowsExpectation | null, message?: string): ThrownError;
/** Skip this assertion. */
skip(fn: () => any, expectations?: any, message?: string): void;
}
export interface ThrowsAsyncAssertion {
/**
* Assert that the async function throws [an error](https://www.npmjs.com/package/is-error). If so, returns the error
* value. You must await the result.
*/
<ThrownError extends Error>(fn: () => PromiseLike<any>, expectations?: null, message?: string): Promise<ThrownError>;
/**
* Assert that the async function throws [an error](https://www.npmjs.com/package/is-error). If so, returns the error
* value. You must await the result. The error must satisfy all expectations.
*/
<ThrownError extends Error>(fn: () => PromiseLike<any>, expectations: ThrowsExpectation, message?: string): Promise<ThrownError>;
/**
* Assert that the promise rejects with [an error](https://www.npmjs.com/package/is-error). If so, returns the
* rejection reason. You must await the result.
*/
<ThrownError extends Error>(promise: PromiseLike<any>, expectations?: null, message?: string): Promise<ThrownError>;
/**
* Assert that the promise rejects with [an error](https://www.npmjs.com/package/is-error). If so, returns the
* rejection reason. You must await the result. The error must satisfy all expectations.
*/
<ThrownError extends Error>(promise: PromiseLike<any>, expectations: ThrowsExpectation, message?: string): Promise<ThrownError>;
/** Skip this assertion. */
skip(thrower: any, expectations?: any, message?: string): void;
}
export interface TrueAssertion {
/** Assert that `actual` is strictly true. */
(actual: any, message?: string): void;
/** Skip this assertion. */
skip(actual: any, message?: string): void;
}
export interface TruthyAssertion {
/** Assert that `actual` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). */
(actual: any, message?: string): void;
/** Skip this assertion. */
skip(actual: any, message?: string): void;
}
/** The `t` value passed to test & hook implementations. */
export interface ExecutionContext<Context = unknown> extends Assertions {
/** Test context, shared with hooks. */
context: Context;
/** Title of the test or hook. */
readonly title: string;
/** Whether the test has passed. Only accurate in afterEach hooks. */
readonly passed: boolean;
log: LogFn;
plan: PlanFn;
teardown: TeardownFn;
timeout: TimeoutFn;
try: TryFn<Context>;
}
export interface LogFn {
/** Log one or more values. */
(...values: any[]): void;
/** Skip logging. */
skip(...values: any[]): void;
}
export interface PlanFn {
/**
* Plan how many assertion there are in the test. The test will fail if the actual assertion count doesn't match the
* number of planned assertions. See [assertion planning](https://github.com/avajs/ava#assertion-planning).
*/
(count: number): void;
/** Don't plan assertions. */
skip(count: number): void;
}
export interface TimeoutFn {
/**
* Set a timeout for the test, in milliseconds. The test will fail if the timeout is exceeded.
* The timeout is reset each time an assertion is made.
*/
(ms: number): void;
}
export interface TeardownFn {
/** Declare a function to be run after the test has ended. */
(fn: () => void): void;
}
export interface TryFn<Context = unknown> {
/**
* Attempt to run some assertions. The result must be explicitly committed or discarded or else
* the test will fail. A macro may be provided. The title may help distinguish attempts from
* one another.
*/
<Args extends any[]>(title: string, fn: EitherMacro<Args, Context>, ...args: Args): Promise<TryResult>;
/**
* Attempt to run some assertions. The result must be explicitly committed or discarded or else
* the test will fail. A macro may be provided. The title may help distinguish attempts from
* one another.
*/
<Args extends any[]>(title: string, fn: [EitherMacro<Args, Context>, ...Array<EitherMacro<Args, Context>>], ...args: Args): Promise<TryResult[]>;
/**
* Attempt to run some assertions. The result must be explicitly committed or discarded or else
* the test will fail. A macro may be provided.
*/
<Args extends any[]>(fn: EitherMacro<Args, Context>, ...args: Args): Promise<TryResult>;
/**
* Attempt to run some assertions. The result must be explicitly committed or discarded or else
* the test will fail. A macro may be provided.
*/
<Args extends any[]>(fn: [EitherMacro<Args, Context>, ...Array<EitherMacro<Args, Context>>], ...args: Args): Promise<TryResult[]>;
}
export interface AssertionError extends Error {}
export interface TryResult {
/**
* Title of the attempt, helping you tell attempts aparts.
*/
title: string;
/**
* Indicates whether all assertions passed, or at least one failed.
*/
passed: boolean;
/**
* Errors raised for each failed assertion.
*/
errors: AssertionError[];
/**
* Logs created during the attempt using `t.log()`. Contains formatted values.
*/
logs: string[];
/**
* Commit the attempt. Counts as one assertion for the plan count. If the
* attempt failed, calling this will also cause your test to fail.
*/
commit(options?: CommitDiscardOptions): void;
/**
* Discard the attempt.
*/
discard(options?: CommitDiscardOptions): void;
}
/** The `t` value passed to implementations for tests & hooks declared with the `.cb` modifier. */
export interface CbExecutionContext<Context = unknown> extends ExecutionContext<Context> {
/**
* End the test. If `error` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) the test or hook
* will fail.
*/
end(error?: any): void;
}
export type ImplementationResult = PromiseLike<void> | Subscribable | void;
export type Implementation<Context = unknown> = (t: ExecutionContext<Context>) => ImplementationResult;
export type CbImplementation<Context = unknown> = (t: CbExecutionContext<Context>) => ImplementationResult;
/** A reusable test or hook implementation. */
export type UntitledMacro<Args extends any[], Context = unknown> = (t: ExecutionContext<Context>, ...args: Args) => ImplementationResult;
/** A reusable test or hook implementation. */
export type Macro<Args extends any[], Context = unknown> = UntitledMacro<Args, Context> & {
/**
* Implement this function to generate a test (or hook) title whenever this macro is used. `providedTitle` contains
* the title provided when the test or hook was declared. Also receives the remaining test arguments.
*/
title?: (providedTitle: string | undefined, ...args: Args) => string;
};
export type EitherMacro<Args extends any[], Context> = Macro<Args, Context> | UntitledMacro<Args, Context>;
/** Alias for a single macro, or an array of macros. */
export type OneOrMoreMacros<Args extends any[], Context> = EitherMacro<Args, Context> | [EitherMacro<Args, Context>, ...Array<EitherMacro<Args, Context>>];
/** A reusable test or hook implementation, for tests & hooks declared with the `.cb` modifier. */
export type UntitledCbMacro<Args extends any[], Context = unknown> = (t: CbExecutionContext<Context>, ...args: Args) => ImplementationResult;
/** A reusable test or hook implementation, for tests & hooks declared with the `.cb` modifier. */
export type CbMacro<Args extends any[], Context = unknown> = UntitledCbMacro<Args, Context> & {
title?: (providedTitle: string | undefined, ...args: Args) => string;
};
export type EitherCbMacro<Args extends any[], Context> = CbMacro<Args, Context> | UntitledCbMacro<Args, Context>;
/** Alias for a single macro, or an array of macros, used for tests & hooks declared with the `.cb` modifier. */
export type OneOrMoreCbMacros<Args extends any[], Context> = EitherCbMacro<Args, Context> | [EitherCbMacro<Args, Context>, ...Array<EitherCbMacro<Args, Context>>];
export interface TestInterface<Context = unknown> {
/** Declare a concurrent test. */
(title: string, implementation: Implementation<Context>): void;
/** Declare a concurrent test that uses one or more macros. Additional arguments are passed to the macro. */
<T extends any[]>(title: string, macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Declare a concurrent test that uses one or more macros. The macro is responsible for generating a unique test title. */
<T extends any[]>(macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Declare a hook that is run once, after all tests have passed. */
after: AfterInterface<Context>;
/** Declare a hook that is run after each passing test. */
afterEach: AfterInterface<Context>;
/** Declare a hook that is run once, before all tests. */
before: BeforeInterface<Context>;
/** Declare a hook that is run before each test. */
beforeEach: BeforeInterface<Context>;
/** Declare a test that must call `t.end()` when it's done. */
cb: CbInterface<Context>;
/** Declare a test that is expected to fail. */
failing: FailingInterface<Context>;
/** Declare tests and hooks that are run serially. */
serial: SerialInterface<Context>;
only: OnlyInterface<Context>;
skip: SkipInterface<Context>;
todo: TodoDeclaration;
meta: MetaInterface;
}
export interface AfterInterface<Context = unknown> {
/** Declare a hook that is run once, after all tests have passed. */
(implementation: Implementation<Context>): void;
/** Declare a hook that is run once, after all tests have passed. */
(title: string, implementation: Implementation<Context>): void;
/** Declare a hook that is run once, after all tests have passed. Additional arguments are passed to the macro. */
<T extends any[]>(title: string, macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Declare a hook that is run once, after all tests have passed. */
<T extends any[]>(macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Declare a hook that is run once, after all tests are done. */
always: AlwaysInterface<Context>;
/** Declare a hook that must call `t.end()` when it's done. */
cb: HookCbInterface<Context>;
skip: HookSkipInterface<Context>;
}
export interface AlwaysInterface<Context = unknown> {
/** Declare a hook that is run once, after all tests are done. */
(implementation: Implementation<Context>): void;
/** Declare a hook that is run once, after all tests are done. */
(title: string, implementation: Implementation<Context>): void;
/** Declare a hook that is run once, after all tests are done. Additional arguments are passed to the macro. */
<T extends any[]>(title: string, macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Declare a hook that is run once, after all tests are done. */
<T extends any[]>(macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Declare a hook that must call `t.end()` when it's done. */
cb: HookCbInterface<Context>;
skip: HookSkipInterface<Context>;
}
export interface BeforeInterface<Context = unknown> {
/** Declare a hook that is run once, before all tests. */
(implementation: Implementation<Context>): void;
/** Declare a hook that is run once, before all tests. */
(title: string, implementation: Implementation<Context>): void;
/** Declare a hook that is run once, before all tests. Additional arguments are passed to the macro. */
<T extends any[]>(title: string, macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Declare a hook that is run once, before all tests. */
<T extends any[]>(macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Declare a hook that must call `t.end()` when it's done. */
cb: HookCbInterface<Context>;
skip: HookSkipInterface<Context>;
}
export interface CbInterface<Context = unknown> {
/** Declare a test that must call `t.end()` when it's done. */
(title: string, implementation: CbImplementation<Context>): void;
/**
* Declare a concurrent test that uses one or more macros. The macros must call `t.end()` when they're done.
* Additional arguments are passed to the macro.
*/
<T extends any[]>(title: string, macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
/**
* Declare a concurrent test that uses one or more macros. The macros must call `t.end()` when they're done.
* The macro is responsible for generating a unique test title.
*/
<T extends any[]>(macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
/** Declare a test that is expected to fail. */
failing: CbFailingInterface<Context>;
only: CbOnlyInterface<Context>;
skip: CbSkipInterface<Context>;
}
export interface CbFailingInterface<Context = unknown> {
/** Declare a test that must call `t.end()` when it's done. The test is expected to fail. */
(title: string, implementation: CbImplementation<Context>): void;
/**
* Declare a test that uses one or more macros. The macros must call `t.end()` when they're done.
* Additional arguments are passed to the macro. The test is expected to fail.
*/
<T extends any[]>(title: string, macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
/**
* Declare a test that uses one or more macros. The macros must call `t.end()` when they're done.
* The test is expected to fail.
*/
<T extends any[]>(macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
only: CbOnlyInterface<Context>;
skip: CbSkipInterface<Context>;
}
export interface CbOnlyInterface<Context = unknown> {
/**
* Declare a test that must call `t.end()` when it's done. Only this test and others declared with `.only()` are run.
*/
(title: string, implementation: CbImplementation<Context>): void;
/**
* Declare a test that uses one or more macros. The macros must call `t.end()` when they're done.
* Additional arguments are passed to the macro. Only this test and others declared with `.only()` are run.
*/
<T extends any[]>(title: string, macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
/**
* Declare a test that uses one or more macros. The macros must call `t.end()` when they're done.
* Additional arguments are passed to the macro. Only this test and others declared with `.only()` are run.
*/
<T extends any[]>(macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
}
export interface CbSkipInterface<Context = unknown> {
/** Skip this test. */
(title: string, implementation: CbImplementation<Context>): void;
/** Skip this test. */
<T extends any[]>(title: string, macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
/** Skip this test. */
<T extends any[]>(macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
}
export interface FailingInterface<Context = unknown> {
/** Declare a concurrent test. The test is expected to fail. */
(title: string, implementation: Implementation<Context>): void;
/**
* Declare a concurrent test that uses one or more macros. Additional arguments are passed to the macro.
* The test is expected to fail.
*/
<T extends any[]>(title: string, macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/**
* Declare a concurrent test that uses one or more macros. The macro is responsible for generating a unique test title.
* The test is expected to fail.
*/
<T extends any[]>(macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
only: OnlyInterface<Context>;
skip: SkipInterface<Context>;
}
export interface HookCbInterface<Context = unknown> {
/** Declare a hook that must call `t.end()` when it's done. */
(implementation: CbImplementation<Context>): void;
/** Declare a hook that must call `t.end()` when it's done. */
(title: string, implementation: CbImplementation<Context>): void;
/**
* Declare a hook that uses one or more macros. The macros must call `t.end()` when they're done.
* Additional arguments are passed to the macro.
*/
<T extends any[]>(title: string, macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
/**
* Declare a hook that uses one or more macros. The macros must call `t.end()` when they're done.
*/
<T extends any[]>(macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
skip: HookCbSkipInterface<Context>;
}
export interface HookCbSkipInterface<Context = unknown> {
/** Skip this hook. */
(implementation: CbImplementation<Context>): void;
/** Skip this hook. */
(title: string, implementation: CbImplementation<Context>): void;
/** Skip this hook. */
<T extends any[]>(title: string, macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
/** Skip this hook. */
<T extends any[]>(macros: OneOrMoreCbMacros<T, Context>, ...rest: T): void;
}
export interface HookSkipInterface<Context = unknown> {
/** Skip this hook. */
(implementation: Implementation<Context>): void;
/** Skip this hook. */
(title: string, implementation: Implementation<Context>): void;
/** Skip this hook. */
<T extends any[]>(title: string, macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Skip this hook. */
<T extends any[]>(macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
}
export interface OnlyInterface<Context = unknown> {
/** Declare a test. Only this test and others declared with `.only()` are run. */
(title: string, implementation: Implementation<Context>): void;
/**
* Declare a test that uses one or more macros. Additional arguments are passed to the macro.
* Only this test and others declared with `.only()` are run.
*/
<T extends any[]>(title: string, macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/**
* Declare a test that uses one or more macros. The macro is responsible for generating a unique test title.
* Only this test and others declared with `.only()` are run.
*/
<T extends any[]>(macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
}
export interface SerialInterface<Context = unknown> {
/** Declare a serial test. */
(title: string, implementation: Implementation<Context>): void;
/** Declare a serial test that uses one or more macros. Additional arguments are passed to the macro. */
<T extends any[]>(title: string, macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/**
* Declare a serial test that uses one or more macros. The macro is responsible for generating a unique test title.
*/
<T extends any[]>(macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Declare a serial hook that is run once, after all tests have passed. */
after: AfterInterface<Context>;
/** Declare a serial hook that is run after each passing test. */
afterEach: AfterInterface<Context>;
/** Declare a serial hook that is run once, before all tests. */
before: BeforeInterface<Context>;
/** Declare a serial hook that is run before each test. */
beforeEach: BeforeInterface<Context>;
/** Declare a serial test that must call `t.end()` when it's done. */
cb: CbInterface<Context>;
/** Declare a serial test that is expected to fail. */
failing: FailingInterface<Context>;
only: OnlyInterface<Context>;
skip: SkipInterface<Context>;
todo: TodoDeclaration;
}
export interface SkipInterface<Context = unknown> {
/** Skip this test. */
(title: string, implementation: Implementation<Context>): void;
/** Skip this test. */
<T extends any[]>(title: string, macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
/** Skip this test. */
<T extends any[]>(macros: OneOrMoreMacros<T, Context>, ...rest: T): void;
}
export interface TodoDeclaration {
/** Declare a test that should be implemented later. */
(title: string): void;
}
export interface MetaInterface {
/** Path to the test file being executed. */
file: string;
/** Directory where snapshots are stored. */
snapshotDirectory: string;
}
/** Call to declare a test, or chain to declare hooks or test modifiers */
declare const test: TestInterface;
/** Call to declare a test, or chain to declare hooks or test modifiers */
export default test;
/** Call to declare a hook that is run once, after all tests have passed, or chain to declare modifiers. */
export const after: AfterInterface;
/** Call to declare a hook that is run after each passing test, or chain to declare modifiers. */
export const afterEach: AfterInterface;
/** Call to declare a hook that is run once, before all tests, or chain to declare modifiers. */
export const before: BeforeInterface;
/** Call to declare a hook that is run before each test, or chain to declare modifiers. */
export const beforeEach: BeforeInterface;
/** Call to declare a test that must invoke `t.end()` when it's done, or chain to declare modifiers. */
export const cb: CbInterface;
/** Call to declare a test that is expected to fail, or chain to declare modifiers. */
export const failing: FailingInterface;
/** Call to declare a test that is run exclusively, along with other tests declared with `.only()`. */
export const only: OnlyInterface;
/** Call to declare a serial test, or chain to declare serial hooks or test modifiers. */
export const serial: SerialInterface;
/** Skip this test. */
export const skip: SkipInterface;
/** Declare a test that should be implemented later. */
export const todo: TodoDeclaration;
/** Meta data associated with the current process. */
export const meta: MetaInterface;

8
node_modules/ava/index.js generated vendored Normal file
View file

@ -0,0 +1,8 @@
'use strict';
// Ensure the same AVA install is loaded by the test file as by the test worker
if (process.env.AVA_PATH && process.env.AVA_PATH !== __dirname) {
module.exports = require(process.env.AVA_PATH);
} else {
module.exports = require('./lib/worker/main');
}

275
node_modules/ava/lib/api.js generated vendored Normal file
View file

@ -0,0 +1,275 @@
'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const commonPathPrefix = require('common-path-prefix');
const resolveCwd = require('resolve-cwd');
const debounce = require('lodash/debounce');
const arrify = require('arrify');
const ms = require('ms');
const chunkd = require('chunkd');
const Emittery = require('emittery');
const pMap = require('p-map');
const tempDir = require('temp-dir');
const globs = require('./globs');
const isCi = require('./is-ci');
const RunStatus = require('./run-status');
const fork = require('./fork');
const serializeError = require('./serialize-error');
const {getApplicableLineNumbers} = require('./line-numbers');
function resolveModules(modules) {
return arrify(modules).map(name => {
const modulePath = resolveCwd.silent(name);
if (modulePath === undefined) {
throw new Error(`Could not resolve required module ${name}`);
}
return modulePath;
});
}
function getFilePathPrefix(files) {
if (files.length === 1) {
// Get the correct prefix up to the basename.
return commonPathPrefix([files[0], path.dirname(files[0])]);
}
return commonPathPrefix(files);
}
class Api extends Emittery {
constructor(options) {
super();
this.options = {match: [], moduleTypes: {}, ...options};
this.options.require = resolveModules(this.options.require);
this._cacheDir = null;
this._interruptHandler = () => {};
if (options.ranFromCli) {
process.on('SIGINT', () => this._interruptHandler());
}
}
async run({files: selectedFiles = [], filter = [], runtimeOptions = {}} = {}) {
let setupOrGlobError;
const apiOptions = this.options;
// Each run will have its own status. It can only be created when test files
// have been found.
let runStatus;
// Irrespectively, perform some setup now, before finding test files.
// Track active forks and manage timeouts.
const failFast = apiOptions.failFast === true;
let bailed = false;
const pendingWorkers = new Set();
const timedOutWorkerFiles = new Set();
let restartTimer;
if (apiOptions.timeout && !apiOptions.debug) {
const timeout = ms(apiOptions.timeout);
restartTimer = debounce(() => {
// If failFast is active, prevent new test files from running after
// the current ones are exited.
if (failFast) {
bailed = true;
}
runStatus.emitStateChange({type: 'timeout', period: timeout});
for (const worker of pendingWorkers) {
timedOutWorkerFiles.add(worker.file);
worker.exit();
}
}, timeout);
} else {
restartTimer = Object.assign(() => {}, {cancel() {}});
}
this._interruptHandler = () => {
if (bailed) {
// Exiting already
return;
}
// Prevent new test files from running
bailed = true;
// Make sure we don't run the timeout handler
restartTimer.cancel();
runStatus.emitStateChange({type: 'interrupt'});
for (const worker of pendingWorkers) {
worker.exit();
}
};
let cacheDir;
let testFiles;
try {
cacheDir = this._createCacheDir();
testFiles = await globs.findTests({cwd: this.options.projectDir, ...apiOptions.globs});
if (selectedFiles.length === 0) {
if (filter.length === 0) {
selectedFiles = testFiles;
} else {
selectedFiles = globs.applyTestFileFilter({
cwd: this.options.projectDir,
filter: filter.map(({pattern}) => pattern),
testFiles
});
}
}
} catch (error) {
selectedFiles = [];
setupOrGlobError = error;
}
try {
if (this.options.parallelRuns) {
const {currentIndex, totalRuns} = this.options.parallelRuns;
const fileCount = selectedFiles.length;
// The files must be in the same order across all runs, so sort them.
selectedFiles = selectedFiles.sort((a, b) => a.localeCompare(b, [], {numeric: true}));
selectedFiles = chunkd(selectedFiles, currentIndex, totalRuns);
const currentFileCount = selectedFiles.length;
runStatus = new RunStatus(fileCount, {currentFileCount, currentIndex, totalRuns});
} else {
runStatus = new RunStatus(selectedFiles.length, null);
}
const debugWithoutSpecificFile = Boolean(this.options.debug) && selectedFiles.length !== 1;
await this.emit('run', {
bailWithoutReporting: debugWithoutSpecificFile,
clearLogOnNextRun: runtimeOptions.clearLogOnNextRun === true,
debug: Boolean(this.options.debug),
failFastEnabled: failFast,
filePathPrefix: getFilePathPrefix(selectedFiles),
files: selectedFiles,
matching: apiOptions.match.length > 0,
previousFailures: runtimeOptions.previousFailures || 0,
runOnlyExclusive: runtimeOptions.runOnlyExclusive === true,
runVector: runtimeOptions.runVector || 0,
status: runStatus
});
if (setupOrGlobError) {
throw setupOrGlobError;
}
// Bail out early if no files were found, or when debugging and there is not a single specific test file to debug.
if (selectedFiles.length === 0 || debugWithoutSpecificFile) {
return runStatus;
}
runStatus.on('stateChange', record => {
if (record.testFile && !timedOutWorkerFiles.has(record.testFile)) {
// Restart the timer whenever there is activity from workers that
// haven't already timed out.
restartTimer();
}
if (failFast && (record.type === 'hook-failed' || record.type === 'test-failed' || record.type === 'worker-failed')) {
// Prevent new test files from running once a test has failed.
bailed = true;
// Try to stop currently scheduled tests.
for (const worker of pendingWorkers) {
worker.notifyOfPeerFailure();
}
}
});
const {providers = []} = this.options;
const providerStates = (await Promise.all(providers.map(async ({type, main}) => {
const state = await main.compile({cacheDir, files: testFiles});
return state === null ? null : {type, state};
}))).filter(state => state !== null);
// Resolve the correct concurrency value.
let concurrency = Math.min(os.cpus().length, isCi ? 2 : Infinity);
if (apiOptions.concurrency > 0) {
concurrency = apiOptions.concurrency;
}
if (apiOptions.serial) {
concurrency = 1;
}
// Try and run each file, limited by `concurrency`.
await pMap(selectedFiles, async file => {
// No new files should be run once a test has timed out or failed,
// and failFast is enabled.
if (bailed) {
return;
}
const lineNumbers = getApplicableLineNumbers(globs.normalizeFileForMatching(apiOptions.projectDir, file), filter);
const options = {
...apiOptions,
providerStates,
lineNumbers,
recordNewSnapshots: !isCi,
// If we're looking for matches, run every single test process in exclusive-only mode
runOnlyExclusive: apiOptions.match.length > 0 || runtimeOptions.runOnlyExclusive === true
};
if (runtimeOptions.updateSnapshots) {
// Don't use in Object.assign() since it'll override options.updateSnapshots even when false.
options.updateSnapshots = true;
}
const worker = fork(file, options, apiOptions.nodeArguments);
runStatus.observeWorker(worker, file, {selectingLines: lineNumbers.length > 0});
pendingWorkers.add(worker);
worker.promise.then(() => {
pendingWorkers.delete(worker);
});
restartTimer();
return worker.promise;
}, {concurrency, stopOnError: false});
} catch (error) {
if (error && error.name === 'AggregateError') {
for (const err of error) {
runStatus.emitStateChange({type: 'internal-error', err: serializeError('Internal error', false, err)});
}
} else {
runStatus.emitStateChange({type: 'internal-error', err: serializeError('Internal error', false, error)});
}
}
restartTimer.cancel();
return runStatus;
}
_createCacheDir() {
if (this._cacheDir) {
return this._cacheDir;
}
const cacheDir = this.options.cacheEnabled === false ?
fs.mkdtempSync(`${tempDir}${path.sep}`) :
path.join(this.options.projectDir, 'node_modules', '.cache', 'ava');
// Ensure cacheDir exists
fs.mkdirSync(cacheDir, {recursive: true});
this._cacheDir = cacheDir;
return cacheDir;
}
}
module.exports = Api;

880
node_modules/ava/lib/assert.js generated vendored Normal file
View file

@ -0,0 +1,880 @@
'use strict';
const concordance = require('concordance');
const isError = require('is-error');
const isPromise = require('is-promise');
const concordanceOptions = require('./concordance-options').default;
const concordanceDiffOptions = require('./concordance-options').diff;
const snapshotManager = require('./snapshot-manager');
function formatDescriptorDiff(actualDescriptor, expectedDescriptor, options) {
options = {...options, ...concordanceDiffOptions};
return {
label: 'Difference:',
formatted: concordance.diffDescriptors(actualDescriptor, expectedDescriptor, options)
};
}
function formatDescriptorWithLabel(label, descriptor) {
return {
label,
formatted: concordance.formatDescriptor(descriptor, concordanceOptions)
};
}
function formatWithLabel(label, value) {
return formatDescriptorWithLabel(label, concordance.describe(value, concordanceOptions));
}
function formatPowerAssertValue(value) {
return concordance.format(value, concordanceOptions);
}
const hasOwnProperty = (object, prop) => Object.prototype.hasOwnProperty.call(object, prop);
const noop = () => {};
const notImplemented = () => {
throw new Error('not implemented');
};
class AssertionError extends Error {
constructor(options) {
super(options.message || '');
this.name = 'AssertionError';
this.assertion = options.assertion;
this.fixedSource = options.fixedSource;
this.improperUsage = options.improperUsage || false;
this.actualStack = options.actualStack;
this.operator = options.operator;
this.values = options.values || [];
// Raw expected and actual objects are stored for custom reporters
// (such as wallaby.js), that manage worker processes directly and
// use the values for custom diff views
this.raw = options.raw;
// Reserved for power-assert statements
this.statements = [];
if (options.savedError) {
this.savedError = options.savedError;
} else {
this.savedError = getErrorWithLongStackTrace();
}
}
}
exports.AssertionError = AssertionError;
function getErrorWithLongStackTrace() {
const limitBefore = Error.stackTraceLimit;
Error.stackTraceLimit = Infinity;
const err = new Error();
Error.stackTraceLimit = limitBefore;
return err;
}
function validateExpectations(assertion, expectations, numberArgs) { // eslint-disable-line complexity
if (numberArgs === 1 || expectations === null || expectations === undefined) {
expectations = {};
} else if (
typeof expectations === 'function' ||
typeof expectations === 'string' ||
expectations instanceof RegExp ||
typeof expectations !== 'object' ||
Array.isArray(expectations) ||
Object.keys(expectations).length === 0
) {
throw new AssertionError({
assertion,
message: `The second argument to \`t.${assertion}()\` must be an expectation object, \`null\` or \`undefined\``,
values: [formatWithLabel('Called with:', expectations)]
});
} else {
if (hasOwnProperty(expectations, 'instanceOf') && typeof expectations.instanceOf !== 'function') {
throw new AssertionError({
assertion,
message: `The \`instanceOf\` property of the second argument to \`t.${assertion}()\` must be a function`,
values: [formatWithLabel('Called with:', expectations)]
});
}
if (hasOwnProperty(expectations, 'message') && typeof expectations.message !== 'string' && !(expectations.message instanceof RegExp)) {
throw new AssertionError({
assertion,
message: `The \`message\` property of the second argument to \`t.${assertion}()\` must be a string or regular expression`,
values: [formatWithLabel('Called with:', expectations)]
});
}
if (hasOwnProperty(expectations, 'name') && typeof expectations.name !== 'string') {
throw new AssertionError({
assertion,
message: `The \`name\` property of the second argument to \`t.${assertion}()\` must be a string`,
values: [formatWithLabel('Called with:', expectations)]
});
}
if (hasOwnProperty(expectations, 'code') && typeof expectations.code !== 'string' && typeof expectations.code !== 'number') {
throw new AssertionError({
assertion,
message: `The \`code\` property of the second argument to \`t.${assertion}()\` must be a string or number`,
values: [formatWithLabel('Called with:', expectations)]
});
}
for (const key of Object.keys(expectations)) {
switch (key) {
case 'instanceOf':
case 'is':
case 'message':
case 'name':
case 'code':
continue;
default:
throw new AssertionError({
assertion,
message: `The second argument to \`t.${assertion}()\` contains unexpected properties`,
values: [formatWithLabel('Called with:', expectations)]
});
}
}
}
return expectations;
}
// Note: this function *must* throw exceptions, since it can be used
// as part of a pending assertion for promises.
function assertExpectations({assertion, actual, expectations, message, prefix, savedError}) {
if (!isError(actual)) {
throw new AssertionError({
assertion,
message,
savedError,
values: [formatWithLabel(`${prefix} exception that is not an error:`, actual)]
});
}
const actualStack = actual.stack;
if (hasOwnProperty(expectations, 'is') && actual !== expectations.is) {
throw new AssertionError({
assertion,
message,
savedError,
actualStack,
values: [
formatWithLabel(`${prefix} unexpected exception:`, actual),
formatWithLabel('Expected to be strictly equal to:', expectations.is)
]
});
}
if (expectations.instanceOf && !(actual instanceof expectations.instanceOf)) {
throw new AssertionError({
assertion,
message,
savedError,
actualStack,
values: [
formatWithLabel(`${prefix} unexpected exception:`, actual),
formatWithLabel('Expected instance of:', expectations.instanceOf)
]
});
}
if (typeof expectations.name === 'string' && actual.name !== expectations.name) {
throw new AssertionError({
assertion,
message,
savedError,
actualStack,
values: [
formatWithLabel(`${prefix} unexpected exception:`, actual),
formatWithLabel('Expected name to equal:', expectations.name)
]
});
}
if (typeof expectations.message === 'string' && actual.message !== expectations.message) {
throw new AssertionError({
assertion,
message,
savedError,
actualStack,
values: [
formatWithLabel(`${prefix} unexpected exception:`, actual),
formatWithLabel('Expected message to equal:', expectations.message)
]
});
}
if (expectations.message instanceof RegExp && !expectations.message.test(actual.message)) {
throw new AssertionError({
assertion,
message,
savedError,
actualStack,
values: [
formatWithLabel(`${prefix} unexpected exception:`, actual),
formatWithLabel('Expected message to match:', expectations.message)
]
});
}
if (typeof expectations.code !== 'undefined' && actual.code !== expectations.code) {
throw new AssertionError({
assertion,
message,
savedError,
actualStack,
values: [
formatWithLabel(`${prefix} unexpected exception:`, actual),
formatWithLabel('Expected code to equal:', expectations.code)
]
});
}
}
class Assertions {
constructor({
pass = notImplemented,
pending = notImplemented,
fail = notImplemented,
skip = notImplemented,
compareWithSnapshot = notImplemented,
powerAssert
} = {}) {
const withSkip = assertionFn => {
assertionFn.skip = skip;
return assertionFn;
};
// When adding new enhanced functions with new patterns, don't forget to
// enable the pattern in the power-assert compilation step in @ava/babel.
const withPowerAssert = (pattern, assertionFn) => powerAssert.empower(assertionFn, {
onError: event => {
if (event.powerAssertContext) {
event.error.statements = powerAssert.format(event.powerAssertContext, formatPowerAssertValue);
}
fail(event.error);
},
onSuccess: () => {
pass();
},
bindReceiver: false,
patterns: [pattern]
});
const checkMessage = (assertion, message, powerAssert = false) => {
if (typeof message === 'undefined' || typeof message === 'string') {
return true;
}
const error = new AssertionError({
assertion,
improperUsage: true,
message: 'The assertion message must be a string',
values: [formatWithLabel('Called with:', message)]
});
if (powerAssert) {
throw error;
}
fail(error);
return false;
};
this.pass = withSkip(() => {
pass();
});
this.fail = withSkip(message => {
if (!checkMessage('fail', message)) {
return;
}
fail(new AssertionError({
assertion: 'fail',
message: message || 'Test failed via `t.fail()`'
}));
});
this.is = withSkip((actual, expected, message) => {
if (!checkMessage('is', message)) {
return;
}
if (Object.is(actual, expected)) {
pass();
} else {
const result = concordance.compare(actual, expected, concordanceOptions);
const actualDescriptor = result.actual || concordance.describe(actual, concordanceOptions);
const expectedDescriptor = result.expected || concordance.describe(expected, concordanceOptions);
if (result.pass) {
fail(new AssertionError({
assertion: 'is',
message,
raw: {actual, expected},
values: [formatDescriptorWithLabel('Values are deeply equal to each other, but they are not the same:', actualDescriptor)]
}));
} else {
fail(new AssertionError({
assertion: 'is',
message,
raw: {actual, expected},
values: [formatDescriptorDiff(actualDescriptor, expectedDescriptor)]
}));
}
}
});
this.not = withSkip((actual, expected, message) => {
if (!checkMessage('not', message)) {
return;
}
if (Object.is(actual, expected)) {
fail(new AssertionError({
assertion: 'not',
message,
raw: {actual, expected},
values: [formatWithLabel('Value is the same as:', actual)]
}));
} else {
pass();
}
});
this.deepEqual = withSkip((actual, expected, message) => {
if (!checkMessage('deepEqual', message)) {
return;
}
const result = concordance.compare(actual, expected, concordanceOptions);
if (result.pass) {
pass();
} else {
const actualDescriptor = result.actual || concordance.describe(actual, concordanceOptions);
const expectedDescriptor = result.expected || concordance.describe(expected, concordanceOptions);
fail(new AssertionError({
assertion: 'deepEqual',
message,
raw: {actual, expected},
values: [formatDescriptorDiff(actualDescriptor, expectedDescriptor)]
}));
}
});
this.notDeepEqual = withSkip((actual, expected, message) => {
if (!checkMessage('notDeepEqual', message)) {
return;
}
const result = concordance.compare(actual, expected, concordanceOptions);
if (result.pass) {
const actualDescriptor = result.actual || concordance.describe(actual, concordanceOptions);
fail(new AssertionError({
assertion: 'notDeepEqual',
message,
raw: {actual, expected},
values: [formatDescriptorWithLabel('Value is deeply equal:', actualDescriptor)]
}));
} else {
pass();
}
});
this.throws = withSkip((...args) => {
// Since arrow functions do not support 'arguments', we are using rest
// operator, so we can determine the total number of arguments passed
// to the function.
let [fn, expectations, message] = args;
if (!checkMessage('throws', message)) {
return;
}
if (typeof fn !== 'function') {
fail(new AssertionError({
assertion: 'throws',
improperUsage: true,
message: '`t.throws()` must be called with a function',
values: [formatWithLabel('Called with:', fn)]
}));
return;
}
try {
expectations = validateExpectations('throws', expectations, args.length);
} catch (error) {
fail(error);
return;
}
let retval;
let actual = null;
try {
retval = fn();
if (isPromise(retval)) {
// Here isPromise() checks if something is "promise like". Cast to an actual promise.
Promise.resolve(retval).catch(noop);
fail(new AssertionError({
assertion: 'throws',
message,
values: [formatWithLabel('Function returned a promise. Use `t.throwsAsync()` instead:', retval)]
}));
return;
}
} catch (error) {
actual = error;
}
if (!actual) {
fail(new AssertionError({
assertion: 'throws',
message,
values: [formatWithLabel('Function returned:', retval)]
}));
return;
}
try {
assertExpectations({
assertion: 'throws',
actual,
expectations,
message,
prefix: 'Function threw'
});
pass();
return actual;
} catch (error) {
fail(error);
}
});
this.throwsAsync = withSkip((...args) => {
let [thrower, expectations, message] = args;
if (!checkMessage('throwsAsync', message)) {
return Promise.resolve();
}
if (typeof thrower !== 'function' && !isPromise(thrower)) {
fail(new AssertionError({
assertion: 'throwsAsync',
improperUsage: true,
message: '`t.throwsAsync()` must be called with a function or promise',
values: [formatWithLabel('Called with:', thrower)]
}));
return Promise.resolve();
}
try {
expectations = validateExpectations('throwsAsync', expectations, args.length);
} catch (error) {
fail(error);
return Promise.resolve();
}
const handlePromise = (promise, wasReturned) => {
// Create an error object to record the stack before it gets lost in the promise chain.
const savedError = getErrorWithLongStackTrace();
// Handle "promise like" objects by casting to a real Promise.
const intermediate = Promise.resolve(promise).then(value => { // eslint-disable-line promise/prefer-await-to-then
throw new AssertionError({
assertion: 'throwsAsync',
message,
savedError,
values: [formatWithLabel(`${wasReturned ? 'Returned promise' : 'Promise'} resolved with:`, value)]
});
}, error => {
assertExpectations({
assertion: 'throwsAsync',
actual: error,
expectations,
message,
prefix: `${wasReturned ? 'Returned promise' : 'Promise'} rejected with`,
savedError
});
return error;
});
pending(intermediate);
// Don't reject the returned promise, even if the assertion fails.
return intermediate.catch(noop);
};
if (isPromise(thrower)) {
return handlePromise(thrower, false);
}
let retval;
let actual = null;
try {
retval = thrower();
} catch (error) {
actual = error;
}
if (actual) {
fail(new AssertionError({
assertion: 'throwsAsync',
message,
actualStack: actual.stack,
values: [formatWithLabel('Function threw synchronously. Use `t.throws()` instead:', actual)]
}));
return Promise.resolve();
}
if (isPromise(retval)) {
return handlePromise(retval, true);
}
fail(new AssertionError({
assertion: 'throwsAsync',
message,
values: [formatWithLabel('Function returned:', retval)]
}));
return Promise.resolve();
});
this.notThrows = withSkip((fn, message) => {
if (!checkMessage('notThrows', message)) {
return;
}
if (typeof fn !== 'function') {
fail(new AssertionError({
assertion: 'notThrows',
improperUsage: true,
message: '`t.notThrows()` must be called with a function',
values: [formatWithLabel('Called with:', fn)]
}));
return;
}
try {
fn();
} catch (error) {
fail(new AssertionError({
assertion: 'notThrows',
message,
actualStack: error.stack,
values: [formatWithLabel('Function threw:', error)]
}));
return;
}
pass();
});
this.notThrowsAsync = withSkip((nonThrower, message) => {
if (!checkMessage('notThrowsAsync', message)) {
return Promise.resolve();
}
if (typeof nonThrower !== 'function' && !isPromise(nonThrower)) {
fail(new AssertionError({
assertion: 'notThrowsAsync',
improperUsage: true,
message: '`t.notThrowsAsync()` must be called with a function or promise',
values: [formatWithLabel('Called with:', nonThrower)]
}));
return Promise.resolve();
}
const handlePromise = (promise, wasReturned) => {
// Create an error object to record the stack before it gets lost in the promise chain.
const savedError = getErrorWithLongStackTrace();
// Handle "promise like" objects by casting to a real Promise.
const intermediate = Promise.resolve(promise).then(noop, error => { // eslint-disable-line promise/prefer-await-to-then
throw new AssertionError({
assertion: 'notThrowsAsync',
message,
savedError,
values: [formatWithLabel(`${wasReturned ? 'Returned promise' : 'Promise'} rejected with:`, error)]
});
});
pending(intermediate);
// Don't reject the returned promise, even if the assertion fails.
return intermediate.catch(noop);
};
if (isPromise(nonThrower)) {
return handlePromise(nonThrower, false);
}
let retval;
try {
retval = nonThrower();
} catch (error) {
fail(new AssertionError({
assertion: 'notThrowsAsync',
message,
actualStack: error.stack,
values: [formatWithLabel('Function threw:', error)]
}));
return Promise.resolve();
}
if (!isPromise(retval)) {
fail(new AssertionError({
assertion: 'notThrowsAsync',
message,
values: [formatWithLabel('Function did not return a promise. Use `t.notThrows()` instead:', retval)]
}));
return Promise.resolve();
}
return handlePromise(retval, true);
});
this.snapshot = withSkip((expected, ...rest) => {
let message;
let snapshotOptions;
if (rest.length > 1) {
[snapshotOptions, message] = rest;
} else {
const [optionsOrMessage] = rest;
if (typeof optionsOrMessage === 'object') {
snapshotOptions = optionsOrMessage;
} else {
message = optionsOrMessage;
}
}
if (!checkMessage('snapshot', message)) {
return;
}
let result;
try {
result = compareWithSnapshot({
expected,
id: snapshotOptions ? snapshotOptions.id : undefined,
message
});
} catch (error) {
if (!(error instanceof snapshotManager.SnapshotError)) {
throw error;
}
const improperUsage = {name: error.name, snapPath: error.snapPath};
if (error instanceof snapshotManager.VersionMismatchError) {
improperUsage.snapVersion = error.snapVersion;
improperUsage.expectedVersion = error.expectedVersion;
}
fail(new AssertionError({
assertion: 'snapshot',
message: message || 'Could not compare snapshot',
improperUsage
}));
return;
}
if (result.pass) {
pass();
} else if (result.actual) {
fail(new AssertionError({
assertion: 'snapshot',
message: message || 'Did not match snapshot',
values: [formatDescriptorDiff(result.actual, result.expected, {invert: true})]
}));
} else {
// This can only occur in CI environments.
fail(new AssertionError({
assertion: 'snapshot',
message: message || 'No snapshot available — new snapshots are not created in CI environments'
}));
}
});
this.truthy = withSkip((actual, message) => {
if (!checkMessage('truthy', message)) {
return;
}
if (actual) {
pass();
} else {
fail(new AssertionError({
assertion: 'truthy',
message,
operator: '!!',
values: [formatWithLabel('Value is not truthy:', actual)]
}));
}
});
this.falsy = withSkip((actual, message) => {
if (!checkMessage('falsy', message)) {
return;
}
if (actual) {
fail(new AssertionError({
assertion: 'falsy',
message,
operator: '!',
values: [formatWithLabel('Value is not falsy:', actual)]
}));
} else {
pass();
}
});
this.true = withSkip((actual, message) => {
if (!checkMessage('true', message)) {
return;
}
if (actual === true) {
pass();
} else {
fail(new AssertionError({
assertion: 'true',
message,
values: [formatWithLabel('Value is not `true`:', actual)]
}));
}
});
this.false = withSkip((actual, message) => {
if (!checkMessage('false', message)) {
return;
}
if (actual === false) {
pass();
} else {
fail(new AssertionError({
assertion: 'false',
message,
values: [formatWithLabel('Value is not `false`:', actual)]
}));
}
});
this.regex = withSkip((string, regex, message) => {
if (!checkMessage('regex', message)) {
return;
}
if (typeof string !== 'string') {
fail(new AssertionError({
assertion: 'regex',
improperUsage: true,
message: '`t.regex()` must be called with a string',
values: [formatWithLabel('Called with:', string)]
}));
return;
}
if (!(regex instanceof RegExp)) {
fail(new AssertionError({
assertion: 'regex',
improperUsage: true,
message: '`t.regex()` must be called with a regular expression',
values: [formatWithLabel('Called with:', regex)]
}));
return;
}
if (!regex.test(string)) {
fail(new AssertionError({
assertion: 'regex',
message,
values: [
formatWithLabel('Value must match expression:', string),
formatWithLabel('Regular expression:', regex)
]
}));
return;
}
pass();
});
this.notRegex = withSkip((string, regex, message) => {
if (!checkMessage('notRegex', message)) {
return;
}
if (typeof string !== 'string') {
fail(new AssertionError({
assertion: 'notRegex',
improperUsage: true,
message: '`t.notRegex()` must be called with a string',
values: [formatWithLabel('Called with:', string)]
}));
return;
}
if (!(regex instanceof RegExp)) {
fail(new AssertionError({
assertion: 'notRegex',
improperUsage: true,
message: '`t.notRegex()` must be called with a regular expression',
values: [formatWithLabel('Called with:', regex)]
}));
return;
}
if (regex.test(string)) {
fail(new AssertionError({
assertion: 'notRegex',
message,
values: [
formatWithLabel('Value must not match expression:', string),
formatWithLabel('Regular expression:', regex)
]
}));
return;
}
pass();
});
if (powerAssert === undefined) {
this.assert = withSkip((actual, message) => {
if (!checkMessage('assert', message)) {
return;
}
if (!actual) {
fail(new AssertionError({
assertion: 'assert',
message,
operator: '!!',
values: [formatWithLabel('Value is not truthy:', actual)]
}));
return;
}
pass();
});
} else {
this.assert = withSkip(withPowerAssert(
'assert(value, [message])',
(actual, message) => {
checkMessage('assert', message, true);
if (!actual) {
throw new AssertionError({
assertion: 'assert',
message,
operator: '!!',
values: [formatWithLabel('Value is not truthy:', actual)]
});
}
})
);
}
}
}
exports.Assertions = Assertions;

20
node_modules/ava/lib/chalk.js generated vendored Normal file
View file

@ -0,0 +1,20 @@
'use strict';
const chalk = require('chalk');
let ctx = null;
exports.get = () => {
if (!ctx) {
throw new Error('Chalk has not yet been configured');
}
return ctx;
};
exports.set = options => {
if (ctx) {
throw new Error('Chalk has already been configured');
}
ctx = new chalk.Instance(options);
return ctx;
};

449
node_modules/ava/lib/cli.js generated vendored Normal file
View file

@ -0,0 +1,449 @@
'use strict';
const path = require('path');
const del = require('del');
const updateNotifier = require('update-notifier');
const figures = require('figures');
const arrify = require('arrify');
const yargs = require('yargs');
const readPkg = require('read-pkg');
const isCi = require('./is-ci');
const loadConfig = require('./load-config');
function exit(message) {
console.error(`\n ${require('./chalk').get().red(figures.cross)} ${message}`);
process.exit(1); // eslint-disable-line unicorn/no-process-exit
}
const coerceLastValue = value => {
return Array.isArray(value) ? value.pop() : value;
};
const FLAGS = {
concurrency: {
alias: 'c',
coerce: coerceLastValue,
description: 'Max number of test files running at the same time (default: CPU cores)',
type: 'number'
},
'fail-fast': {
coerce: coerceLastValue,
description: 'Stop after first test failure',
type: 'boolean'
},
match: {
alias: 'm',
description: 'Only run tests with matching title (can be repeated)',
type: 'string'
},
'node-arguments': {
coerce: coerceLastValue,
description: 'Additional Node.js arguments for launching worker processes (specify as a single string)',
type: 'string'
},
serial: {
alias: 's',
coerce: coerceLastValue,
description: 'Run tests serially',
type: 'boolean'
},
tap: {
alias: 't',
coerce: coerceLastValue,
description: 'Generate TAP output',
type: 'boolean'
},
timeout: {
alias: 'T',
coerce: coerceLastValue,
description: 'Set global timeout (milliseconds or human-readable, e.g. 10s, 2m)',
type: 'string'
},
'update-snapshots': {
alias: 'u',
coerce: coerceLastValue,
description: 'Update snapshots',
type: 'boolean'
},
verbose: {
alias: 'v',
coerce: coerceLastValue,
description: 'Enable verbose output',
type: 'boolean'
},
watch: {
alias: 'w',
coerce: coerceLastValue,
description: 'Re-run tests when files change',
type: 'boolean'
}
};
exports.run = async () => { // eslint-disable-line complexity
let conf = {};
let confError = null;
try {
const {argv: {config: configFile}} = yargs.help(false);
conf = loadConfig({configFile});
} catch (error) {
confError = error;
}
let debug = null;
let resetCache = false;
const {argv} = yargs
.parserConfiguration({
'boolean-negation': true,
'camel-case-expansion': false,
'combine-arrays': false,
'dot-notation': false,
'duplicate-arguments-array': true,
'flatten-duplicate-arrays': true,
'negation-prefix': 'no-',
'parse-numbers': true,
'populate--': true,
'set-placeholder-key': false,
'short-option-groups': true,
'strip-aliased': true,
'unknown-options-as-args': false
})
.usage('$0 [<pattern>...]')
.usage('$0 debug [<pattern>...]')
.usage('$0 reset-cache')
.options({
color: {
description: 'Force color output',
type: 'boolean'
},
config: {
description: 'Specific JavaScript file for AVA to read its config from, instead of using package.json or ava.config.* files'
}
})
.command('* [<pattern>...]', 'Run tests', yargs => yargs.options(FLAGS).positional('pattern', {
array: true,
describe: 'Glob patterns to select what test files to run. Leave empty if you want AVA to run all test files instead. Add a colon and specify line numbers of specific tests to run',
type: 'string'
}))
.command(
'debug [<pattern>...]',
'Activate Node.js inspector and run a single test file',
yargs => yargs.options(FLAGS).options({
break: {
description: 'Break before the test file is loaded',
type: 'boolean'
},
host: {
default: '127.0.0.1',
description: 'Address or hostname through which you can connect to the inspector',
type: 'string'
},
port: {
default: 9229,
description: 'Port on which you can connect to the inspector',
type: 'number'
}
}).positional('pattern', {
demand: true,
describe: 'Glob patterns to select a single test file to debug. Add a colon and specify line numbers of specific tests to run',
type: 'string'
}),
argv => {
debug = {
break: argv.break === true,
files: argv.pattern,
host: argv.host,
port: argv.port
};
})
.command(
'reset-cache',
'Reset AVAs compilation cache and exit',
yargs => yargs,
() => {
resetCache = true;
})
.example('$0')
.example('$0 test.js')
.example('$0 test.js:4,7-9')
.help();
const combined = {...conf};
for (const flag of Object.keys(FLAGS)) {
if (Reflect.has(argv, flag)) {
if (flag === 'fail-fast') {
combined.failFast = argv[flag];
} else if (flag === 'update-snapshots') {
combined.updateSnapshots = argv[flag];
} else if (flag !== 'node-arguments') {
combined[flag] = argv[flag];
}
}
}
const chalkOptions = {level: combined.color === false ? 0 : require('chalk').level};
const chalk = require('./chalk').set(chalkOptions);
if (confError) {
if (confError.parent) {
exit(`${confError.message}\n\n${chalk.gray((confError.parent && confError.parent.stack) || confError.parent)}`);
} else {
exit(confError.message);
}
}
updateNotifier({pkg: require('../package.json')}).notify();
const {nonSemVerExperiments: experiments, projectDir} = conf;
if (resetCache) {
const cacheDir = path.join(projectDir, 'node_modules', '.cache', 'ava');
try {
await del('*', {
cwd: cacheDir,
nodir: true
});
console.error(`\n${chalk.green(figures.tick)} Removed AVA cache files in ${cacheDir}`);
process.exit(0); // eslint-disable-line unicorn/no-process-exit
} catch (error) {
exit(`Error removing AVA cache files in ${cacheDir}\n\n${chalk.gray((error && error.stack) || error)}`);
}
return;
}
if (argv.watch) {
if (argv.tap && !conf.tap) {
exit('The TAP reporter is not available when using watch mode.');
}
if (isCi) {
exit('Watch mode is not available in CI, as it prevents AVA from terminating.');
}
if (debug !== null) {
exit('Watch mode is not available when debugging.');
}
}
if (debug !== null) {
if (argv.tap && !conf.tap) {
exit('The TAP reporter is not available when debugging.');
}
if (isCi) {
exit('Debugging is not available in CI.');
}
if (combined.timeout) {
console.log(chalk.magenta(` ${figures.warning} The timeout option has been disabled to help with debugging.`));
}
}
if (Reflect.has(combined, 'concurrency') && (!Number.isInteger(combined.concurrency) || combined.concurrency < 0)) {
exit('The --concurrency or -c flag must be provided with a nonnegative integer.');
}
if (!combined.tap && Object.keys(experiments).length > 0) {
console.log(chalk.magenta(` ${figures.warning} Experiments are enabled. These are unsupported and may change or be removed at any time.`));
}
if (Reflect.has(conf, 'compileEnhancements')) {
exit('Enhancement compilation must be configured in AVAs Babel options.');
}
if (Reflect.has(conf, 'helpers')) {
exit('AVA no longer compiles helpers. Add exclusion patterns to the files configuration and specify compileAsTests in the Babel options instead.');
}
if (Reflect.has(conf, 'sources')) {
exit('sources has been removed. Use ignoredByWatcher to provide glob patterns of files that the watcher should ignore.');
}
const ciParallelVars = require('ci-parallel-vars');
const Api = require('./api');
const VerboseReporter = require('./reporters/verbose');
const MiniReporter = require('./reporters/mini');
const TapReporter = require('./reporters/tap');
const Watcher = require('./watcher');
const normalizeExtensions = require('./extensions');
const {normalizeGlobs, normalizePattern} = require('./globs');
const normalizeNodeArguments = require('./node-arguments');
const validateEnvironmentVariables = require('./environment-variables');
const {splitPatternAndLineNumbers} = require('./line-numbers');
const providerManager = require('./provider-manager');
let pkg;
try {
pkg = readPkg.sync({cwd: projectDir});
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}
const {type: defaultModuleType = 'commonjs'} = pkg || {};
const moduleTypes = {
cjs: 'commonjs',
mjs: 'module',
js: defaultModuleType
};
const providers = [];
if (Reflect.has(conf, 'babel')) {
try {
const {level, main} = providerManager.babel(projectDir);
providers.push({
level,
main: main({config: conf.babel}),
type: 'babel'
});
} catch (error) {
exit(error.message);
}
}
if (Reflect.has(conf, 'typescript')) {
try {
const {level, main} = providerManager.typescript(projectDir);
providers.push({
level,
main: main({config: conf.typescript}),
type: 'typescript'
});
} catch (error) {
exit(error.message);
}
}
let environmentVariables;
try {
environmentVariables = validateEnvironmentVariables(conf.environmentVariables);
} catch (error) {
exit(error.message);
}
let extensions;
try {
extensions = normalizeExtensions(conf.extensions, providers);
} catch (error) {
exit(error.message);
}
let globs;
try {
globs = normalizeGlobs({files: conf.files, ignoredByWatcher: conf.ignoredByWatcher, extensions, providers});
} catch (error) {
exit(error.message);
}
let nodeArguments;
try {
nodeArguments = normalizeNodeArguments(conf.nodeArguments, argv['node-arguments']);
} catch (error) {
exit(error.message);
}
let parallelRuns = null;
if (isCi && ciParallelVars) {
const {index: currentIndex, total: totalRuns} = ciParallelVars;
parallelRuns = {currentIndex, totalRuns};
}
const match = combined.match === '' ? [] : arrify(combined.match);
const input = debug ? debug.files : (argv.pattern || []);
const filter = input
.map(pattern => splitPatternAndLineNumbers(pattern))
.map(({pattern, ...rest}) => ({
pattern: normalizePattern(path.relative(projectDir, path.resolve(process.cwd(), pattern))),
...rest
}));
const api = new Api({
cacheEnabled: combined.cache !== false,
chalkOptions,
concurrency: combined.concurrency || 0,
debug,
environmentVariables,
experiments,
extensions,
failFast: combined.failFast,
failWithoutAssertions: combined.failWithoutAssertions !== false,
globs,
match,
moduleTypes,
nodeArguments,
parallelRuns,
projectDir,
providers,
ranFromCli: true,
require: arrify(combined.require),
serial: combined.serial,
snapshotDir: combined.snapshotDir ? path.resolve(projectDir, combined.snapshotDir) : null,
timeout: combined.timeout || '10s',
updateSnapshots: combined.updateSnapshots,
workerArgv: argv['--']
});
let reporter;
if (combined.tap && !combined.watch && debug === null) {
reporter = new TapReporter({
projectDir,
reportStream: process.stdout,
stdStream: process.stderr
});
} else if (debug !== null || combined.verbose || isCi || !process.stdout.isTTY) {
reporter = new VerboseReporter({
projectDir,
reportStream: process.stdout,
stdStream: process.stderr,
watching: combined.watch
});
} else {
reporter = new MiniReporter({
projectDir,
reportStream: process.stdout,
stdStream: process.stderr,
watching: combined.watch
});
}
api.on('run', plan => {
reporter.startRun(plan);
plan.status.on('stateChange', evt => {
if (evt.type === 'interrupt') {
reporter.endRun();
process.exit(1); // eslint-disable-line unicorn/no-process-exit
}
});
});
if (combined.watch) {
const watcher = new Watcher({
api,
filter,
globs,
projectDir,
providers,
reporter
});
watcher.observeStdin(process.stdin);
} else {
let debugWithoutSpecificFile = false;
api.on('run', plan => {
if (plan.debug && plan.files.length !== 1) {
debugWithoutSpecificFile = true;
}
});
const runStatus = await api.run({filter});
if (debugWithoutSpecificFile) {
exit('Provide the path to the test file you wish to debug');
return;
}
process.exitCode = runStatus.suggestExitCode({matching: match.length > 0});
reporter.endRun();
}
};

54
node_modules/ava/lib/code-excerpt.js generated vendored Normal file
View file

@ -0,0 +1,54 @@
'use strict';
const fs = require('fs');
const equalLength = require('equal-length');
const codeExcerpt = require('code-excerpt');
const truncate = require('cli-truncate');
const chalk = require('./chalk').get();
const formatLineNumber = (lineNumber, maxLineNumber) =>
' '.repeat(Math.max(0, String(maxLineNumber).length - String(lineNumber).length)) + lineNumber;
module.exports = (source, options = {}) => {
if (!source.isWithinProject || source.isDependency) {
return null;
}
const {file, line} = source;
const maxWidth = options.maxWidth || 80;
let contents;
try {
contents = fs.readFileSync(file, 'utf8');
} catch (_) {
return null;
}
const excerpt = codeExcerpt(contents, line, {around: 1});
if (!excerpt) {
return null;
}
const lines = excerpt.map(item => ({
line: item.line,
value: truncate(item.value, maxWidth - String(line).length - 5)
}));
const joinedLines = lines.map(line => line.value).join('\n');
const extendedLines = equalLength(joinedLines).split('\n');
return lines
.map((item, index) => ({
line: item.line,
value: extendedLines[index]
}))
.map(item => {
const isErrorSource = item.line === line;
const lineNumber = formatLineNumber(item.line, line) + ':';
const coloredLineNumber = isErrorSource ? lineNumber : chalk.grey(lineNumber);
const result = ` ${coloredLineNumber} ${item.value}`;
return isErrorSource ? chalk.bgRed(result) : result;
})
.join('\n');
};

139
node_modules/ava/lib/concordance-options.js generated vendored Normal file
View file

@ -0,0 +1,139 @@
'use strict';
const util = require('util');
const ansiStyles = require('ansi-styles');
const stripAnsi = require('strip-ansi');
const cloneDeepWith = require('lodash/cloneDeepWith');
const reactPlugin = require('@concordance/react');
const chalk = require('./chalk').get();
// Wrap Concordance's React plugin. Change the name to avoid collisions if in
// the future users can register plugins themselves.
const avaReactPlugin = {...reactPlugin, name: 'ava-plugin-react'};
const plugins = [avaReactPlugin];
const forceColor = new chalk.Instance({level: Math.max(chalk.level, 1)});
const colorTheme = {
boolean: ansiStyles.yellow,
circular: forceColor.grey('[Circular]'),
date: {
invalid: forceColor.red('invalid'),
value: ansiStyles.blue
},
diffGutters: {
actual: forceColor.red('-') + ' ',
expected: forceColor.green('+') + ' ',
padding: ' '
},
error: {
ctor: {open: ansiStyles.grey.open + '(', close: ')' + ansiStyles.grey.close},
name: ansiStyles.magenta
},
function: {
name: ansiStyles.blue,
stringTag: ansiStyles.magenta
},
global: ansiStyles.magenta,
item: {after: forceColor.grey(',')},
list: {openBracket: forceColor.grey('['), closeBracket: forceColor.grey(']')},
mapEntry: {after: forceColor.grey(',')},
maxDepth: forceColor.grey('…'),
null: ansiStyles.yellow,
number: ansiStyles.yellow,
object: {
openBracket: forceColor.grey('{'),
closeBracket: forceColor.grey('}'),
ctor: ansiStyles.magenta,
stringTag: {open: ansiStyles.magenta.open + '@', close: ansiStyles.magenta.close},
secondaryStringTag: {open: ansiStyles.grey.open + '@', close: ansiStyles.grey.close}
},
property: {
after: forceColor.grey(','),
keyBracket: {open: forceColor.grey('['), close: forceColor.grey(']')},
valueFallback: forceColor.grey('…')
},
react: {
functionType: forceColor.grey('\u235F'),
openTag: {
start: forceColor.grey('<'),
end: forceColor.grey('>'),
selfClose: forceColor.grey('/'),
selfCloseVoid: ' ' + forceColor.grey('/')
},
closeTag: {
open: forceColor.grey('</'),
close: forceColor.grey('>')
},
tagName: ansiStyles.magenta,
attribute: {
separator: '=',
value: {
openBracket: forceColor.grey('{'),
closeBracket: forceColor.grey('}'),
string: {
line: {open: forceColor.blue('"'), close: forceColor.blue('"'), escapeQuote: '"'}
}
}
},
child: {
openBracket: forceColor.grey('{'),
closeBracket: forceColor.grey('}')
}
},
regexp: {
source: {open: ansiStyles.blue.open + '/', close: '/' + ansiStyles.blue.close},
flags: ansiStyles.yellow
},
stats: {separator: forceColor.grey('---')},
string: {
open: ansiStyles.blue.open,
close: ansiStyles.blue.close,
line: {open: forceColor.blue('\''), close: forceColor.blue('\'')},
multiline: {start: forceColor.blue('`'), end: forceColor.blue('`')},
controlPicture: ansiStyles.grey,
diff: {
insert: {
open: ansiStyles.bgGreen.open + ansiStyles.black.open,
close: ansiStyles.black.close + ansiStyles.bgGreen.close
},
delete: {
open: ansiStyles.bgRed.open + ansiStyles.black.open,
close: ansiStyles.black.close + ansiStyles.bgRed.close
},
equal: ansiStyles.blue,
insertLine: {
open: ansiStyles.green.open,
close: ansiStyles.green.close
},
deleteLine: {
open: ansiStyles.red.open,
close: ansiStyles.red.close
}
}
},
symbol: ansiStyles.yellow,
typedArray: {
bytes: ansiStyles.yellow
},
undefined: ansiStyles.yellow
};
const plainTheme = cloneDeepWith(colorTheme, value => {
if (typeof value === 'string') {
return stripAnsi(value);
}
});
const theme = chalk.level > 0 ? colorTheme : plainTheme;
exports.default = {
// Use Node's object inspection depth, clamped to a minimum of 3
get maxDepth() {
return Math.max(3, util.inspect.defaultOptions.depth);
},
plugins,
theme
};
exports.diff = {maxDepth: 1, plugins, theme};
exports.snapshotManager = {plugins, theme: plainTheme};

42
node_modules/ava/lib/context-ref.js generated vendored Normal file
View file

@ -0,0 +1,42 @@
'use strict';
const clone = require('lodash/clone');
class ContextRef {
constructor() {
this.value = {};
}
get() {
return this.value;
}
set(newValue) {
this.value = newValue;
}
copy() {
return new LateBinding(this);
}
}
module.exports = ContextRef;
class LateBinding extends ContextRef {
constructor(ref) {
super();
this.ref = ref;
this.bound = false;
}
get() {
if (!this.bound) {
this.set(clone(this.ref.get()));
}
return super.get();
}
set(newValue) {
this.bound = true;
super.set(newValue);
}
}

116
node_modules/ava/lib/create-chain.js generated vendored Normal file
View file

@ -0,0 +1,116 @@
'use strict';
const chainRegistry = new WeakMap();
function startChain(name, call, defaults) {
const fn = (...args) => {
call({...defaults}, args);
};
Object.defineProperty(fn, 'name', {value: name});
chainRegistry.set(fn, {call, defaults, fullName: name});
return fn;
}
function extendChain(previous, name, flag) {
if (!flag) {
flag = name;
}
const fn = (...args) => {
callWithFlag(previous, flag, args);
};
const fullName = `${chainRegistry.get(previous).fullName}.${name}`;
Object.defineProperty(fn, 'name', {value: fullName});
previous[name] = fn;
chainRegistry.set(fn, {flag, fullName, prev: previous});
return fn;
}
function callWithFlag(previous, flag, args) {
const combinedFlags = {[flag]: true};
do {
const step = chainRegistry.get(previous);
if (step.call) {
step.call({...step.defaults, ...combinedFlags}, args);
previous = null;
} else {
combinedFlags[step.flag] = true;
previous = step.prev;
}
} while (previous);
}
function createHookChain(hook, isAfterHook) {
// Hook chaining rules:
// * `always` comes immediately after "after hooks"
// * `skip` must come at the end
// * no `only`
// * no repeating
extendChain(hook, 'cb', 'callback');
extendChain(hook, 'skip', 'skipped');
extendChain(hook.cb, 'skip', 'skipped');
if (isAfterHook) {
extendChain(hook, 'always');
extendChain(hook.always, 'cb', 'callback');
extendChain(hook.always, 'skip', 'skipped');
extendChain(hook.always.cb, 'skip', 'skipped');
}
return hook;
}
function createChain(fn, defaults, meta) {
// Test chaining rules:
// * `serial` must come at the start
// * `only` and `skip` must come at the end
// * `failing` must come at the end, but can be followed by `only` and `skip`
// * `only` and `skip` cannot be chained together
// * no repeating
const root = startChain('test', fn, {...defaults, type: 'test'});
extendChain(root, 'cb', 'callback');
extendChain(root, 'failing');
extendChain(root, 'only', 'exclusive');
extendChain(root, 'serial');
extendChain(root, 'skip', 'skipped');
extendChain(root.cb, 'failing');
extendChain(root.cb, 'only', 'exclusive');
extendChain(root.cb, 'skip', 'skipped');
extendChain(root.cb.failing, 'only', 'exclusive');
extendChain(root.cb.failing, 'skip', 'skipped');
extendChain(root.failing, 'only', 'exclusive');
extendChain(root.failing, 'skip', 'skipped');
extendChain(root.serial, 'cb', 'callback');
extendChain(root.serial, 'failing');
extendChain(root.serial, 'only', 'exclusive');
extendChain(root.serial, 'skip', 'skipped');
extendChain(root.serial.cb, 'failing');
extendChain(root.serial.cb, 'only', 'exclusive');
extendChain(root.serial.cb, 'skip', 'skipped');
extendChain(root.serial.cb.failing, 'only', 'exclusive');
extendChain(root.serial.cb.failing, 'skip', 'skipped');
extendChain(root.serial.failing, 'only', 'exclusive');
extendChain(root.serial.failing, 'skip', 'skipped');
root.after = createHookChain(startChain('test.after', fn, {...defaults, type: 'after'}), true);
root.afterEach = createHookChain(startChain('test.afterEach', fn, {...defaults, type: 'afterEach'}), true);
root.before = createHookChain(startChain('test.before', fn, {...defaults, type: 'before'}), false);
root.beforeEach = createHookChain(startChain('test.beforeEach', fn, {...defaults, type: 'beforeEach'}), false);
root.serial.after = createHookChain(startChain('test.after', fn, {...defaults, serial: true, type: 'after'}), true);
root.serial.afterEach = createHookChain(startChain('test.afterEach', fn, {...defaults, serial: true, type: 'afterEach'}), true);
root.serial.before = createHookChain(startChain('test.before', fn, {...defaults, serial: true, type: 'before'}), false);
root.serial.beforeEach = createHookChain(startChain('test.beforeEach', fn, {...defaults, serial: true, type: 'beforeEach'}), false);
// "todo" tests cannot be chained. Allow todo tests to be flagged as needing
// to be serial.
root.todo = startChain('test.todo', fn, {...defaults, type: 'test', todo: true});
root.serial.todo = startChain('test.serial.todo', fn, {...defaults, serial: true, type: 'test', todo: true});
root.meta = meta;
return root;
}
module.exports = createChain;

16
node_modules/ava/lib/environment-variables.js generated vendored Normal file
View file

@ -0,0 +1,16 @@
'use strict';
function validateEnvironmentVariables(environmentVariables) {
if (!environmentVariables) {
return {};
}
for (const value of Object.values(environmentVariables)) {
if (typeof value !== 'string') {
throw new TypeError('The environmentVariables configuration must be an object containing string values.');
}
}
return environmentVariables;
}
module.exports = validateEnvironmentVariables;

43
node_modules/ava/lib/extensions.js generated vendored Normal file
View file

@ -0,0 +1,43 @@
module.exports = (configuredExtensions, providers = []) => {
// Combine all extensions possible for testing. Remove duplicate extensions.
const duplicates = new Set();
const seen = new Set();
const combine = extensions => {
for (const ext of extensions) {
if (seen.has(ext)) {
duplicates.add(ext);
} else {
seen.add(ext);
}
}
};
if (configuredExtensions !== undefined) {
combine(configuredExtensions);
}
for (const {main} of providers) {
combine(main.extensions);
}
if (duplicates.size > 0) {
throw new Error(`Unexpected duplicate extensions in options: ${[...duplicates].join(', ')}.`);
}
// Unless the default was used by providers, as long as the extensions aren't explicitly set, set the default.
if (configuredExtensions === undefined) {
if (!seen.has('cjs')) {
seen.add('cjs');
}
if (!seen.has('mjs')) {
seen.add('mjs');
}
if (!seen.has('js')) {
seen.add('js');
}
}
return [...seen];
};

117
node_modules/ava/lib/fork.js generated vendored Normal file
View file

@ -0,0 +1,117 @@
'use strict';
const childProcess = require('child_process');
const path = require('path');
const fs = require('fs');
const Emittery = require('emittery');
if (fs.realpathSync(__filename) !== __filename) {
console.warn('WARNING: `npm link ava` and the `--preserve-symlink` flag are incompatible. We have detected that AVA is linked via `npm link`, and that you are using either an early version of Node 6, or the `--preserve-symlink` flag. This breaks AVA. You should upgrade to Node 6.2.0+, avoid the `--preserve-symlink` flag, or avoid using `npm link ava`.');
}
// In case the test file imports a different AVA install,
// the presence of this variable allows it to require this one instead
const AVA_PATH = path.resolve(__dirname, '..');
const workerPath = require.resolve('./worker/subprocess');
module.exports = (file, options, execArgv = process.execArgv) => {
let finished = false;
const emitter = new Emittery();
const emitStateChange = evt => {
if (!finished) {
emitter.emit('stateChange', Object.assign(evt, {testFile: file}));
}
};
options = {
file,
baseDir: process.cwd(),
...options
};
const subprocess = childProcess.fork(workerPath, options.workerArgv, {
cwd: options.projectDir,
silent: true,
env: {NODE_ENV: 'test', ...process.env, ...options.environmentVariables, AVA_PATH},
execArgv
});
subprocess.stdout.on('data', chunk => {
emitStateChange({type: 'worker-stdout', chunk});
});
subprocess.stderr.on('data', chunk => {
emitStateChange({type: 'worker-stderr', chunk});
});
let forcedExit = false;
const send = evt => {
if (subprocess.connected && !finished && !forcedExit) {
subprocess.send({ava: evt}, () => {
// Disregard errors.
});
}
};
const promise = new Promise(resolve => {
const finish = () => {
finished = true;
resolve();
};
subprocess.on('message', message => {
if (!message.ava) {
return;
}
if (message.ava.type === 'ready-for-options') {
send({type: 'options', options});
return;
}
if (message.ava.type === 'ping') {
send({type: 'pong'});
} else {
emitStateChange(message.ava);
}
});
subprocess.on('error', err => {
emitStateChange({type: 'worker-failed', err});
finish();
});
subprocess.on('exit', (code, signal) => {
if (forcedExit) {
emitStateChange({type: 'worker-finished', forcedExit});
} else if (code > 0) {
emitStateChange({type: 'worker-failed', nonZeroExitCode: code});
} else if (code === null && signal) {
emitStateChange({type: 'worker-failed', signal});
} else {
emitStateChange({type: 'worker-finished', forcedExit});
}
finish();
});
});
return {
exit() {
forcedExit = true;
subprocess.kill();
},
notifyOfPeerFailure() {
send({type: 'peer-failed'});
},
onStateChange(listener) {
return emitter.on('stateChange', listener);
},
file,
promise
};
};

247
node_modules/ava/lib/globs.js generated vendored Normal file
View file

@ -0,0 +1,247 @@
'use strict';
const path = require('path');
const globby = require('globby');
const ignoreByDefault = require('ignore-by-default');
const picomatch = require('picomatch');
const slash = require('slash');
const providerManager = require('./provider-manager');
const defaultIgnorePatterns = [...ignoreByDefault.directories(), '**/node_modules'];
const defaultPicomatchIgnorePatterns = [
...defaultIgnorePatterns,
// Unlike globby(), picomatch needs a complete pattern when ignoring directories.
...defaultIgnorePatterns.map(pattern => `${pattern}/**/*`)
];
const defaultMatchNoIgnore = picomatch(defaultPicomatchIgnorePatterns);
const defaultIgnoredByWatcherPatterns = [
'**/*.snap.md', // No need to rerun tests when the Markdown files change.
'ava.config.js', // Config is not reloaded so avoid rerunning tests when it changes.
'ava.config.cjs' // Config is not reloaded so avoid rerunning tests when it changes.
];
const buildExtensionPattern = extensions => extensions.length === 1 ? extensions[0] : `{${extensions.join(',')}}`;
function normalizePattern(pattern) {
// Always use `/` in patterns, harmonizing matching across platforms
if (process.platform === 'win32') {
pattern = slash(pattern);
}
if (pattern.startsWith('./')) {
return pattern.slice(2);
}
if (pattern.startsWith('!./')) {
return `!${pattern.slice(3)}`;
}
return pattern;
}
exports.normalizePattern = normalizePattern;
function normalizePatterns(patterns) {
return patterns.map(pattern => normalizePattern(pattern));
}
exports.normalizePatterns = normalizePatterns;
function normalizeGlobs({extensions, files: filePatterns, ignoredByWatcher: ignoredByWatcherPatterns, providers}) {
if (filePatterns !== undefined && (!Array.isArray(filePatterns) || filePatterns.length === 0)) {
throw new Error('The files configuration must be an array containing glob patterns.');
}
if (ignoredByWatcherPatterns !== undefined && (!Array.isArray(ignoredByWatcherPatterns) || ignoredByWatcherPatterns.length === 0)) {
throw new Error('The ignoredByWatcher configuration must be an array containing glob patterns.');
}
const extensionPattern = buildExtensionPattern(extensions);
const defaultTestPatterns = [
`test.${extensionPattern}`,
`{src,source}/test.${extensionPattern}`,
`**/__tests__/**/*.${extensionPattern}`,
`**/*.spec.${extensionPattern}`,
`**/*.test.${extensionPattern}`,
`**/test-*.${extensionPattern}`,
`**/test/**/*.${extensionPattern}`,
`**/tests/**/*.${extensionPattern}`,
'!**/__tests__/**/__{helper,fixture}?(s)__/**/*',
'!**/test?(s)/**/{helper,fixture}?(s)/**/*'
];
if (filePatterns) {
filePatterns = normalizePatterns(filePatterns);
if (filePatterns.every(pattern => pattern.startsWith('!'))) {
// Use defaults if patterns only contains exclusions.
filePatterns = [...defaultTestPatterns, ...filePatterns];
}
} else {
filePatterns = defaultTestPatterns;
}
if (ignoredByWatcherPatterns) {
ignoredByWatcherPatterns = [...defaultIgnoredByWatcherPatterns, ...normalizePatterns(ignoredByWatcherPatterns)];
} else {
ignoredByWatcherPatterns = [...defaultIgnoredByWatcherPatterns];
}
for (const {level, main} of providers) {
if (level >= providerManager.levels.pathRewrites) {
({filePatterns, ignoredByWatcherPatterns} = main.updateGlobs({filePatterns, ignoredByWatcherPatterns}));
}
}
return {extensions, filePatterns, ignoredByWatcherPatterns};
}
exports.normalizeGlobs = normalizeGlobs;
const hasExtension = (extensions, file) => extensions.includes(path.extname(file).slice(1));
exports.hasExtension = hasExtension;
const globFiles = async (cwd, patterns) => {
const files = await globby(patterns, {
// Globs should work relative to the cwd value only (this should be the
// project directory that AVA is run in).
absolute: false,
braceExpansion: true,
caseSensitiveMatch: false,
cwd,
dot: false,
expandDirectories: false,
extglob: true,
followSymbolicLinks: true,
gitignore: false,
globstar: true,
ignore: defaultIgnorePatterns,
baseNameMatch: false,
onlyFiles: true,
stats: false,
unique: true
});
// Return absolute file paths. This has the side-effect of normalizing paths
// on Windows.
return files.map(file => path.join(cwd, file));
};
async function findFiles({cwd, extensions, filePatterns}) {
return (await globFiles(cwd, filePatterns)).filter(file => hasExtension(extensions, file));
}
exports.findFiles = findFiles;
async function findTests({cwd, extensions, filePatterns}) {
return (await findFiles({cwd, extensions, filePatterns})).filter(file => !path.basename(file).startsWith('_'));
}
exports.findTests = findTests;
function getChokidarIgnorePatterns({ignoredByWatcherPatterns}) {
return [
...defaultIgnorePatterns.map(pattern => `${pattern}/**/*`),
...ignoredByWatcherPatterns.filter(pattern => !pattern.startsWith('!'))
];
}
exports.getChokidarIgnorePatterns = getChokidarIgnorePatterns;
const matchingCache = new WeakMap();
const processMatchingPatterns = input => {
let result = matchingCache.get(input);
if (!result) {
const ignore = [...defaultPicomatchIgnorePatterns];
const patterns = input.filter(pattern => {
if (pattern.startsWith('!')) {
// Unlike globby(), picomatch needs a complete pattern when ignoring directories.
ignore.push(pattern.slice(1), `${pattern.slice(1)}/**/*`);
return false;
}
return true;
});
result = {
match: picomatch(patterns, {ignore}),
matchNoIgnore: picomatch(patterns)
};
matchingCache.set(input, result);
}
return result;
};
function matches(file, patterns) {
const {match} = processMatchingPatterns(patterns);
return match(file);
}
exports.matches = matches;
const matchesIgnorePatterns = (file, patterns) => {
const {matchNoIgnore} = processMatchingPatterns(patterns);
return matchNoIgnore(file) || defaultMatchNoIgnore(file);
};
function normalizeFileForMatching(cwd, file) {
if (process.platform === 'win32') {
cwd = slash(cwd);
file = slash(file);
}
if (!cwd) { // TODO: Ensure tests provide an actual value.
return file;
}
// TODO: If `file` is outside `cwd` we can't normalize it. Need to figure
// out if that's a real-world scenario, but we may have to ensure the file
// isn't even selected.
if (!file.startsWith(cwd)) {
return file;
}
// Assume `cwd` does *not* end in a slash.
return file.slice(cwd.length + 1);
}
exports.normalizeFileForMatching = normalizeFileForMatching;
function isHelperish(file) { // Assume file has been normalized already.
// File names starting with an underscore are deemed "helpers".
if (path.basename(file).startsWith('_')) {
return true;
}
// This function assumes the file has been normalized. If it couldn't be,
// don't check if it's got a parent directory that starts with an underscore.
// Deem it not a "helper".
if (path.isAbsolute(file)) {
return false;
}
// If the file has a parent directory that starts with only a single
// underscore, it's deemed a "helper".
return path.dirname(file).split('/').some(dir => /^_(?:$|[^_])/.test(dir));
}
exports.isHelperish = isHelperish;
function classify(file, {cwd, extensions, filePatterns, ignoredByWatcherPatterns}) {
file = normalizeFileForMatching(cwd, file);
return {
isIgnoredByWatcher: matchesIgnorePatterns(file, ignoredByWatcherPatterns),
isTest: hasExtension(extensions, file) && !isHelperish(file) && filePatterns.length > 0 && matches(file, filePatterns)
};
}
exports.classify = classify;
function applyTestFileFilter({cwd, filter, testFiles}) {
return testFiles.filter(file => matches(normalizeFileForMatching(cwd, file), filter));
}
exports.applyTestFileFilter = applyTestFileFilter;

5
node_modules/ava/lib/is-ci.js generated vendored Normal file
View file

@ -0,0 +1,5 @@
const info = require('ci-info');
const {AVA_FORCE_CI} = process.env;
module.exports = AVA_FORCE_CI === 'not-ci' ? false : AVA_FORCE_CI === 'ci' || info.isCI;

64
node_modules/ava/lib/line-numbers.js generated vendored Normal file
View file

@ -0,0 +1,64 @@
'use strict';
const micromatch = require('micromatch');
const flatten = require('lodash/flatten');
const NUMBER_REGEX = /^\d+$/;
const RANGE_REGEX = /^(?<startGroup>\d+)-(?<endGroup>\d+)$/;
const LINE_NUMBERS_REGEX = /^(?:\d+(?:-\d+)?,?)+$/;
const DELIMITER = ':';
const distinctArray = array => [...new Set(array)];
const sortNumbersAscending = array => {
const sorted = [...array];
sorted.sort((a, b) => a - b);
return sorted;
};
const parseNumber = string => Number.parseInt(string, 10);
const removeAllWhitespace = string => string.replace(/\s/g, '');
const range = (start, end) => new Array(end - start + 1).fill(start).map((element, index) => element + index);
const parseLineNumbers = suffix => sortNumbersAscending(distinctArray(flatten(
suffix.split(',').map(part => {
if (NUMBER_REGEX.test(part)) {
return parseNumber(part);
}
const {groups: {startGroup, endGroup}} = RANGE_REGEX.exec(part);
const start = parseNumber(startGroup);
const end = parseNumber(endGroup);
if (start > end) {
return range(end, start);
}
return range(start, end);
})
)));
function splitPatternAndLineNumbers(pattern) {
const parts = pattern.split(DELIMITER);
if (parts.length === 1) {
return {pattern, lineNumbers: null};
}
const suffix = removeAllWhitespace(parts.pop());
if (!LINE_NUMBERS_REGEX.test(suffix)) {
return {pattern, lineNumbers: null};
}
return {pattern: parts.join(DELIMITER), lineNumbers: parseLineNumbers(suffix)};
}
exports.splitPatternAndLineNumbers = splitPatternAndLineNumbers;
function getApplicableLineNumbers(normalizedFilePath, filter) {
return sortNumbersAscending(distinctArray(flatten(
filter
.filter(({pattern, lineNumbers}) => lineNumbers && micromatch.isMatch(normalizedFilePath, pattern))
.map(({lineNumbers}) => lineNumbers)
)));
}
exports.getApplicableLineNumbers = getApplicableLineNumbers;

160
node_modules/ava/lib/load-config.js generated vendored Normal file
View file

@ -0,0 +1,160 @@
'use strict';
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const isPlainObject = require('is-plain-object');
const pkgConf = require('pkg-conf');
const NO_SUCH_FILE = Symbol('no ava.config.js file');
const MISSING_DEFAULT_EXPORT = Symbol('missing default export');
const EXPERIMENTS = new Set();
// *Very* rudimentary support for loading ava.config.js files containing an `export default` statement.
const evaluateJsConfig = configFile => {
const contents = fs.readFileSync(configFile, 'utf8');
const script = new vm.Script(`'use strict';(()=>{let __export__;\n${contents.replace(/export default/g, '__export__ =')};return __export__;})()`, {
filename: configFile,
lineOffset: -1
});
return {
default: script.runInThisContext()
};
};
const loadJsConfig = ({projectDir, configFile = path.join(projectDir, 'ava.config.js')}) => {
if (!configFile.endsWith('.js')) {
return null;
}
const fileForErrorMessage = path.relative(projectDir, configFile);
let config;
try {
({default: config = MISSING_DEFAULT_EXPORT} = evaluateJsConfig(configFile));
} catch (error) {
if (error.code === 'ENOENT') {
return null;
}
throw Object.assign(new Error(`Error loading ${fileForErrorMessage}: ${error.message}`), {parent: error});
}
if (config === MISSING_DEFAULT_EXPORT) {
throw new Error(`${fileForErrorMessage} must have a default export, using ES module syntax`);
}
return {config, fileForErrorMessage};
};
const loadCjsConfig = ({projectDir, configFile = path.join(projectDir, 'ava.config.cjs')}) => {
if (!configFile.endsWith('.cjs')) {
return null;
}
const fileForErrorMessage = path.relative(projectDir, configFile);
try {
return {config: require(configFile), fileForErrorMessage};
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
return null;
}
throw Object.assign(new Error(`Error loading ${fileForErrorMessage}`), {parent: error});
}
};
const loadMjsConfig = ({projectDir, configFile = path.join(projectDir, 'ava.config.mjs')}) => {
if (!configFile.endsWith('.mjs')) {
return null;
}
const fileForErrorMessage = path.relative(projectDir, configFile);
try {
fs.readFileSync(configFile);
} catch (error) {
if (error.code === 'ENOENT') {
return null;
}
throw Object.assign(new Error(`Error loading ${fileForErrorMessage}`), {parent: error});
}
throw new Error(`AVA cannot yet load ${fileForErrorMessage} files`);
};
function loadConfig({configFile, resolveFrom = process.cwd(), defaults = {}} = {}) { // eslint-disable-line complexity
let packageConf = pkgConf.sync('ava', {cwd: resolveFrom});
const filepath = pkgConf.filepath(packageConf);
const projectDir = filepath === null ? resolveFrom : path.dirname(filepath);
if (configFile) {
configFile = path.resolve(configFile); // Relative to CWD
if (path.basename(configFile) !== path.relative(projectDir, configFile)) {
throw new Error('Config files must be located next to the package.json file');
}
if (!configFile.endsWith('.js') && !configFile.endsWith('.cjs') && !configFile.endsWith('.mjs')) {
throw new Error('Config files must have .js, .cjs or .mjs extensions');
}
}
const allowConflictWithPackageJson = Boolean(configFile);
let [{config: fileConf, fileForErrorMessage} = {config: NO_SUCH_FILE, fileForErrorMessage: undefined}, ...conflicting] = [
loadJsConfig({projectDir, configFile}),
loadCjsConfig({projectDir, configFile}),
loadMjsConfig({projectDir, configFile})
].filter(result => result !== null);
if (conflicting.length > 0) {
throw new Error(`Conflicting configuration in ${fileForErrorMessage} and ${conflicting.map(({fileForErrorMessage}) => fileForErrorMessage).join(' & ')}`);
}
if (fileConf !== NO_SUCH_FILE) {
if (allowConflictWithPackageJson) {
packageConf = {};
} else if (Object.keys(packageConf).length > 0) {
throw new Error(`Conflicting configuration in ${fileForErrorMessage} and package.json`);
}
if (fileConf && typeof fileConf.then === 'function') { // eslint-disable-line promise/prefer-await-to-then
throw new TypeError(`${fileForErrorMessage} must not export a promise`);
}
if (!isPlainObject(fileConf) && typeof fileConf !== 'function') {
throw new TypeError(`${fileForErrorMessage} must export a plain object or factory function`);
}
if (typeof fileConf === 'function') {
fileConf = fileConf({projectDir});
if (fileConf && typeof fileConf.then === 'function') { // eslint-disable-line promise/prefer-await-to-then
throw new TypeError(`Factory method exported by ${fileForErrorMessage} must not return a promise`);
}
if (!isPlainObject(fileConf)) {
throw new TypeError(`Factory method exported by ${fileForErrorMessage} must return a plain object`);
}
}
if ('ava' in fileConf) {
throw new Error(`Encountered ava property in ${fileForErrorMessage}; avoid wrapping the configuration`);
}
}
const config = {...defaults, nonSemVerExperiments: {}, ...fileConf, ...packageConf, projectDir};
const {nonSemVerExperiments: experiments} = config;
if (!isPlainObject(experiments)) {
throw new Error(`nonSemVerExperiments from ${fileForErrorMessage} must be an object`);
}
for (const key of Object.keys(experiments)) {
if (!EXPERIMENTS.has(key)) {
throw new Error(`nonSemVerExperiments.${key} from ${fileForErrorMessage} is not a supported experiment`);
}
}
return config;
}
module.exports = loadConfig;

17
node_modules/ava/lib/node-arguments.js generated vendored Normal file
View file

@ -0,0 +1,17 @@
'use strict';
const arrgv = require('arrgv');
function normalizeNodeArguments(fromConf = [], fromArgv = '') {
let parsedArgv = [];
if (fromArgv !== '') {
try {
parsedArgv = arrgv(fromArgv);
} catch {
throw new Error('Could not parse `--node-arguments` value. Make sure all strings are closed and backslashes are used correctly.');
}
}
return [...process.execArgv, ...fromConf, ...parsedArgv];
}
module.exports = normalizeNodeArguments;

5
node_modules/ava/lib/now-and-timers.js generated vendored Normal file
View file

@ -0,0 +1,5 @@
'use strict';
const timers = require('timers');
Object.assign(exports, timers);
exports.now = Date.now;

15
node_modules/ava/lib/parse-test-args.js generated vendored Normal file
View file

@ -0,0 +1,15 @@
'use strict';
function parseTestArgs(args) {
const rawTitle = typeof args[0] === 'string' ? args.shift() : undefined;
const receivedImplementationArray = Array.isArray(args[0]);
const implementations = receivedImplementationArray ? args.shift() : args.splice(0, 1);
const buildTitle = implementation => {
const title = implementation.title ? implementation.title(rawTitle, ...args) : rawTitle;
return {title, isSet: typeof title !== 'undefined', isValid: typeof title === 'string', isEmpty: !title};
};
return {args, buildTitle, implementations, rawTitle, receivedImplementationArray};
}
module.exports = parseTestArgs;

53
node_modules/ava/lib/provider-manager.js generated vendored Normal file
View file

@ -0,0 +1,53 @@
const pkg = require('../package.json');
const globs = require('./globs');
const levels = {
ava3: 1,
pathRewrites: 2
};
exports.levels = levels;
const levelsByProtocol = {
'ava-3': levels.ava3,
'ava-3.2': levels.pathRewrites
};
function load(providerModule, projectDir) {
const ava = {version: pkg.version};
const makeProvider = require(providerModule);
let fatal;
let level;
const provider = makeProvider({
negotiateProtocol(identifiers, {version}) {
const [identifier] = identifiers.filter(identifier => Reflect.has(levelsByProtocol, identifier));
if (identifier === undefined) {
fatal = new Error(`This version of AVA (${ava.version}) is not compatible with ${providerModule}@${version}`);
return null;
}
level = levelsByProtocol[identifier];
return {
ava,
async findFiles({extensions, patterns}) {
return globs.findFiles({cwd: projectDir, extensions, filePatterns: patterns});
},
identifier,
normalizeGlobPatterns: globs.normalizePatterns,
projectDir
};
}
});
if (fatal) {
throw fatal;
}
return {...provider, level};
}
exports.babel = projectDir => load('@ava/babel', projectDir);
exports.typescript = projectDir => load('@ava/typescript', projectDir);

73
node_modules/ava/lib/reporters/beautify-stack.js generated vendored Normal file
View file

@ -0,0 +1,73 @@
'use strict';
const StackUtils = require('stack-utils');
const stackUtils = new StackUtils({
ignoredPackages: [
'@ava/babel',
'@ava/require-precompiled',
'@ava/typescript',
'append-transform',
'ava',
'empower-core',
'esm',
'nyc'
],
internals: [
// AVA internals, which ignoredPackages don't ignore when we run our own unit tests.
/\/ava\/(?:lib\/|lib\/worker\/)?[\w-]+\.js:\d+:\d+\)?$/,
// Only ignore Node.js internals that really are not useful for debugging.
...StackUtils.nodeInternals().filter(regexp => !/\(internal/.test(regexp.source)),
/\(internal\/process\/task_queues\.js:\d+:\d+\)$/,
/\(internal\/modules\/cjs\/.+?\.js:\d+:\d+\)$/,
/async Promise\.all \(index/,
/new Promise \(<anonymous>\)/
]
});
/*
* Given a string value of the format generated for the `stack` property of a
* V8 error object, return a string that contains only stack frame information
* for frames that have relevance to the consumer.
*
* For example, given the following string value:
*
* ```
* Error
* at inner (/home/ava/ex.js:7:12)
* at /home/ava/ex.js:12:5
* at outer (/home/ava/ex.js:13:4)
* at Object.<anonymous> (/home/ava/ex.js:14:3)
* at Module._compile (module.js:570:32)
* at Object.Module._extensions..js (module.js:579:10)
* at Module.load (module.js:487:32)
* at tryModuleLoad (module.js:446:12)
* at Function.Module._load (module.js:438:3)
* at Module.runMain (module.js:604:10)
* ```
*
* ...this function returns the following string value:
*
* ```
* inner (/home/ava/ex.js:7:12)
* /home/ava/ex.js:12:5
* outer (/home/ava/ex.js:13:4)
* Object.<anonymous> (/home/ava/ex.js:14:3)
* Module._compile (module.js:570:32)
* Object.Module._extensions..js (module.js:579:10)
* Module.load (module.js:487:32)
* tryModuleLoad (module.js:446:12)
* Function.Module._load (module.js:438:3)
* Module.runMain (module.js:604:10)
* ```
*/
module.exports = stack => {
if (!stack) {
return [];
}
return stackUtils.clean(stack)
.trim()
.split('\n')
.map(line => line.trim())
.filter(line => line !== '');
};

17
node_modules/ava/lib/reporters/colors.js generated vendored Normal file
View file

@ -0,0 +1,17 @@
'use strict';
const chalk = require('../chalk').get();
module.exports = {
log: chalk.gray,
title: chalk.bold,
error: chalk.red,
skip: chalk.yellow,
todo: chalk.blue,
pass: chalk.green,
duration: chalk.gray.dim,
errorSource: chalk.gray,
errorStack: chalk.gray,
errorStackInternal: chalk.gray.dim,
stack: chalk.red,
information: chalk.magenta
};

View file

@ -0,0 +1,27 @@
'use strict';
const trimOffNewlines = require('trim-off-newlines');
const chalk = require('../chalk').get();
function formatSerializedError(error) {
const printMessage = error.values.length === 0 ?
Boolean(error.message) :
!error.values[0].label.startsWith(error.message);
if (error.statements.length === 0 && error.values.length === 0) {
return {formatted: null, printMessage};
}
let formatted = '';
for (const value of error.values) {
formatted += `${value.label}\n\n${trimOffNewlines(value.formatted)}\n\n`;
}
for (const statement of error.statements) {
formatted += `${statement[0]}\n${chalk.grey('=>')} ${trimOffNewlines(statement[1])}\n\n`;
}
formatted = trimOffNewlines(formatted);
return {formatted, printMessage};
}
module.exports = formatSerializedError;

View file

@ -0,0 +1,55 @@
'use strict';
const chalk = require('../chalk').get();
const pkg = require('../../package.json');
exports.forError = error => {
if (!error.improperUsage) {
return null;
}
const {assertion} = error;
if (assertion === 'throws' || assertion === 'notThrows') {
return `Try wrapping the first argument to \`t.${assertion}()\` in a function:
${chalk.cyan(`t.${assertion}(() => { `)}${chalk.grey('/* your code here */')}${chalk.cyan(' })')}
Visit the following URL for more details:
${chalk.blue.underline(`https://github.com/avajs/ava/blob/v${pkg.version}/docs/03-assertions.md#throwsfn-expected-message`)}`;
}
if (assertion === 'snapshot') {
const {name, snapPath} = error.improperUsage;
if (name === 'ChecksumError') {
return `The snapshot file is corrupted.
File path: ${chalk.yellow(snapPath)}
Please run AVA again with the ${chalk.cyan('--update-snapshots')} flag to recreate it.`;
}
if (name === 'LegacyError') {
return `The snapshot file was created with AVA 0.19. Its not supported by this AVA version.
File path: ${chalk.yellow(snapPath)}
Please run AVA again with the ${chalk.cyan('--update-snapshots')} flag to upgrade.`;
}
if (name === 'VersionMismatchError') {
const {snapVersion, expectedVersion} = error.improperUsage;
const upgradeMessage = snapVersion < expectedVersion ?
`Please run AVA again with the ${chalk.cyan('--update-snapshots')} flag to upgrade.` :
'You should upgrade AVA.';
return `The snapshot file is v${snapVersion}, but only v${expectedVersion} is supported.
File path: ${chalk.yellow(snapPath)}
${upgradeMessage}`;
}
}
return null;
};

619
node_modules/ava/lib/reporters/mini.js generated vendored Normal file
View file

@ -0,0 +1,619 @@
'use strict';
const os = require('os');
const path = require('path');
const stream = require('stream');
const cliCursor = require('cli-cursor');
const figures = require('figures');
const indentString = require('indent-string');
const ora = require('ora');
const plur = require('plur');
const trimOffNewlines = require('trim-off-newlines');
const beautifyStack = require('./beautify-stack');
const chalk = require('../chalk').get();
const codeExcerpt = require('../code-excerpt');
const colors = require('./colors');
const formatSerializedError = require('./format-serialized-error');
const improperUsageMessages = require('./improper-usage-messages');
const prefixTitle = require('./prefix-title');
const whileCorked = require('./while-corked');
const nodeInternals = require('stack-utils').nodeInternals();
class LineWriter extends stream.Writable {
constructor(dest, spinner) {
super();
this.dest = dest;
this.columns = dest.columns || 80;
this.spinner = spinner;
this.lastSpinnerText = '';
}
_write(chunk, encoding, callback) {
// Discard the current spinner output. Any lines that were meant to be
// preserved should be rewritten.
this.spinner.clear();
this._writeWithSpinner(chunk.toString('utf8'));
callback();
}
_writev(pieces, callback) {
// Discard the current spinner output. Any lines that were meant to be
// preserved should be rewritten.
this.spinner.clear();
const last = pieces.pop();
for (const piece of pieces) {
this.dest.write(piece.chunk);
}
this._writeWithSpinner(last.chunk.toString('utf8'));
callback();
}
_writeWithSpinner(string) {
if (!this.spinner.id) {
this.dest.write(string);
return;
}
this.lastSpinnerText = string;
// Ignore whitespace at the end of the chunk. We're continiously rewriting
// the last line through the spinner. Also be careful to remove the indent
// as the spinner adds its own.
this.spinner.text = string.trimEnd().slice(2);
this.spinner.render();
}
writeLine(string) {
if (string) {
this.write(indentString(string, 2) + os.EOL);
} else {
this.write(os.EOL);
}
}
}
class MiniReporter {
constructor(options) {
this.reportStream = options.reportStream;
this.stdStream = options.stdStream;
this.watching = options.watching;
this.spinner = ora({
isEnabled: true,
color: options.spinner ? options.spinner.color : 'gray',
discardStdin: !options.watching,
hideCursor: false,
spinner: options.spinner || (process.platform === 'win32' ? 'line' : 'dots'),
stream: options.reportStream
});
this.lineWriter = new LineWriter(this.reportStream, this.spinner);
this.consumeStateChange = whileCorked(this.reportStream, whileCorked(this.lineWriter, this.consumeStateChange));
this.endRun = whileCorked(this.reportStream, whileCorked(this.lineWriter, this.endRun));
this.relativeFile = file => path.relative(options.projectDir, file);
this.reset();
}
reset() {
if (this.removePreviousListener) {
this.removePreviousListener();
}
this.failFastEnabled = false;
this.failures = [];
this.filesWithMissingAvaImports = new Set();
this.filesWithoutDeclaredTests = new Set();
this.filesWithoutMatchedLineNumbers = new Set();
this.internalErrors = [];
this.knownFailures = [];
this.lineNumberErrors = [];
this.matching = false;
this.prefixTitle = (testFile, title) => title;
this.previousFailures = 0;
this.removePreviousListener = null;
this.stats = null;
this.uncaughtExceptions = [];
this.unhandledRejections = [];
}
startRun(plan) {
if (plan.bailWithoutReporting) {
return;
}
this.reset();
this.failFastEnabled = plan.failFastEnabled;
this.matching = plan.matching;
this.previousFailures = plan.previousFailures;
if (this.watching || plan.files.length > 1) {
this.prefixTitle = (testFile, title) => prefixTitle(plan.filePathPrefix, testFile, title);
}
this.removePreviousListener = plan.status.on('stateChange', evt => this.consumeStateChange(evt));
if (this.watching && plan.runVector > 1) {
this.reportStream.write(chalk.gray.dim('\u2500'.repeat(this.lineWriter.columns)) + os.EOL);
}
cliCursor.hide(this.reportStream);
this.lineWriter.writeLine();
this.spinner.start();
}
consumeStateChange(evt) { // eslint-disable-line complexity
const fileStats = this.stats && evt.testFile ? this.stats.byFile.get(evt.testFile) : null;
switch (evt.type) {
case 'declared-test':
// Ignore
break;
case 'hook-failed':
this.failures.push(evt);
this.writeTestSummary(evt);
break;
case 'internal-error':
this.internalErrors.push(evt);
if (evt.testFile) {
this.writeWithCounts(colors.error(`${figures.cross} Internal error when running ${this.relativeFile(evt.testFile)}`));
} else {
this.writeWithCounts(colors.error(`${figures.cross} Internal error`));
}
break;
case 'line-number-selection-error':
this.lineNumberErrors.push(evt);
this.writeWithCounts(colors.information(`${figures.warning} Could not parse ${this.relativeFile(evt.testFile)} for line number selection`));
break;
case 'missing-ava-import':
this.filesWithMissingAvaImports.add(evt.testFile);
this.writeWithCounts(colors.error(`${figures.cross} No tests found in ${this.relativeFile(evt.testFile)}, make sure to import "ava" at the top of your test file`));
break;
case 'selected-test':
// Ignore
break;
case 'stats':
this.stats = evt.stats;
break;
case 'test-failed':
this.failures.push(evt);
this.writeTestSummary(evt);
break;
case 'test-passed':
if (evt.knownFailing) {
this.knownFailures.push(evt);
}
this.writeTestSummary(evt);
break;
case 'timeout':
this.lineWriter.writeLine(colors.error(`\n${figures.cross} Timed out while running tests`));
this.lineWriter.writeLine('');
this.writePendingTests(evt);
break;
case 'interrupt':
this.lineWriter.writeLine(colors.error(`\n${figures.cross} Exiting due to SIGINT`));
this.lineWriter.writeLine('');
this.writePendingTests(evt);
break;
case 'uncaught-exception':
this.uncaughtExceptions.push(evt);
break;
case 'unhandled-rejection':
this.unhandledRejections.push(evt);
break;
case 'worker-failed':
if (fileStats.declaredTests === 0) {
this.filesWithoutDeclaredTests.add(evt.testFile);
}
break;
case 'worker-finished':
if (fileStats.declaredTests === 0) {
this.filesWithoutDeclaredTests.add(evt.testFile);
this.writeWithCounts(colors.error(`${figures.cross} No tests found in ${this.relativeFile(evt.testFile)}`));
} else if (fileStats.selectingLines && fileStats.selectedTests === 0) {
this.filesWithoutMatchedLineNumbers.add(evt.testFile);
this.writeWithCounts(colors.error(`${figures.cross} Line numbers for ${this.relativeFile(evt.testFile)} did not match any tests`));
}
break;
case 'worker-stderr':
case 'worker-stdout':
// Forcibly clear the spinner, writing the chunk corrupts the TTY.
this.spinner.clear();
this.stdStream.write(evt.chunk);
// If the chunk does not end with a linebreak, *forcibly* write one to
// ensure it remains visible in the TTY.
// Tests cannot assume their standard output is not interrupted. Indeed
// we multiplex stdout and stderr into a single stream. However as
// long as stdStream is different from reportStream users can read
// their original output by redirecting the streams.
if (evt.chunk[evt.chunk.length - 1] !== 0x0A) {
// Use write() rather than writeLine() so the (presumably corked)
// line writer will actually write the empty line before re-rendering
// the last spinner text below.
this.lineWriter.write(os.EOL);
}
this.lineWriter.write(this.lineWriter.lastSpinnerText);
break;
default:
break;
}
}
writeWithCounts(string) {
if (!this.stats) {
return this.lineWriter.writeLine(string);
}
string = string || '';
if (string !== '') {
string += os.EOL;
}
let firstLinePostfix = this.watching ?
' ' + chalk.gray.dim('[' + new Date().toLocaleTimeString('en-US', {hour12: false}) + ']') :
'';
if (this.stats.passedTests > 0) {
string += os.EOL + colors.pass(`${this.stats.passedTests} passed`) + firstLinePostfix;
firstLinePostfix = '';
}
if (this.stats.passedKnownFailingTests > 0) {
string += os.EOL + colors.error(`${this.stats.passedKnownFailingTests} ${plur('known failure', this.stats.passedKnownFailingTests)}`);
}
if (this.stats.failedHooks > 0) {
string += os.EOL + colors.error(`${this.stats.failedHooks} ${plur('hook', this.stats.failedHooks)} failed`) + firstLinePostfix;
firstLinePostfix = '';
}
if (this.stats.failedTests > 0) {
string += os.EOL + colors.error(`${this.stats.failedTests} ${plur('test', this.stats.failedTests)} failed`) + firstLinePostfix;
firstLinePostfix = '';
}
if (this.stats.skippedTests > 0) {
string += os.EOL + colors.skip(`${this.stats.skippedTests} skipped`);
}
if (this.stats.todoTests > 0) {
string += os.EOL + colors.todo(`${this.stats.todoTests} todo`);
}
this.lineWriter.writeLine(string);
}
writeErr(evt) {
if (evt.err.name === 'TSError' && evt.err.object && evt.err.object.diagnosticText) {
this.lineWriter.writeLine(colors.errorStack(trimOffNewlines(evt.err.object.diagnosticText)));
return;
}
if (evt.err.source) {
this.lineWriter.writeLine(colors.errorSource(`${this.relativeFile(evt.err.source.file)}:${evt.err.source.line}`));
const excerpt = codeExcerpt(evt.err.source, {maxWidth: this.lineWriter.columns - 2});
if (excerpt) {
this.lineWriter.writeLine();
this.lineWriter.writeLine(excerpt);
}
}
if (evt.err.avaAssertionError) {
const result = formatSerializedError(evt.err);
if (result.printMessage) {
this.lineWriter.writeLine();
this.lineWriter.writeLine(evt.err.message);
}
if (result.formatted) {
this.lineWriter.writeLine();
this.lineWriter.writeLine(result.formatted);
}
const message = improperUsageMessages.forError(evt.err);
if (message) {
this.lineWriter.writeLine();
this.lineWriter.writeLine(message);
}
} else if (evt.err.nonErrorObject) {
this.lineWriter.writeLine(trimOffNewlines(evt.err.formatted));
} else {
this.lineWriter.writeLine();
this.lineWriter.writeLine(evt.err.summary);
}
const formatted = this.formatErrorStack(evt.err);
if (formatted.length > 0) {
this.lineWriter.writeLine();
this.lineWriter.writeLine(formatted.join('\n'));
}
}
formatErrorStack(error) {
if (!error.stack) {
return [];
}
if (error.shouldBeautifyStack) {
return beautifyStack(error.stack).map(line => {
if (nodeInternals.some(internal => internal.test(line))) {
return colors.errorStackInternal(`${figures.pointerSmall} ${line}`);
}
return colors.errorStack(`${figures.pointerSmall} ${line}`);
});
}
return [error.stack];
}
writeLogs(evt) {
if (evt.logs) {
for (const log of evt.logs) {
const logLines = indentString(colors.log(log), 4);
const logLinesWithLeadingFigure = logLines.replace(
/^ {4}/,
` ${colors.information(figures.info)} `
);
this.lineWriter.writeLine(logLinesWithLeadingFigure);
}
}
}
writeTestSummary(evt) {
if (evt.type === 'hook-failed' || evt.type === 'test-failed') {
this.writeWithCounts(`${this.prefixTitle(evt.testFile, evt.title)}`);
} else if (evt.knownFailing) {
this.writeWithCounts(`${colors.error(this.prefixTitle(evt.testFile, evt.title))}`);
} else {
this.writeWithCounts(`${this.prefixTitle(evt.testFile, evt.title)}`);
}
}
writeFailure(evt) {
this.lineWriter.writeLine(`${colors.title(this.prefixTitle(evt.testFile, evt.title))}`);
this.writeLogs(evt);
this.lineWriter.writeLine();
this.writeErr(evt);
}
writePendingTests(evt) {
for (const [file, testsInFile] of evt.pendingTests) {
if (testsInFile.size === 0) {
continue;
}
this.lineWriter.writeLine(`${testsInFile.size} tests were pending in ${this.relativeFile(file)}\n`);
for (const title of testsInFile) {
this.lineWriter.writeLine(`${figures.circleDotted} ${this.prefixTitle(file, title)}`);
}
this.lineWriter.writeLine('');
}
}
endRun() { // eslint-disable-line complexity
this.spinner.stop();
cliCursor.show(this.reportStream);
if (!this.stats) {
this.lineWriter.writeLine(colors.error(`${figures.cross} Couldnt find any files to test`));
this.lineWriter.writeLine();
return;
}
if (this.matching && this.stats.selectedTests === 0) {
this.lineWriter.writeLine(colors.error(`${figures.cross} Couldnt find any matching tests`));
this.lineWriter.writeLine();
return;
}
this.lineWriter.writeLine();
let firstLinePostfix = this.watching ?
' ' + chalk.gray.dim('[' + new Date().toLocaleTimeString('en-US', {hour12: false}) + ']') :
'';
if (this.filesWithMissingAvaImports.size > 0) {
for (const testFile of this.filesWithMissingAvaImports) {
this.lineWriter.writeLine(colors.error(`${figures.cross} No tests found in ${this.relativeFile(testFile)}, make sure to import "ava" at the top of your test file`) + firstLinePostfix);
firstLinePostfix = '';
}
}
if (this.filesWithoutDeclaredTests.size > 0) {
for (const testFile of this.filesWithoutDeclaredTests) {
if (!this.filesWithMissingAvaImports.has(testFile)) {
this.lineWriter.writeLine(colors.error(`${figures.cross} No tests found in ${this.relativeFile(testFile)}`) + firstLinePostfix);
firstLinePostfix = '';
}
}
}
if (this.lineNumberErrors.length > 0) {
for (const evt of this.lineNumberErrors) {
this.lineWriter.writeLine(colors.information(`${figures.warning} Could not parse ${this.relativeFile(evt.testFile)} for line number selection`));
}
}
if (this.filesWithoutMatchedLineNumbers.size > 0) {
for (const testFile of this.filesWithoutMatchedLineNumbers) {
if (!this.filesWithMissingAvaImports.has(testFile) && !this.filesWithoutDeclaredTests.has(testFile)) {
this.lineWriter.writeLine(colors.error(`${figures.cross} Line numbers for ${this.relativeFile(testFile)} did not match any tests`) + firstLinePostfix);
firstLinePostfix = '';
}
}
}
if (this.filesWithMissingAvaImports.size > 0 || this.filesWithoutDeclaredTests.size > 0 || this.filesWithoutMatchedLineNumbers.size > 0) {
this.lineWriter.writeLine();
}
if (this.stats.failedHooks > 0) {
this.lineWriter.writeLine(colors.error(`${this.stats.failedHooks} ${plur('hook', this.stats.failedHooks)} failed`) + firstLinePostfix);
firstLinePostfix = '';
}
if (this.stats.failedTests > 0) {
this.lineWriter.writeLine(colors.error(`${this.stats.failedTests} ${plur('test', this.stats.failedTests)} failed`) + firstLinePostfix);
firstLinePostfix = '';
}
if (this.stats.failedHooks === 0 && this.stats.failedTests === 0 && this.stats.passedTests > 0) {
this.lineWriter.writeLine(colors.pass(`${this.stats.passedTests} ${plur('test', this.stats.passedTests)} passed`) + firstLinePostfix);
firstLinePostfix = '';
}
if (this.stats.passedKnownFailingTests > 0) {
this.lineWriter.writeLine(colors.error(`${this.stats.passedKnownFailingTests} ${plur('known failure', this.stats.passedKnownFailingTests)}`));
}
if (this.stats.skippedTests > 0) {
this.lineWriter.writeLine(colors.skip(`${this.stats.skippedTests} ${plur('test', this.stats.skippedTests)} skipped`));
}
if (this.stats.todoTests > 0) {
this.lineWriter.writeLine(colors.todo(`${this.stats.todoTests} ${plur('test', this.stats.todoTests)} todo`));
}
if (this.stats.unhandledRejections > 0) {
this.lineWriter.writeLine(colors.error(`${this.stats.unhandledRejections} unhandled ${plur('rejection', this.stats.unhandledRejections)}`));
}
if (this.stats.uncaughtExceptions > 0) {
this.lineWriter.writeLine(colors.error(`${this.stats.uncaughtExceptions} uncaught ${plur('exception', this.stats.uncaughtExceptions)}`));
}
if (this.previousFailures > 0) {
this.lineWriter.writeLine(colors.error(`${this.previousFailures} previous ${plur('failure', this.previousFailures)} in test files that were not rerun`));
}
if (this.stats.passedKnownFailingTests > 0) {
this.lineWriter.writeLine();
for (const evt of this.knownFailures) {
this.lineWriter.writeLine(colors.error(this.prefixTitle(evt.testFile, evt.title)));
}
}
const shouldWriteFailFastDisclaimer = this.failFastEnabled && (this.stats.remainingTests > 0 || this.stats.files > this.stats.finishedWorkers);
if (this.failures.length > 0) {
const writeTrailingLines = shouldWriteFailFastDisclaimer || this.internalErrors.length > 0 || this.uncaughtExceptions.length > 0 || this.unhandledRejections.length > 0;
this.lineWriter.writeLine();
const last = this.failures[this.failures.length - 1];
for (const evt of this.failures) {
this.writeFailure(evt);
if (evt !== last || writeTrailingLines) {
this.lineWriter.writeLine();
this.lineWriter.writeLine();
this.lineWriter.writeLine();
}
}
}
if (this.internalErrors.length > 0) {
const writeLeadingLine = this.failures.length === 0;
const writeTrailingLines = shouldWriteFailFastDisclaimer || this.uncaughtExceptions.length > 0 || this.unhandledRejections.length > 0;
if (writeLeadingLine) {
this.lineWriter.writeLine();
}
const last = this.internalErrors[this.internalErrors.length - 1];
for (const evt of this.internalErrors) {
if (evt.testFile) {
this.lineWriter.writeLine(colors.error(`${figures.cross} Internal error when running ${this.relativeFile(evt.testFile)}`));
} else {
this.lineWriter.writeLine(colors.error(`${figures.cross} Internal error`));
}
this.lineWriter.writeLine(colors.stack(evt.err.summary));
this.lineWriter.writeLine(colors.errorStack(evt.err.stack));
if (evt !== last || writeTrailingLines) {
this.lineWriter.writeLine();
this.lineWriter.writeLine();
this.lineWriter.writeLine();
}
}
}
if (this.uncaughtExceptions.length > 0) {
const writeLeadingLine = this.failures.length === 0 && this.internalErrors.length === 0;
const writeTrailingLines = shouldWriteFailFastDisclaimer || this.unhandledRejections.length > 0;
if (writeLeadingLine) {
this.lineWriter.writeLine();
}
const last = this.uncaughtExceptions[this.uncaughtExceptions.length - 1];
for (const evt of this.uncaughtExceptions) {
this.lineWriter.writeLine(colors.title(`Uncaught exception in ${this.relativeFile(evt.testFile)}`));
this.lineWriter.writeLine();
this.writeErr(evt);
if (evt !== last || writeTrailingLines) {
this.lineWriter.writeLine();
this.lineWriter.writeLine();
this.lineWriter.writeLine();
}
}
}
if (this.unhandledRejections.length > 0) {
const writeLeadingLine = this.failures.length === 0 && this.internalErrors.length === 0 && this.uncaughtExceptions.length === 0;
const writeTrailingLines = shouldWriteFailFastDisclaimer;
if (writeLeadingLine) {
this.lineWriter.writeLine();
}
const last = this.unhandledRejections[this.unhandledRejections.length - 1];
for (const evt of this.unhandledRejections) {
this.lineWriter.writeLine(colors.title(`Unhandled rejection in ${this.relativeFile(evt.testFile)}`));
this.lineWriter.writeLine();
this.writeErr(evt);
if (evt !== last || writeTrailingLines) {
this.lineWriter.writeLine();
this.lineWriter.writeLine();
this.lineWriter.writeLine();
}
}
}
if (shouldWriteFailFastDisclaimer) {
let remaining = '';
if (this.stats.remainingTests > 0) {
remaining += `At least ${this.stats.remainingTests} ${plur('test was', 'tests were', this.stats.remainingTests)} skipped`;
if (this.stats.files > this.stats.finishedWorkers) {
remaining += ', as well as ';
}
}
if (this.stats.files > this.stats.finishedWorkers) {
const skippedFileCount = this.stats.files - this.stats.finishedWorkers;
remaining += `${skippedFileCount} ${plur('test file', 'test files', skippedFileCount)}`;
if (this.stats.remainingTests === 0) {
remaining += ` ${plur('was', 'were', skippedFileCount)} skipped`;
}
}
this.lineWriter.writeLine(colors.information(`\`--fail-fast\` is on. ${remaining}.`));
}
this.lineWriter.writeLine();
}
}
module.exports = MiniReporter;

21
node_modules/ava/lib/reporters/prefix-title.js generated vendored Normal file
View file

@ -0,0 +1,21 @@
'use strict';
const path = require('path');
const figures = require('figures');
const chalk = require('../chalk').get();
const SEPERATOR = ' ' + chalk.gray.dim(figures.pointerSmall) + ' ';
module.exports = (base, file, title) => {
const prefix = file
// Only replace base if it is found at the start of the path
.replace(base, (match, offset) => offset === 0 ? '' : match)
.replace(/\.spec/, '')
.replace(/\.test/, '')
.replace(/test-/g, '')
.replace(/\.js$/, '')
.split(path.sep)
.filter(p => p !== '__tests__')
.join(SEPERATOR);
return prefix + SEPERATOR + title;
};

209
node_modules/ava/lib/reporters/tap.js generated vendored Normal file
View file

@ -0,0 +1,209 @@
'use strict';
const os = require('os');
const path = require('path');
const plur = require('plur');
const stripAnsi = require('strip-ansi');
const supertap = require('supertap');
const indentString = require('indent-string');
const beautifyStack = require('./beautify-stack');
const prefixTitle = require('./prefix-title');
function dumpError(error) {
const object = {...error.object};
if (error.name) {
object.name = error.name;
}
if (error.message) {
object.message = error.message;
}
if (error.avaAssertionError) {
if (error.assertion) {
object.assertion = error.assertion;
}
if (error.operator) {
object.operator = error.operator;
}
if (error.values.length > 0) {
object.values = error.values.reduce((acc, value) => {
acc[value.label] = stripAnsi(value.formatted);
return acc;
}, {});
}
}
if (error.nonErrorObject) {
object.message = 'Non-error object';
object.formatted = stripAnsi(error.formatted);
}
if (error.stack) {
object.at = error.shouldBeautifyStack ? beautifyStack(error.stack).join('\n') : error.stack;
}
return object;
}
class TapReporter {
constructor(options) {
this.i = 0;
this.stdStream = options.stdStream;
this.reportStream = options.reportStream;
this.crashCount = 0;
this.filesWithMissingAvaImports = new Set();
this.prefixTitle = (testFile, title) => title;
this.relativeFile = file => path.relative(options.projectDir, file);
this.stats = null;
}
startRun(plan) {
if (plan.files.length > 1) {
this.prefixTitle = (testFile, title) => prefixTitle(plan.filePathPrefix, testFile, title);
}
plan.status.on('stateChange', evt => this.consumeStateChange(evt));
this.reportStream.write(supertap.start() + os.EOL);
}
endRun() {
if (this.stats) {
this.reportStream.write(supertap.finish({
crashed: this.crashCount,
failed: this.stats.failedTests + this.stats.remainingTests,
passed: this.stats.passedTests + this.stats.passedKnownFailingTests,
skipped: this.stats.skippedTests,
todo: this.stats.todoTests
}) + os.EOL);
if (this.stats.parallelRuns) {
const {currentFileCount, currentIndex, totalRuns} = this.stats.parallelRuns;
this.reportStream.write(`# Ran ${currentFileCount} test ${plur('file', currentFileCount)} out of ${this.stats.files} for job ${currentIndex + 1} of ${totalRuns}` + os.EOL + os.EOL);
}
} else {
this.reportStream.write(supertap.finish({
crashed: this.crashCount,
failed: 0,
passed: 0,
skipped: 0,
todo: 0
}) + os.EOL);
}
}
writeTest(evt, flags) {
this.reportStream.write(supertap.test(this.prefixTitle(evt.testFile, evt.title), {
comment: evt.logs,
error: evt.err ? dumpError(evt.err) : null,
index: ++this.i,
passed: flags.passed,
skip: flags.skip,
todo: flags.todo
}) + os.EOL);
}
writeCrash(evt, title) {
this.crashCount++;
this.reportStream.write(supertap.test(title || evt.err.summary || evt.type, {
comment: evt.logs,
error: evt.err ? dumpError(evt.err) : null,
index: ++this.i,
passed: false,
skip: false,
todo: false
}) + os.EOL);
}
writeComment(evt, {title = this.prefixTitle(evt.testFile, evt.title)}) {
this.reportStream.write(`# ${stripAnsi(title)}${os.EOL}`);
if (evt.logs) {
for (const log of evt.logs) {
const logLines = indentString(log, 4).replace(/^ {4}/, ' # ');
this.reportStream.write(`${logLines}${os.EOL}`);
}
}
}
consumeStateChange(evt) { // eslint-disable-line complexity
const fileStats = this.stats && evt.testFile ? this.stats.byFile.get(evt.testFile) : null;
switch (evt.type) {
case 'declared-test':
// Ignore
break;
case 'hook-failed':
this.writeTest(evt, {passed: false, todo: false, skip: false});
break;
case 'hook-finished':
this.writeComment(evt, {});
break;
case 'internal-error':
this.writeCrash(evt);
break;
case 'missing-ava-import':
this.filesWithMissingAvaImports.add(evt.testFile);
this.writeCrash(evt, `No tests found in ${this.relativeFile(evt.testFile)}, make sure to import "ava" at the top of your test file`);
break;
case 'selected-test':
if (evt.skip) {
this.writeTest(evt, {passed: true, todo: false, skip: true});
} else if (evt.todo) {
this.writeTest(evt, {passed: false, todo: true, skip: false});
}
break;
case 'stats':
this.stats = evt.stats;
break;
case 'test-failed':
this.writeTest(evt, {passed: false, todo: false, skip: false});
break;
case 'test-passed':
this.writeTest(evt, {passed: true, todo: false, skip: false});
break;
case 'timeout':
this.writeCrash(evt, `Exited because no new tests completed within the last ${evt.period}ms of inactivity`);
break;
case 'uncaught-exception':
this.writeCrash(evt);
break;
case 'unhandled-rejection':
this.writeCrash(evt);
break;
case 'worker-failed':
if (!this.filesWithMissingAvaImports.has(evt.testFile)) {
if (evt.nonZeroExitCode) {
this.writeCrash(evt, `${this.relativeFile(evt.testFile)} exited with a non-zero exit code: ${evt.nonZeroExitCode}`);
} else {
this.writeCrash(evt, `${this.relativeFile(evt.testFile)} exited due to ${evt.signal}`);
}
}
break;
case 'worker-finished':
if (!evt.forcedExit && !this.filesWithMissingAvaImports.has(evt.testFile)) {
if (fileStats.declaredTests === 0) {
this.writeCrash(evt, `No tests found in ${this.relativeFile(evt.testFile)}`);
} else if (!this.failFastEnabled && fileStats.remainingTests > 0) {
this.writeComment(evt, {title: `${fileStats.remainingTests} ${plur('test', fileStats.remainingTests)} remaining in ${this.relativeFile(evt.testFile)}`});
}
}
break;
case 'worker-stderr':
case 'worker-stdout':
this.stdStream.write(evt.chunk);
break;
default:
break;
}
}
}
module.exports = TapReporter;

463
node_modules/ava/lib/reporters/verbose.js generated vendored Normal file
View file

@ -0,0 +1,463 @@
'use strict';
const os = require('os');
const path = require('path');
const stream = require('stream');
const figures = require('figures');
const indentString = require('indent-string');
const plur = require('plur');
const prettyMs = require('pretty-ms');
const trimOffNewlines = require('trim-off-newlines');
const beautifyStack = require('./beautify-stack');
const chalk = require('../chalk').get();
const codeExcerpt = require('../code-excerpt');
const colors = require('./colors');
const formatSerializedError = require('./format-serialized-error');
const improperUsageMessages = require('./improper-usage-messages');
const prefixTitle = require('./prefix-title');
const whileCorked = require('./while-corked');
const nodeInternals = require('stack-utils').nodeInternals();
class LineWriter extends stream.Writable {
constructor(dest) {
super();
this.dest = dest;
this.columns = dest.columns || 80;
this.lastLineIsEmpty = false;
}
_write(chunk, encoding, callback) {
this.dest.write(chunk);
callback();
}
writeLine(string) {
if (string) {
this.write(indentString(string, 2) + os.EOL);
this.lastLineIsEmpty = false;
} else {
this.write(os.EOL);
this.lastLineIsEmpty = true;
}
}
ensureEmptyLine() {
if (!this.lastLineIsEmpty) {
this.writeLine();
}
}
}
class VerboseReporter {
constructor(options) {
this.durationThreshold = options.durationThreshold || 100;
this.reportStream = options.reportStream;
this.stdStream = options.stdStream;
this.watching = options.watching;
this.lineWriter = new LineWriter(this.reportStream);
this.consumeStateChange = whileCorked(this.reportStream, this.consumeStateChange);
this.endRun = whileCorked(this.reportStream, this.endRun);
this.relativeFile = file => path.relative(options.projectDir, file);
this.reset();
}
reset() {
if (this.removePreviousListener) {
this.removePreviousListener();
}
this.failFastEnabled = false;
this.failures = [];
this.filesWithMissingAvaImports = new Set();
this.knownFailures = [];
this.runningTestFiles = new Map();
this.lastLineIsEmpty = false;
this.matching = false;
this.prefixTitle = (testFile, title) => title;
this.previousFailures = 0;
this.removePreviousListener = null;
this.stats = null;
}
startRun(plan) {
if (plan.bailWithoutReporting) {
return;
}
this.reset();
this.failFastEnabled = plan.failFastEnabled;
this.matching = plan.matching;
this.previousFailures = plan.previousFailures;
this.emptyParallelRun = plan.status.emptyParallelRun;
if (this.watching || plan.files.length > 1) {
this.prefixTitle = (testFile, title) => prefixTitle(plan.filePathPrefix, testFile, title);
}
this.removePreviousListener = plan.status.on('stateChange', evt => this.consumeStateChange(evt));
if (this.watching && plan.runVector > 1) {
this.lineWriter.write(chalk.gray.dim('\u2500'.repeat(this.reportStream.columns || 80)) + os.EOL);
}
this.lineWriter.writeLine();
}
consumeStateChange(evt) { // eslint-disable-line complexity
const fileStats = this.stats && evt.testFile ? this.stats.byFile.get(evt.testFile) : null;
switch (evt.type) {
case 'hook-failed':
this.failures.push(evt);
this.writeTestSummary(evt);
break;
case 'internal-error':
if (evt.testFile) {
this.lineWriter.writeLine(colors.error(`${figures.cross} Internal error when running ${this.relativeFile(evt.testFile)}`));
} else {
this.lineWriter.writeLine(colors.error(`${figures.cross} Internal error`));
}
this.lineWriter.writeLine(colors.stack(evt.err.summary));
this.lineWriter.writeLine(colors.errorStack(evt.err.stack));
this.lineWriter.writeLine();
this.lineWriter.writeLine();
break;
case 'line-number-selection-error':
this.lineWriter.writeLine(colors.information(`${figures.warning} Could not parse ${this.relativeFile(evt.testFile)} for line number selection`));
break;
case 'missing-ava-import':
this.filesWithMissingAvaImports.add(evt.testFile);
this.lineWriter.writeLine(colors.error(`${figures.cross} No tests found in ${this.relativeFile(evt.testFile)}, make sure to import "ava" at the top of your test file`));
break;
case 'hook-finished':
if (evt.logs.length > 0) {
this.lineWriter.writeLine(` ${this.prefixTitle(evt.testFile, evt.title)}`);
this.writeLogs(evt);
}
break;
case 'selected-test':
if (evt.skip) {
this.lineWriter.writeLine(colors.skip(`- ${this.prefixTitle(evt.testFile, evt.title)}`));
} else if (evt.todo) {
this.lineWriter.writeLine(colors.todo(`- ${this.prefixTitle(evt.testFile, evt.title)}`));
}
break;
case 'stats':
this.stats = evt.stats;
break;
case 'test-failed':
this.failures.push(evt);
this.writeTestSummary(evt);
break;
case 'test-passed':
if (evt.knownFailing) {
this.knownFailures.push(evt);
}
this.writeTestSummary(evt);
break;
case 'timeout':
this.lineWriter.writeLine(colors.error(`\n${figures.cross} Timed out while running tests`));
this.lineWriter.writeLine('');
this.writePendingTests(evt);
break;
case 'interrupt':
this.lineWriter.writeLine(colors.error(`\n${figures.cross} Exiting due to SIGINT`));
this.lineWriter.writeLine('');
this.writePendingTests(evt);
break;
case 'uncaught-exception':
this.lineWriter.ensureEmptyLine();
this.lineWriter.writeLine(colors.title(`Uncaught exception in ${this.relativeFile(evt.testFile)}`));
this.lineWriter.writeLine();
this.writeErr(evt);
this.lineWriter.writeLine();
break;
case 'unhandled-rejection':
this.lineWriter.ensureEmptyLine();
this.lineWriter.writeLine(colors.title(`Unhandled rejection in ${this.relativeFile(evt.testFile)}`));
this.lineWriter.writeLine();
this.writeErr(evt);
this.lineWriter.writeLine();
break;
case 'worker-failed':
if (!this.filesWithMissingAvaImports.has(evt.testFile)) {
if (evt.nonZeroExitCode) {
this.lineWriter.writeLine(colors.error(`${figures.cross} ${this.relativeFile(evt.testFile)} exited with a non-zero exit code: ${evt.nonZeroExitCode}`));
} else {
this.lineWriter.writeLine(colors.error(`${figures.cross} ${this.relativeFile(evt.testFile)} exited due to ${evt.signal}`));
}
}
break;
case 'worker-finished':
if (!evt.forcedExit && !this.filesWithMissingAvaImports.has(evt.testFile)) {
if (fileStats.declaredTests === 0) {
this.lineWriter.writeLine(colors.error(`${figures.cross} No tests found in ${this.relativeFile(evt.testFile)}`));
} else if (fileStats.selectingLines && fileStats.selectedTests === 0) {
this.lineWriter.writeLine(colors.error(`${figures.cross} Line numbers for ${this.relativeFile(evt.testFile)} did not match any tests`));
} else if (!this.failFastEnabled && fileStats.remainingTests > 0) {
this.lineWriter.writeLine(colors.error(`${figures.cross} ${fileStats.remainingTests} ${plur('test', fileStats.remainingTests)} remaining in ${this.relativeFile(evt.testFile)}`));
}
}
break;
case 'worker-stderr':
case 'worker-stdout':
this.stdStream.write(evt.chunk);
// If the chunk does not end with a linebreak, *forcibly* write one to
// ensure it remains visible in the TTY.
// Tests cannot assume their standard output is not interrupted. Indeed
// we multiplex stdout and stderr into a single stream. However as
// long as stdStream is different from reportStream users can read
// their original output by redirecting the streams.
if (evt.chunk[evt.chunk.length - 1] !== 0x0A) {
this.reportStream.write(os.EOL);
}
break;
default:
break;
}
}
writeErr(evt) {
if (evt.err.name === 'TSError' && evt.err.object && evt.err.object.diagnosticText) {
this.lineWriter.writeLine(colors.errorStack(trimOffNewlines(evt.err.object.diagnosticText)));
return;
}
if (evt.err.source) {
this.lineWriter.writeLine(colors.errorSource(`${this.relativeFile(evt.err.source.file)}:${evt.err.source.line}`));
const excerpt = codeExcerpt(evt.err.source, {maxWidth: this.reportStream.columns - 2});
if (excerpt) {
this.lineWriter.writeLine();
this.lineWriter.writeLine(excerpt);
}
}
if (evt.err.avaAssertionError) {
const result = formatSerializedError(evt.err);
if (result.printMessage) {
this.lineWriter.writeLine();
this.lineWriter.writeLine(evt.err.message);
}
if (result.formatted) {
this.lineWriter.writeLine();
this.lineWriter.writeLine(result.formatted);
}
const message = improperUsageMessages.forError(evt.err);
if (message) {
this.lineWriter.writeLine();
this.lineWriter.writeLine(message);
}
} else if (evt.err.nonErrorObject) {
this.lineWriter.writeLine(trimOffNewlines(evt.err.formatted));
} else {
this.lineWriter.writeLine();
this.lineWriter.writeLine(evt.err.summary);
}
const formatted = this.formatErrorStack(evt.err);
if (formatted.length > 0) {
this.lineWriter.writeLine();
this.lineWriter.writeLine(formatted.join('\n'));
}
}
formatErrorStack(error) {
if (!error.stack) {
return [];
}
if (error.shouldBeautifyStack) {
return beautifyStack(error.stack).map(line => {
if (nodeInternals.some(internal => internal.test(line))) {
return colors.errorStackInternal(`${figures.pointerSmall} ${line}`);
}
return colors.errorStack(`${figures.pointerSmall} ${line}`);
});
}
return [error.stack];
}
writePendingTests(evt) {
for (const [file, testsInFile] of evt.pendingTests) {
if (testsInFile.size === 0) {
continue;
}
this.lineWriter.writeLine(`${testsInFile.size} tests were pending in ${this.relativeFile(file)}\n`);
for (const title of testsInFile) {
this.lineWriter.writeLine(`${figures.circleDotted} ${this.prefixTitle(file, title)}`);
}
this.lineWriter.writeLine('');
}
}
writeLogs(evt) {
if (evt.logs) {
for (const log of evt.logs) {
const logLines = indentString(colors.log(log), 4);
const logLinesWithLeadingFigure = logLines.replace(
/^ {4}/,
` ${colors.information(figures.info)} `
);
this.lineWriter.writeLine(logLinesWithLeadingFigure);
}
}
}
writeTestSummary(evt) {
if (evt.type === 'hook-failed' || evt.type === 'test-failed') {
this.lineWriter.writeLine(`${colors.error(figures.cross)} ${this.prefixTitle(evt.testFile, evt.title)} ${colors.error(evt.err.message)}`);
} else if (evt.knownFailing) {
this.lineWriter.writeLine(`${colors.error(figures.tick)} ${colors.error(this.prefixTitle(evt.testFile, evt.title))}`);
} else {
const duration = evt.duration > this.durationThreshold ? colors.duration(' (' + prettyMs(evt.duration) + ')') : '';
this.lineWriter.writeLine(`${colors.pass(figures.tick)} ${this.prefixTitle(evt.testFile, evt.title)}${duration}`);
}
this.writeLogs(evt);
}
writeFailure(evt) {
this.lineWriter.writeLine(`${colors.title(this.prefixTitle(evt.testFile, evt.title))}`);
this.writeLogs(evt);
this.lineWriter.writeLine();
this.writeErr(evt);
}
endRun() { // eslint-disable-line complexity
if (this.emptyParallelRun) {
this.lineWriter.writeLine('No files tested in this parallel run');
this.lineWriter.writeLine();
return;
}
if (!this.stats) {
this.lineWriter.writeLine(colors.error(`${figures.cross} Couldnt find any files to test`));
this.lineWriter.writeLine();
return;
}
if (this.matching && this.stats.selectedTests === 0) {
this.lineWriter.writeLine(colors.error(`${figures.cross} Couldnt find any matching tests`));
this.lineWriter.writeLine();
return;
}
this.lineWriter.writeLine();
if (this.stats.parallelRuns) {
const {currentFileCount, currentIndex, totalRuns} = this.stats.parallelRuns;
this.lineWriter.writeLine(colors.information(`Ran ${currentFileCount} test ${plur('file', currentFileCount)} out of ${this.stats.files} for job ${currentIndex + 1} of ${totalRuns}`));
this.lineWriter.writeLine();
}
let firstLinePostfix = this.watching ?
' ' + chalk.gray.dim('[' + new Date().toLocaleTimeString('en-US', {hour12: false}) + ']') :
'';
if (this.stats.failedHooks > 0) {
this.lineWriter.writeLine(colors.error(`${this.stats.failedHooks} ${plur('hook', this.stats.failedHooks)} failed`) + firstLinePostfix);
firstLinePostfix = '';
}
if (this.stats.failedTests > 0) {
this.lineWriter.writeLine(colors.error(`${this.stats.failedTests} ${plur('test', this.stats.failedTests)} failed`) + firstLinePostfix);
firstLinePostfix = '';
}
if (this.stats.failedHooks === 0 && this.stats.failedTests === 0 && this.stats.passedTests > 0) {
this.lineWriter.writeLine(colors.pass(`${this.stats.passedTests} ${plur('test', this.stats.passedTests)} passed`) + firstLinePostfix);
firstLinePostfix = '';
}
if (this.stats.passedKnownFailingTests > 0) {
this.lineWriter.writeLine(colors.error(`${this.stats.passedKnownFailingTests} ${plur('known failure', this.stats.passedKnownFailingTests)}`));
}
if (this.stats.skippedTests > 0) {
this.lineWriter.writeLine(colors.skip(`${this.stats.skippedTests} ${plur('test', this.stats.skippedTests)} skipped`));
}
if (this.stats.todoTests > 0) {
this.lineWriter.writeLine(colors.todo(`${this.stats.todoTests} ${plur('test', this.stats.todoTests)} todo`));
}
if (this.stats.unhandledRejections > 0) {
this.lineWriter.writeLine(colors.error(`${this.stats.unhandledRejections} unhandled ${plur('rejection', this.stats.unhandledRejections)}`));
}
if (this.stats.uncaughtExceptions > 0) {
this.lineWriter.writeLine(colors.error(`${this.stats.uncaughtExceptions} uncaught ${plur('exception', this.stats.uncaughtExceptions)}`));
}
if (this.previousFailures > 0) {
this.lineWriter.writeLine(colors.error(`${this.previousFailures} previous ${plur('failure', this.previousFailures)} in test files that were not rerun`));
}
if (this.stats.passedKnownFailingTests > 0) {
this.lineWriter.writeLine();
for (const evt of this.knownFailures) {
this.lineWriter.writeLine(colors.error(this.prefixTitle(evt.testFile, evt.title)));
}
}
const shouldWriteFailFastDisclaimer = this.failFastEnabled && (this.stats.remainingTests > 0 || this.stats.files > this.stats.finishedWorkers);
if (this.failures.length > 0) {
this.lineWriter.writeLine();
const lastFailure = this.failures[this.failures.length - 1];
for (const evt of this.failures) {
this.writeFailure(evt);
if (evt !== lastFailure || shouldWriteFailFastDisclaimer) {
this.lineWriter.writeLine();
this.lineWriter.writeLine();
this.lineWriter.writeLine();
}
}
}
if (shouldWriteFailFastDisclaimer) {
let remaining = '';
if (this.stats.remainingTests > 0) {
remaining += `At least ${this.stats.remainingTests} ${plur('test was', 'tests were', this.stats.remainingTests)} skipped`;
if (this.stats.files > this.stats.finishedWorkers) {
remaining += ', as well as ';
}
}
if (this.stats.files > this.stats.finishedWorkers) {
const skippedFileCount = this.stats.files - this.stats.finishedWorkers;
remaining += `${skippedFileCount} ${plur('test file', 'test files', skippedFileCount)}`;
if (this.stats.remainingTests === 0) {
remaining += ` ${plur('was', 'were', skippedFileCount)} skipped`;
}
}
this.lineWriter.writeLine(colors.information(`\`--fail-fast\` is on. ${remaining}.`));
}
this.lineWriter.writeLine();
}
}
module.exports = VerboseReporter;

13
node_modules/ava/lib/reporters/while-corked.js generated vendored Normal file
View file

@ -0,0 +1,13 @@
'use strict';
function whileCorked(stream, fn) {
return function (...args) {
stream.cork();
try {
fn.apply(this, args);
} finally {
stream.uncork();
}
};
}
module.exports = whileCorked;

194
node_modules/ava/lib/run-status.js generated vendored Normal file
View file

@ -0,0 +1,194 @@
'use strict';
const Emittery = require('emittery');
const cloneDeep = require('lodash/cloneDeep');
class RunStatus extends Emittery {
constructor(files, parallelRuns) {
super();
this.pendingTests = new Map();
this.emptyParallelRun = parallelRuns &&
parallelRuns.currentFileCount === 0 &&
parallelRuns.totalRuns > 1 &&
files > 0;
this.stats = {
byFile: new Map(),
declaredTests: 0,
failedHooks: 0,
failedTests: 0,
failedWorkers: 0,
files,
parallelRuns,
finishedWorkers: 0,
internalErrors: 0,
remainingTests: 0,
passedKnownFailingTests: 0,
passedTests: 0,
selectedTests: 0,
skippedTests: 0,
timeouts: 0,
todoTests: 0,
uncaughtExceptions: 0,
unhandledRejections: 0
};
}
observeWorker(worker, testFile, stats) {
this.stats.byFile.set(testFile, {
declaredTests: 0,
failedHooks: 0,
failedTests: 0,
internalErrors: 0,
remainingTests: 0,
passedKnownFailingTests: 0,
passedTests: 0,
selectedTests: 0,
selectingLines: false,
skippedTests: 0,
todoTests: 0,
uncaughtExceptions: 0,
unhandledRejections: 0,
...stats
});
this.pendingTests.set(testFile, new Set());
worker.onStateChange(data => this.emitStateChange(data));
}
emitStateChange(event) {
const {stats} = this;
const fileStats = stats.byFile.get(event.testFile);
let changedStats = true;
switch (event.type) {
case 'declared-test':
stats.declaredTests++;
fileStats.declaredTests++;
break;
case 'hook-failed':
stats.failedHooks++;
fileStats.failedHooks++;
break;
case 'internal-error':
stats.internalErrors++;
if (event.testFile) {
fileStats.internalErrors++;
}
break;
case 'selected-test':
stats.selectedTests++;
fileStats.selectedTests++;
if (event.skip) {
stats.skippedTests++;
fileStats.skippedTests++;
} else if (event.todo) {
stats.todoTests++;
fileStats.todoTests++;
} else {
stats.remainingTests++;
fileStats.remainingTests++;
this.addPendingTest(event);
}
break;
case 'test-failed':
stats.failedTests++;
fileStats.failedTests++;
stats.remainingTests--;
fileStats.remainingTests--;
this.removePendingTest(event);
break;
case 'test-passed':
if (event.knownFailing) {
stats.passedKnownFailingTests++;
fileStats.passedKnownFailingTests++;
} else {
stats.passedTests++;
fileStats.passedTests++;
}
stats.remainingTests--;
fileStats.remainingTests--;
this.removePendingTest(event);
break;
case 'timeout':
event.pendingTests = this.pendingTests;
this.pendingTests = new Map();
stats.timeouts++;
break;
case 'interrupt':
event.pendingTests = this.pendingTests;
this.pendingTests = new Map();
break;
case 'uncaught-exception':
stats.uncaughtExceptions++;
fileStats.uncaughtExceptions++;
break;
case 'unhandled-rejection':
stats.unhandledRejections++;
fileStats.unhandledRejections++;
break;
case 'worker-failed':
stats.failedWorkers++;
break;
case 'worker-finished':
stats.finishedWorkers++;
break;
default:
changedStats = false;
break;
}
if (changedStats) {
this.emit('stateChange', {type: 'stats', stats: cloneDeep(stats)});
}
this.emit('stateChange', event);
}
suggestExitCode(circumstances) {
if (this.emptyParallelRun) {
return 0;
}
if (circumstances.matching && this.stats.selectedTests === 0) {
return 1;
}
if (
this.stats.declaredTests === 0 ||
this.stats.internalErrors > 0 ||
this.stats.failedHooks > 0 ||
this.stats.failedTests > 0 ||
this.stats.failedWorkers > 0 ||
this.stats.timeouts > 0 ||
this.stats.uncaughtExceptions > 0 ||
this.stats.unhandledRejections > 0
) {
return 1;
}
if ([...this.stats.byFile.values()].some(stats => stats.selectingLines && stats.selectedTests === 0)) {
return 1;
}
return 0;
}
addPendingTest(event) {
if (this.pendingTests.has(event.testFile)) {
this.pendingTests.get(event.testFile).add(event.title);
}
}
removePendingTest(event) {
if (this.pendingTests.has(event.testFile)) {
this.pendingTests.get(event.testFile).delete(event.title);
}
}
}
module.exports = RunStatus;

514
node_modules/ava/lib/runner.js generated vendored Normal file
View file

@ -0,0 +1,514 @@
'use strict';
const Emittery = require('emittery');
const matcher = require('matcher');
const ContextRef = require('./context-ref');
const createChain = require('./create-chain');
const parseTestArgs = require('./parse-test-args');
const snapshotManager = require('./snapshot-manager');
const serializeError = require('./serialize-error');
const Runnable = require('./test');
class Runner extends Emittery {
constructor(options = {}) {
super();
this.experiments = options.experiments || {};
this.failFast = options.failFast === true;
this.failWithoutAssertions = options.failWithoutAssertions !== false;
this.file = options.file;
this.checkSelectedByLineNumbers = options.checkSelectedByLineNumbers;
this.match = options.match || [];
this.powerAssert = undefined; // Assigned later.
this.projectDir = options.projectDir;
this.recordNewSnapshots = options.recordNewSnapshots === true;
this.runOnlyExclusive = options.runOnlyExclusive === true;
this.serial = options.serial === true;
this.snapshotDir = options.snapshotDir;
this.updateSnapshots = options.updateSnapshots;
this.activeRunnables = new Set();
this.boundCompareTestSnapshot = this.compareTestSnapshot.bind(this);
this.interrupted = false;
this.snapshots = null;
this.tasks = {
after: [],
afterAlways: [],
afterEach: [],
afterEachAlways: [],
before: [],
beforeEach: [],
concurrent: [],
serial: [],
todo: []
};
const uniqueTestTitles = new Set();
this.registerUniqueTitle = title => {
if (uniqueTestTitles.has(title)) {
return false;
}
uniqueTestTitles.add(title);
return true;
};
let hasStarted = false;
let scheduledStart = false;
const meta = Object.freeze({
file: options.file,
get snapshotDirectory() {
const {file, snapshotDir: fixedLocation, projectDir} = options;
return snapshotManager.determineSnapshotDir({file, fixedLocation, projectDir});
}
});
this.chain = createChain((metadata, testArgs) => { // eslint-disable-line complexity
if (hasStarted) {
throw new Error('All tests and hooks must be declared synchronously in your test file, and cannot be nested within other tests or hooks.');
}
if (!scheduledStart) {
scheduledStart = true;
process.nextTick(() => {
hasStarted = true;
this.start();
});
}
const {args, buildTitle, implementations, rawTitle} = parseTestArgs(testArgs);
if (this.checkSelectedByLineNumbers) {
metadata.selected = this.checkSelectedByLineNumbers();
}
if (metadata.todo) {
if (implementations.length > 0) {
throw new TypeError('`todo` tests are not allowed to have an implementation. Use `test.skip()` for tests with an implementation.');
}
if (!rawTitle) { // Either undefined or a string.
throw new TypeError('`todo` tests require a title');
}
if (!this.registerUniqueTitle(rawTitle)) {
throw new Error(`Duplicate test title: ${rawTitle}`);
}
if (this.match.length > 0) {
// --match selects TODO tests.
if (matcher([rawTitle], this.match).length === 1) {
metadata.exclusive = true;
this.runOnlyExclusive = true;
}
}
this.tasks.todo.push({title: rawTitle, metadata});
this.emit('stateChange', {
type: 'declared-test',
title: rawTitle,
knownFailing: false,
todo: true
});
} else {
if (implementations.length === 0) {
throw new TypeError('Expected an implementation. Use `test.todo()` for tests without an implementation.');
}
for (const implementation of implementations) {
let {title, isSet, isValid, isEmpty} = buildTitle(implementation);
if (isSet && !isValid) {
throw new TypeError('Test & hook titles must be strings');
}
if (isEmpty) {
if (metadata.type === 'test') {
throw new TypeError('Tests must have a title');
} else if (metadata.always) {
title = `${metadata.type}.always hook`;
} else {
title = `${metadata.type} hook`;
}
}
if (metadata.type === 'test' && !this.registerUniqueTitle(title)) {
throw new Error(`Duplicate test title: ${title}`);
}
const task = {
title,
implementation,
args,
metadata: {...metadata}
};
if (metadata.type === 'test') {
if (this.match.length > 0) {
// --match overrides .only()
task.metadata.exclusive = matcher([title], this.match).length === 1;
}
if (task.metadata.exclusive) {
this.runOnlyExclusive = true;
}
this.tasks[metadata.serial ? 'serial' : 'concurrent'].push(task);
this.emit('stateChange', {
type: 'declared-test',
title,
knownFailing: metadata.failing,
todo: false
});
} else if (!metadata.skipped) {
this.tasks[metadata.type + (metadata.always ? 'Always' : '')].push(task);
}
}
}
}, {
serial: false,
exclusive: false,
skipped: false,
todo: false,
failing: false,
callback: false,
inline: false, // Set for attempt metadata created by `t.try()`
always: false
}, meta);
}
compareTestSnapshot(options) {
if (!this.snapshots) {
this.snapshots = snapshotManager.load({
file: this.file,
fixedLocation: this.snapshotDir,
projectDir: this.projectDir,
recordNewSnapshots: this.recordNewSnapshots,
updating: this.updateSnapshots
});
this.emit('dependency', this.snapshots.snapPath);
}
return this.snapshots.compare(options);
}
saveSnapshotState() {
if (this.snapshots) {
return this.snapshots.save();
}
if (this.updateSnapshots) {
// TODO: There may be unused snapshot files if no test caused the
// snapshots to be loaded. Prune them. But not if tests (including hooks!)
// were skipped. Perhaps emit a warning if this occurs?
}
return null;
}
onRun(runnable) {
this.activeRunnables.add(runnable);
}
onRunComplete(runnable) {
this.activeRunnables.delete(runnable);
}
attributeLeakedError(err) {
for (const runnable of this.activeRunnables) {
if (runnable.attributeLeakedError(err)) {
return true;
}
}
return false;
}
beforeExitHandler() {
for (const runnable of this.activeRunnables) {
runnable.finishDueToInactivity();
}
}
async runMultiple(runnables) {
let allPassed = true;
const storedResults = [];
const runAndStoreResult = async runnable => {
const result = await this.runSingle(runnable);
if (!result.passed) {
allPassed = false;
}
storedResults.push(result);
};
let waitForSerial = Promise.resolve();
await runnables.reduce((previous, runnable) => {
if (runnable.metadata.serial || this.serial) {
waitForSerial = previous.then(() => {
// Serial runnables run as long as there was no previous failure, unless
// the runnable should always be run.
return (allPassed || runnable.metadata.always) && runAndStoreResult(runnable);
});
return waitForSerial;
}
return Promise.all([
previous,
waitForSerial.then(() => {
// Concurrent runnables are kicked off after the previous serial
// runnables have completed, as long as there was no previous failure
// (or if the runnable should always be run). One concurrent runnable's
// failure does not prevent the next runnable from running.
return (allPassed || runnable.metadata.always) && runAndStoreResult(runnable);
})
]);
}, waitForSerial);
return {allPassed, storedResults};
}
async runSingle(runnable) {
this.onRun(runnable);
const result = await runnable.run();
// If run() throws or rejects then the entire test run crashes, so
// onRunComplete() doesn't *have* to be inside a finally.
this.onRunComplete(runnable);
return result;
}
async runHooks(tasks, contextRef, titleSuffix, testPassed) {
const hooks = tasks.map(task => new Runnable({
contextRef,
experiments: this.experiments,
failWithoutAssertions: false,
fn: task.args.length === 0 ?
task.implementation :
t => task.implementation.apply(null, [t].concat(task.args)),
compareTestSnapshot: this.boundCompareTestSnapshot,
updateSnapshots: this.updateSnapshots,
metadata: task.metadata,
powerAssert: this.powerAssert,
title: `${task.title}${titleSuffix || ''}`,
isHook: true,
testPassed
}));
const outcome = await this.runMultiple(hooks, this.serial);
for (const result of outcome.storedResults) {
if (result.passed) {
this.emit('stateChange', {
type: 'hook-finished',
title: result.title,
duration: result.duration,
logs: result.logs
});
} else {
this.emit('stateChange', {
type: 'hook-failed',
title: result.title,
err: serializeError('Hook failure', true, result.error),
duration: result.duration,
logs: result.logs
});
}
}
return outcome.allPassed;
}
async runTest(task, contextRef) {
const hookSuffix = ` for ${task.title}`;
let hooksOk = await this.runHooks(this.tasks.beforeEach, contextRef, hookSuffix);
let testOk = false;
if (hooksOk) {
// Only run the test if all `beforeEach` hooks passed.
const test = new Runnable({
contextRef,
experiments: this.experiments,
failWithoutAssertions: this.failWithoutAssertions,
fn: task.args.length === 0 ?
task.implementation :
t => task.implementation.apply(null, [t].concat(task.args)),
compareTestSnapshot: this.boundCompareTestSnapshot,
updateSnapshots: this.updateSnapshots,
metadata: task.metadata,
powerAssert: this.powerAssert,
title: task.title,
registerUniqueTitle: this.registerUniqueTitle
});
const result = await this.runSingle(test);
testOk = result.passed;
if (testOk) {
this.emit('stateChange', {
type: 'test-passed',
title: result.title,
duration: result.duration,
knownFailing: result.metadata.failing,
logs: result.logs
});
hooksOk = await this.runHooks(this.tasks.afterEach, contextRef, hookSuffix, testOk);
} else {
this.emit('stateChange', {
type: 'test-failed',
title: result.title,
err: serializeError('Test failure', true, result.error, this.file),
duration: result.duration,
knownFailing: result.metadata.failing,
logs: result.logs
});
// Don't run `afterEach` hooks if the test failed.
}
}
const alwaysOk = await this.runHooks(this.tasks.afterEachAlways, contextRef, hookSuffix, testOk);
return alwaysOk && hooksOk && testOk;
}
async start() {
const concurrentTests = [];
const serialTests = [];
for (const task of this.tasks.serial) {
if (this.runOnlyExclusive && !task.metadata.exclusive) {
continue;
}
if (this.checkSelectedByLineNumbers && !task.metadata.selected) {
continue;
}
this.emit('stateChange', {
type: 'selected-test',
title: task.title,
knownFailing: task.metadata.failing,
skip: task.metadata.skipped,
todo: false
});
if (!task.metadata.skipped) {
serialTests.push(task);
}
}
for (const task of this.tasks.concurrent) {
if (this.runOnlyExclusive && !task.metadata.exclusive) {
continue;
}
if (this.checkSelectedByLineNumbers && !task.metadata.selected) {
continue;
}
this.emit('stateChange', {
type: 'selected-test',
title: task.title,
knownFailing: task.metadata.failing,
skip: task.metadata.skipped,
todo: false
});
if (!task.metadata.skipped) {
if (this.serial) {
serialTests.push(task);
} else {
concurrentTests.push(task);
}
}
}
for (const task of this.tasks.todo) {
if (this.runOnlyExclusive && !task.metadata.exclusive) {
continue;
}
if (this.checkSelectedByLineNumbers && !task.metadata.selected) {
continue;
}
this.emit('stateChange', {
type: 'selected-test',
title: task.title,
knownFailing: false,
skip: false,
todo: true
});
}
if (concurrentTests.length === 0 && serialTests.length === 0) {
this.emit('finish');
// Don't run any hooks if there are no tests to run.
return;
}
const contextRef = new ContextRef();
// Note that the hooks and tests always begin running asynchronously.
const beforePromise = this.runHooks(this.tasks.before, contextRef);
const serialPromise = beforePromise.then(beforeHooksOk => { // eslint-disable-line promise/prefer-await-to-then
// Don't run tests if a `before` hook failed.
if (!beforeHooksOk) {
return false;
}
return serialTests.reduce(async (previous, task) => {
const previousOk = await previous;
// Don't start tests after an interrupt.
if (this.interrupted) {
return previousOk;
}
// Prevent subsequent tests from running if `failFast` is enabled and
// the previous test failed.
if (!previousOk && this.failFast) {
return false;
}
return this.runTest(task, contextRef.copy());
}, true);
});
const concurrentPromise = Promise.all([beforePromise, serialPromise]).then(async ([beforeHooksOk, serialOk]) => { // eslint-disable-line promise/prefer-await-to-then
// Don't run tests if a `before` hook failed, or if `failFast` is enabled
// and a previous serial test failed.
if (!beforeHooksOk || (!serialOk && this.failFast)) {
return false;
}
// Don't start tests after an interrupt.
if (this.interrupted) {
return true;
}
// If a concurrent test fails, even if `failFast` is enabled it won't
// stop other concurrent tests from running.
const allOkays = await Promise.all(concurrentTests.map(task => {
return this.runTest(task, contextRef.copy());
}));
return allOkays.every(ok => ok);
});
const beforeExitHandler = this.beforeExitHandler.bind(this);
process.on('beforeExit', beforeExitHandler);
try {
const ok = await concurrentPromise;
// Only run `after` hooks if all hooks and tests passed.
if (ok) {
await this.runHooks(this.tasks.after, contextRef);
}
// Always run `after.always` hooks.
await this.runHooks(this.tasks.afterAlways, contextRef);
process.removeListener('beforeExit', beforeExitHandler);
await this.emit('finish');
} catch (error) {
await this.emit('error', error);
}
}
interrupt() {
this.interrupted = true;
}
}
module.exports = Runner;

173
node_modules/ava/lib/serialize-error.js generated vendored Normal file
View file

@ -0,0 +1,173 @@
'use strict';
const path = require('path');
const cleanYamlObject = require('clean-yaml-object');
const concordance = require('concordance');
const isError = require('is-error');
const slash = require('slash');
const StackUtils = require('stack-utils');
const assert = require('./assert');
const concordanceOptions = require('./concordance-options').default;
function isAvaAssertionError(source) {
return source instanceof assert.AssertionError;
}
function filter(propertyName, isRoot) {
return !isRoot || (propertyName !== 'message' && propertyName !== 'name' && propertyName !== 'stack');
}
const stackUtils = new StackUtils();
function extractSource(stack, testFile) {
if (!stack || !testFile) {
return null;
}
// Normalize the test file so it matches `callSite.file`.
const relFile = path.relative(process.cwd(), testFile);
const normalizedFile = process.platform === 'win32' ? slash(relFile) : relFile;
for (const line of stack.split('\n')) {
try {
const callSite = stackUtils.parseLine(line);
if (callSite.file === normalizedFile) {
return {
isDependency: false,
isWithinProject: true,
file: path.resolve(process.cwd(), callSite.file),
line: callSite.line
};
}
} catch {}
}
return null;
}
function buildSource(source) {
if (!source) {
return null;
}
// Assume the CWD is the project directory. This holds since this function
// is only called in test workers, which are created with their working
// directory set to the project directory.
const projectDir = process.cwd();
const file = path.resolve(projectDir, source.file.trim());
const rel = path.relative(projectDir, file);
const [segment] = rel.split(path.sep);
const isWithinProject = segment !== '..' && (process.platform !== 'win32' || !segment.includes(':'));
const isDependency = isWithinProject && path.dirname(rel).split(path.sep).includes('node_modules');
return {
isDependency,
isWithinProject,
file,
line: source.line
};
}
function trySerializeError(err, shouldBeautifyStack, testFile) {
const stack = err.savedError ? err.savedError.stack : err.stack;
const retval = {
avaAssertionError: isAvaAssertionError(err),
nonErrorObject: false,
source: extractSource(stack, testFile),
stack,
shouldBeautifyStack
};
if (err.actualStack) {
retval.stack = err.actualStack;
}
if (retval.avaAssertionError) {
retval.improperUsage = err.improperUsage;
retval.message = err.message;
retval.name = err.name;
retval.statements = err.statements;
retval.values = err.values;
if (err.fixedSource) {
const source = buildSource(err.fixedSource);
if (source) {
retval.source = source;
}
}
if (err.assertion) {
retval.assertion = err.assertion;
}
if (err.operator) {
retval.operator = err.operator;
}
} else {
retval.object = cleanYamlObject(err, filter); // Cleanly copy non-standard properties
if (typeof err.message === 'string') {
retval.message = err.message;
}
if (typeof err.name === 'string') {
retval.name = err.name;
}
}
if (typeof err.stack === 'string') {
const lines = err.stack.split('\n');
if (err.name === 'SyntaxError' && !lines[0].startsWith('SyntaxError')) {
retval.summary = '';
for (const line of lines) {
retval.summary += line + '\n';
if (line.startsWith('SyntaxError')) {
break;
}
}
retval.summary = retval.summary.trim();
} else {
// Skip the source line header inserted by `esm`:
// <https://github.com/standard-things/esm/wiki/improved-errors>
const start = lines.findIndex(line => !/:\d+$/.test(line));
retval.summary = '';
for (let index = start; index < lines.length; index++) {
if (lines[index].startsWith(' at')) {
break;
}
const next = index + 1;
const end = next === lines.length || lines[next].startsWith(' at');
retval.summary += end ? lines[index] : lines[index] + '\n';
}
}
}
return retval;
}
function serializeError(origin, shouldBeautifyStack, err, testFile) {
if (!isError(err)) {
return {
avaAssertionError: false,
nonErrorObject: true,
formatted: concordance.formatDescriptor(concordance.describe(err, concordanceOptions), concordanceOptions)
};
}
try {
return trySerializeError(err, shouldBeautifyStack, testFile);
} catch {
const replacement = new Error(`${origin}: Could not serialize error`);
return {
avaAssertionError: false,
nonErrorObject: false,
name: replacement.name,
message: replacement.message,
stack: replacement.stack,
summary: replacement.message
};
}
}
module.exports = serializeError;

463
node_modules/ava/lib/snapshot-manager.js generated vendored Normal file
View file

@ -0,0 +1,463 @@
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const zlib = require('zlib');
const concordance = require('concordance');
const indentString = require('indent-string');
const md5Hex = require('md5-hex');
const convertSourceMap = require('convert-source-map');
const slash = require('slash');
const writeFileAtomic = require('write-file-atomic');
const mem = require('mem');
const concordanceOptions = require('./concordance-options').snapshotManager;
// Increment if encoding layout or Concordance serialization versions change. Previous AVA versions will not be able to
// decode buffers generated by a newer version, so changing this value will require a major version bump of AVA itself.
// The version is encoded as an unsigned 16 bit integer.
const VERSION = 2;
const VERSION_HEADER = Buffer.alloc(2);
VERSION_HEADER.writeUInt16LE(VERSION);
// The decoder matches on the trailing newline byte (0x0A).
const READABLE_PREFIX = Buffer.from(`AVA Snapshot v${VERSION}\n`, 'ascii');
const REPORT_SEPARATOR = Buffer.from('\n\n', 'ascii');
const REPORT_TRAILING_NEWLINE = Buffer.from('\n', 'ascii');
const MD5_HASH_LENGTH = 16;
class SnapshotError extends Error {
constructor(message, snapPath) {
super(message);
this.name = 'SnapshotError';
this.snapPath = snapPath;
}
}
exports.SnapshotError = SnapshotError;
class ChecksumError extends SnapshotError {
constructor(snapPath) {
super('Checksum mismatch', snapPath);
this.name = 'ChecksumError';
}
}
exports.ChecksumError = ChecksumError;
class VersionMismatchError extends SnapshotError {
constructor(snapPath, version) {
super('Unexpected snapshot version', snapPath);
this.name = 'VersionMismatchError';
this.snapVersion = version;
this.expectedVersion = VERSION;
}
}
exports.VersionMismatchError = VersionMismatchError;
const LEGACY_SNAPSHOT_HEADER = Buffer.from('// Jest Snapshot v1');
function isLegacySnapshot(buffer) {
return LEGACY_SNAPSHOT_HEADER.equals(buffer.slice(0, LEGACY_SNAPSHOT_HEADER.byteLength));
}
class LegacyError extends SnapshotError {
constructor(snapPath) {
super('Legacy snapshot file', snapPath);
this.name = 'LegacyError';
}
}
exports.LegacyError = LegacyError;
function tryRead(file) {
try {
return fs.readFileSync(file);
} catch (error) {
if (error.code === 'ENOENT') {
return null;
}
throw error;
}
}
function withoutLineEndings(buffer) {
let checkPosition = buffer.byteLength - 1;
while (buffer[checkPosition] === 0x0A || buffer[checkPosition] === 0x0D) {
checkPosition--;
}
return buffer.slice(0, checkPosition + 1);
}
function formatEntry(label, descriptor) {
if (label) {
label = `> ${label}\n\n`;
}
const codeBlock = indentString(concordance.formatDescriptor(descriptor, concordanceOptions), 4);
return Buffer.from(label + codeBlock, 'utf8');
}
function combineEntries(entries) {
const buffers = [];
let byteLength = 0;
const sortedKeys = [...entries.keys()].sort();
for (const key of sortedKeys) {
const keyBuffer = Buffer.from(`\n\n## ${key}\n\n`, 'utf8');
buffers.push(keyBuffer);
byteLength += keyBuffer.byteLength;
const formattedEntries = entries.get(key);
const last = formattedEntries[formattedEntries.length - 1];
for (const entry of formattedEntries) {
buffers.push(entry);
byteLength += entry.byteLength;
if (entry !== last) {
buffers.push(REPORT_SEPARATOR);
byteLength += REPORT_SEPARATOR.byteLength;
}
}
}
return {buffers, byteLength};
}
function generateReport(relFile, snapFile, entries) {
const combined = combineEntries(entries);
const {buffers} = combined;
let {byteLength} = combined;
const header = Buffer.from(`# Snapshot report for \`${slash(relFile)}\`
The actual snapshot is saved in \`${snapFile}\`.
Generated by [AVA](https://avajs.dev).`, 'utf8');
buffers.unshift(header);
byteLength += header.byteLength;
buffers.push(REPORT_TRAILING_NEWLINE);
byteLength += REPORT_TRAILING_NEWLINE.byteLength;
return Buffer.concat(buffers, byteLength);
}
function appendReportEntries(existingReport, entries) {
const combined = combineEntries(entries);
const {buffers} = combined;
let {byteLength} = combined;
const prepend = withoutLineEndings(existingReport);
buffers.unshift(prepend);
byteLength += prepend.byteLength;
buffers.push(REPORT_TRAILING_NEWLINE);
byteLength += REPORT_TRAILING_NEWLINE.byteLength;
return Buffer.concat(buffers, byteLength);
}
function encodeSnapshots(buffersByHash) {
const buffers = [];
let byteOffset = 0;
// Entry start and end pointers are relative to the header length. This means
// it's possible to append new entries to an existing snapshot file, without
// having to rewrite pointers for existing entries.
const headerLength = Buffer.alloc(4);
buffers.push(headerLength);
byteOffset += 4;
// Allows 65535 hashes (tests or identified snapshots) per file.
const numberHashes = Buffer.alloc(2);
numberHashes.writeUInt16LE(buffersByHash.size);
buffers.push(numberHashes);
byteOffset += 2;
const entries = [];
for (const pair of buffersByHash) {
const hash = pair[0];
const snapshotBuffers = pair[1];
buffers.push(Buffer.from(hash, 'hex'));
byteOffset += MD5_HASH_LENGTH;
// Allows 65535 snapshots per hash.
const numberSnapshots = Buffer.alloc(2);
numberSnapshots.writeUInt16LE(snapshotBuffers.length, 0);
buffers.push(numberSnapshots);
byteOffset += 2;
for (const value of snapshotBuffers) {
// Each pointer is 32 bits, restricting the total, uncompressed buffer to
// 4 GiB.
const start = Buffer.alloc(4);
const end = Buffer.alloc(4);
entries.push({start, end, value});
buffers.push(start, end);
byteOffset += 8;
}
}
headerLength.writeUInt32LE(byteOffset, 0);
let bodyOffset = 0;
for (const entry of entries) {
const start = bodyOffset;
const end = bodyOffset + entry.value.byteLength;
entry.start.writeUInt32LE(start, 0);
entry.end.writeUInt32LE(end, 0);
buffers.push(entry.value);
bodyOffset = end;
}
byteOffset += bodyOffset;
const compressed = zlib.gzipSync(Buffer.concat(buffers, byteOffset));
compressed[9] = 0x03; // Override the GZip header containing the OS to always be Linux
const md5sum = crypto.createHash('md5').update(compressed).digest();
return Buffer.concat([
READABLE_PREFIX,
VERSION_HEADER,
md5sum,
compressed
], READABLE_PREFIX.byteLength + VERSION_HEADER.byteLength + MD5_HASH_LENGTH + compressed.byteLength);
}
function decodeSnapshots(buffer, snapPath) {
if (isLegacySnapshot(buffer)) {
throw new LegacyError(snapPath);
}
// The version starts after the readable prefix, which is ended by a newline
// byte (0x0A).
const versionOffset = buffer.indexOf(0x0A) + 1;
const version = buffer.readUInt16LE(versionOffset);
if (version !== VERSION) {
throw new VersionMismatchError(snapPath, version);
}
const md5sumOffset = versionOffset + 2;
const compressedOffset = md5sumOffset + MD5_HASH_LENGTH;
const compressed = buffer.slice(compressedOffset);
const md5sum = crypto.createHash('md5').update(compressed).digest();
const expectedSum = buffer.slice(md5sumOffset, compressedOffset);
if (!md5sum.equals(expectedSum)) {
throw new ChecksumError(snapPath);
}
const decompressed = zlib.gunzipSync(compressed);
let byteOffset = 0;
const headerLength = decompressed.readUInt32LE(byteOffset);
byteOffset += 4;
const snapshotsByHash = new Map();
const numberHashes = decompressed.readUInt16LE(byteOffset);
byteOffset += 2;
for (let count = 0; count < numberHashes; count++) {
const hash = decompressed.toString('hex', byteOffset, byteOffset + MD5_HASH_LENGTH);
byteOffset += MD5_HASH_LENGTH;
const numberSnapshots = decompressed.readUInt16LE(byteOffset);
byteOffset += 2;
const snapshotsBuffers = new Array(numberSnapshots);
for (let index = 0; index < numberSnapshots; index++) {
const start = decompressed.readUInt32LE(byteOffset) + headerLength;
byteOffset += 4;
const end = decompressed.readUInt32LE(byteOffset) + headerLength;
byteOffset += 4;
snapshotsBuffers[index] = decompressed.slice(start, end);
}
// Allow for new entries to be appended to an existing header, which could
// lead to the same hash being present multiple times.
if (snapshotsByHash.has(hash)) {
snapshotsByHash.set(hash, snapshotsByHash.get(hash).concat(snapshotsBuffers));
} else {
snapshotsByHash.set(hash, snapshotsBuffers);
}
}
return snapshotsByHash;
}
class Manager {
constructor(options) {
this.appendOnly = options.appendOnly;
this.dir = options.dir;
this.recordNewSnapshots = options.recordNewSnapshots;
this.relFile = options.relFile;
this.reportFile = options.reportFile;
this.snapFile = options.snapFile;
this.snapPath = options.snapPath;
this.snapshotsByHash = options.snapshotsByHash;
this.hasChanges = false;
this.reportEntries = new Map();
}
compare(options) {
const hash = md5Hex(options.belongsTo);
const entries = this.snapshotsByHash.get(hash) || [];
const snapshotBuffer = entries[options.index];
if (!snapshotBuffer) {
if (!this.recordNewSnapshots) {
return {pass: false};
}
if (options.deferRecording) {
const record = this.deferRecord(hash, options);
return {pass: true, record};
}
this.record(hash, options);
return {pass: true};
}
const actual = concordance.deserialize(snapshotBuffer, concordanceOptions);
const expected = concordance.describe(options.expected, concordanceOptions);
const pass = concordance.compareDescriptors(actual, expected);
return {actual, expected, pass};
}
deferRecord(hash, options) {
const descriptor = concordance.describe(options.expected, concordanceOptions);
const snapshot = concordance.serialize(descriptor);
const entry = formatEntry(options.label, descriptor);
return () => { // Must be called in order!
this.hasChanges = true;
let snapshots = this.snapshotsByHash.get(hash);
if (!snapshots) {
snapshots = [];
this.snapshotsByHash.set(hash, snapshots);
}
if (options.index > snapshots.length) {
throw new RangeError(`Cannot record snapshot ${options.index} for ${JSON.stringify(options.belongsTo)}, exceeds expected index of ${snapshots.length}`);
}
if (options.index < snapshots.length) {
throw new RangeError(`Cannot record snapshot ${options.index} for ${JSON.stringify(options.belongsTo)}, already exists`);
}
snapshots.push(snapshot);
if (this.reportEntries.has(options.belongsTo)) {
this.reportEntries.get(options.belongsTo).push(entry);
} else {
this.reportEntries.set(options.belongsTo, [entry]);
}
};
}
record(hash, options) {
const record = this.deferRecord(hash, options);
record();
}
save() {
if (!this.hasChanges) {
return null;
}
const {snapPath} = this;
const buffer = encodeSnapshots(this.snapshotsByHash);
const reportPath = path.join(this.dir, this.reportFile);
const existingReport = this.appendOnly ? tryRead(reportPath) : null;
const reportBuffer = existingReport ?
appendReportEntries(existingReport, this.reportEntries) :
generateReport(this.relFile, this.snapFile, this.reportEntries);
fs.mkdirSync(this.dir, {recursive: true});
const paths = [snapPath, reportPath];
const tmpfileCreated = tmpfile => paths.push(tmpfile);
writeFileAtomic.sync(snapPath, buffer, {tmpfileCreated});
writeFileAtomic.sync(reportPath, reportBuffer, {tmpfileCreated});
return paths;
}
}
const resolveSourceFile = mem(file => {
const testDir = path.dirname(file);
const buffer = tryRead(file);
if (!buffer) {
return file; // Assume the file is stubbed in our test suite.
}
const source = buffer.toString();
const converter = convertSourceMap.fromSource(source) || convertSourceMap.fromMapFileSource(source, testDir);
if (converter) {
const map = converter.toObject();
const firstSource = `${map.sourceRoot || ''}${map.sources[0]}`;
return path.resolve(testDir, firstSource);
}
return file;
});
const determineSnapshotDir = mem(({file, fixedLocation, projectDir}) => {
const testDir = path.dirname(resolveSourceFile(file));
if (fixedLocation) {
const relativeTestLocation = path.relative(projectDir, testDir);
return path.join(fixedLocation, relativeTestLocation);
}
const parts = new Set(path.relative(projectDir, testDir).split(path.sep));
if (parts.has('__tests__')) {
return path.join(testDir, '__snapshots__');
}
if (parts.has('test') || parts.has('tests')) { // Accept tests, even though it's not in the default test patterns
return path.join(testDir, 'snapshots');
}
return testDir;
}, {cacheKey: ([{file}]) => file});
exports.determineSnapshotDir = determineSnapshotDir;
function load({file, fixedLocation, projectDir, recordNewSnapshots, updating}) {
const dir = determineSnapshotDir({file, fixedLocation, projectDir});
const relFile = path.relative(projectDir, resolveSourceFile(file));
const name = path.basename(relFile);
const reportFile = `${name}.md`;
const snapFile = `${name}.snap`;
const snapPath = path.join(dir, snapFile);
let appendOnly = !updating;
let snapshotsByHash;
if (!updating) {
const buffer = tryRead(snapPath);
if (buffer) {
snapshotsByHash = decodeSnapshots(buffer, snapPath);
} else {
appendOnly = false;
}
}
return new Manager({
appendOnly,
dir,
recordNewSnapshots,
relFile,
reportFile,
snapFile,
snapPath,
snapshotsByHash: snapshotsByHash || new Map()
});
}
exports.load = load;

738
node_modules/ava/lib/test.js generated vendored Normal file
View file

@ -0,0 +1,738 @@
'use strict';
const concordance = require('concordance');
const isPromise = require('is-promise');
const plur = require('plur');
const assert = require('./assert');
const nowAndTimers = require('./now-and-timers');
const parseTestArgs = require('./parse-test-args');
const concordanceOptions = require('./concordance-options').default;
function formatErrorValue(label, error) {
const formatted = concordance.format(error, concordanceOptions);
return {label, formatted};
}
const captureSavedError = () => {
const limitBefore = Error.stackTraceLimit;
Error.stackTraceLimit = 1;
const err = new Error();
Error.stackTraceLimit = limitBefore;
return err;
};
const testMap = new WeakMap();
class ExecutionContext extends assert.Assertions {
constructor(test) {
super({
pass: () => {
test.countPassedAssertion();
},
pending: promise => {
test.addPendingAssertion(promise);
},
fail: err => {
test.addFailedAssertion(err);
},
skip: () => {
test.countPassedAssertion();
},
compareWithSnapshot: options => {
return test.compareWithSnapshot(options);
},
powerAssert: test.powerAssert
});
testMap.set(this, test);
this.snapshot.skip = () => {
test.skipSnapshot();
};
this.log = (...inputArgs) => {
const args = inputArgs.map(value => {
return typeof value === 'string' ?
value :
concordance.format(value, concordanceOptions);
});
if (args.length > 0) {
test.addLog(args.join(' '));
}
};
this.plan = count => {
test.plan(count, captureSavedError());
};
this.plan.skip = () => {};
this.timeout = ms => {
test.timeout(ms);
};
this.teardown = callback => {
test.addTeardown(callback);
};
this.try = async (...attemptArgs) => {
const {args, buildTitle, implementations, receivedImplementationArray} = parseTestArgs(attemptArgs);
if (implementations.length === 0) {
throw new TypeError('Expected an implementation.');
}
const attemptPromises = implementations.map((implementation, index) => {
let {title, isSet, isValid, isEmpty} = buildTitle(implementation);
if (!isSet || isEmpty) {
title = `${test.title} ─ attempt ${test.attemptCount + 1 + index}`;
} else if (isValid) {
title = `${test.title}${title}`;
} else {
throw new TypeError('`t.try()` titles must be strings'); // Throw synchronously!
}
if (!test.registerUniqueTitle(title)) {
throw new Error(`Duplicate test title: ${title}`);
}
return {implementation, title};
}).map(async ({implementation, title}) => {
let committed = false;
let discarded = false;
const {assertCount, deferredSnapshotRecordings, errors, logs, passed, snapshotCount, startingSnapshotCount} = await test.runAttempt(title, t => implementation(t, ...args));
return {
errors,
logs: [...logs], // Don't allow modification of logs.
passed,
title,
commit: ({retainLogs = true} = {}) => {
if (committed) {
return;
}
if (discarded) {
test.saveFirstError(new Error('Cant commit a result that was previously discarded'));
return;
}
committed = true;
test.finishAttempt({
assertCount,
commit: true,
deferredSnapshotRecordings,
errors,
logs,
passed,
retainLogs,
snapshotCount,
startingSnapshotCount
});
},
discard: ({retainLogs = false} = {}) => {
if (committed) {
test.saveFirstError(new Error('Cant discard a result that was previously committed'));
return;
}
if (discarded) {
return;
}
discarded = true;
test.finishAttempt({
assertCount: 0,
commit: false,
deferredSnapshotRecordings,
errors,
logs,
passed,
retainLogs,
snapshotCount,
startingSnapshotCount
});
}
};
});
const results = await Promise.all(attemptPromises);
return receivedImplementationArray ? results : results[0];
};
}
get end() {
const end = testMap.get(this).bindEndCallback();
const endFn = error => end(error, captureSavedError());
return endFn;
}
get title() {
return testMap.get(this).title;
}
get context() {
return testMap.get(this).contextRef.get();
}
set context(context) {
testMap.get(this).contextRef.set(context);
}
get passed() {
return testMap.get(this).testPassed;
}
_throwsArgStart(assertion, file, line) {
testMap.get(this).trackThrows({assertion, file, line});
}
_throwsArgEnd() {
testMap.get(this).trackThrows(null);
}
}
class Test {
constructor(options) {
this.contextRef = options.contextRef;
this.experiments = options.experiments || {};
this.failWithoutAssertions = options.failWithoutAssertions;
this.fn = options.fn;
this.isHook = options.isHook === true;
this.metadata = options.metadata;
this.powerAssert = options.powerAssert;
this.title = options.title;
this.testPassed = options.testPassed;
this.registerUniqueTitle = options.registerUniqueTitle;
this.logs = [];
this.teardowns = [];
const {snapshotBelongsTo = this.title, nextSnapshotIndex = 0} = options;
this.snapshotBelongsTo = snapshotBelongsTo;
this.nextSnapshotIndex = nextSnapshotIndex;
this.snapshotCount = 0;
const deferRecording = this.metadata.inline;
this.deferredSnapshotRecordings = [];
this.compareWithSnapshot = ({expected, id, message}) => {
this.snapshotCount++;
// TODO: In a breaking change, reject non-undefined, falsy IDs and messages.
const belongsTo = id || snapshotBelongsTo;
const index = id ? 0 : this.nextSnapshotIndex++;
const label = id ? '' : message || `Snapshot ${index + 1}`; // Human-readable labels start counting at 1.
const {record, ...result} = options.compareTestSnapshot({belongsTo, deferRecording, expected, index, label});
if (record) {
this.deferredSnapshotRecordings.push(record);
}
return result;
};
this.skipSnapshot = () => {
if (options.updateSnapshots) {
this.addFailedAssertion(new Error('Snapshot assertions cannot be skipped when updating snapshots'));
} else {
this.nextSnapshotIndex++;
this.snapshotCount++;
this.countPassedAssertion();
}
};
this.runAttempt = async (title, fn) => {
if (this.finishing) {
this.saveFirstError(new Error('Running a `t.try()`, but the test has already finished'));
}
this.attemptCount++;
this.pendingAttemptCount++;
const {contextRef, snapshotBelongsTo, nextSnapshotIndex, snapshotCount: startingSnapshotCount} = this;
const attempt = new Test({
...options,
fn,
metadata: {...options.metadata, callback: false, failing: false, inline: true},
contextRef: contextRef.copy(),
snapshotBelongsTo,
nextSnapshotIndex,
title
});
const {deferredSnapshotRecordings, error, logs, passed, assertCount, snapshotCount} = await attempt.run();
const errors = error ? [error] : [];
return {assertCount, deferredSnapshotRecordings, errors, logs, passed, snapshotCount, startingSnapshotCount};
};
this.assertCount = 0;
this.assertError = undefined;
this.attemptCount = 0;
this.calledEnd = false;
this.duration = null;
this.endCallbackFinisher = null;
this.finishDueToAttributedError = null;
this.finishDueToInactivity = null;
this.finishDueToTimeout = null;
this.finishing = false;
this.pendingAssertionCount = 0;
this.pendingAttemptCount = 0;
this.pendingThrowsAssertion = null;
this.planCount = null;
this.startedAt = 0;
this.timeoutMs = 0;
this.timeoutTimer = null;
}
bindEndCallback() {
if (this.metadata.callback) {
return (error, savedError) => {
this.endCallback(error, savedError);
};
}
if (this.metadata.inline) {
throw new Error('`t.end()` is not supported inside `t.try()`');
} else {
throw new Error('`t.end()` is not supported in this context. To use `t.end()` as a callback, you must use "callback mode" via `test.cb(testName, fn)`');
}
}
endCallback(error, savedError) {
if (this.calledEnd) {
this.saveFirstError(new Error('`t.end()` called more than once'));
return;
}
this.calledEnd = true;
if (error) {
this.saveFirstError(new assert.AssertionError({
actual: error,
message: 'Callback called with an error',
savedError,
values: [formatErrorValue('Callback called with an error:', error)]
}));
}
if (this.endCallbackFinisher) {
this.endCallbackFinisher();
}
}
createExecutionContext() {
return new ExecutionContext(this);
}
countPassedAssertion() {
if (this.finishing) {
this.saveFirstError(new Error('Assertion passed, but test has already finished'));
}
if (this.pendingAttemptCount > 0) {
this.saveFirstError(new Error('Assertion passed, but an attempt is pending. Use the attempts assertions instead'));
}
this.assertCount++;
this.refreshTimeout();
}
addLog(text) {
this.logs.push(text);
}
addPendingAssertion(promise) {
if (this.finishing) {
this.saveFirstError(new Error('Assertion started, but test has already finished'));
}
if (this.pendingAttemptCount > 0) {
this.saveFirstError(new Error('Assertion started, but an attempt is pending. Use the attempts assertions instead'));
}
this.assertCount++;
this.pendingAssertionCount++;
this.refreshTimeout();
promise
.catch(error => this.saveFirstError(error))
.then(() => { // eslint-disable-line promise/prefer-await-to-then
this.pendingAssertionCount--;
this.refreshTimeout();
});
}
addFailedAssertion(error) {
if (this.finishing) {
this.saveFirstError(new Error('Assertion failed, but test has already finished'));
}
if (this.pendingAttemptCount > 0) {
this.saveFirstError(new Error('Assertion failed, but an attempt is pending. Use the attempts assertions instead'));
}
this.assertCount++;
this.refreshTimeout();
this.saveFirstError(error);
}
finishAttempt({commit, deferredSnapshotRecordings, errors, logs, passed, retainLogs, snapshotCount, startingSnapshotCount}) {
if (this.finishing) {
if (commit) {
this.saveFirstError(new Error('`t.try()` result was committed, but the test has already finished'));
} else {
this.saveFirstError(new Error('`t.try()` result was discarded, but the test has already finished'));
}
}
if (commit) {
this.assertCount++;
if (startingSnapshotCount === this.snapshotCount) {
this.snapshotCount += snapshotCount;
this.nextSnapshotIndex += snapshotCount;
for (const record of deferredSnapshotRecordings) {
record();
}
} else {
this.saveFirstError(new Error('Cannot commit `t.try()` result. Do not run concurrent snapshot assertions when using `t.try()`'));
}
}
this.pendingAttemptCount--;
if (commit && !passed) {
this.saveFirstError(errors[0]);
}
if (retainLogs) {
for (const log of logs) {
this.addLog(log);
}
}
this.refreshTimeout();
}
saveFirstError(error) {
if (!this.assertError) {
this.assertError = error;
}
}
plan(count, planError) {
if (typeof count !== 'number') {
throw new TypeError('Expected a number');
}
this.planCount = count;
// In case the `planCount` doesn't match `assertCount, we need the stack of
// this function to throw with a useful stack.
this.planError = planError;
}
timeout(ms) {
if (this.finishing) {
return;
}
this.clearTimeout();
this.timeoutMs = ms;
this.timeoutTimer = nowAndTimers.setTimeout(() => {
this.saveFirstError(new Error('Test timeout exceeded'));
if (this.finishDueToTimeout) {
this.finishDueToTimeout();
}
}, ms);
}
refreshTimeout() {
if (!this.timeoutTimer) {
return;
}
if (this.timeoutTimer.refresh) {
this.timeoutTimer.refresh();
} else {
this.timeout(this.timeoutMs);
}
}
clearTimeout() {
nowAndTimers.clearTimeout(this.timeoutTimer);
this.timeoutTimer = null;
}
addTeardown(callback) {
if (this.isHook) {
this.saveFirstError(new Error('`t.teardown()` is not allowed in hooks'));
return;
}
if (this.finishing) {
this.saveFirstError(new Error('`t.teardown()` cannot be used during teardown'));
return;
}
if (typeof callback !== 'function') {
throw new TypeError('Expected a function');
}
this.teardowns.push(callback);
}
async runTeardowns() {
for (const teardown of this.teardowns) {
try {
await teardown(); // eslint-disable-line no-await-in-loop
} catch (error) {
this.saveFirstError(error);
}
}
}
verifyPlan() {
if (!this.assertError && this.planCount !== null && this.planCount !== this.assertCount) {
this.saveFirstError(new assert.AssertionError({
assertion: 'plan',
message: `Planned for ${this.planCount} ${plur('assertion', this.planCount)}, but got ${this.assertCount}.`,
operator: '===',
savedError: this.planError
}));
}
}
verifyAssertions() {
if (this.assertError) {
return;
}
if (this.pendingAttemptCount > 0) {
this.saveFirstError(new Error('Test finished, but not all attempts were committed or discarded'));
return;
}
if (this.pendingAssertionCount > 0) {
this.saveFirstError(new Error('Test finished, but an assertion is still pending'));
return;
}
if (this.failWithoutAssertions) {
if (this.planCount !== null) {
return; // `verifyPlan()` will report an error already.
}
if (this.assertCount === 0 && !this.calledEnd) {
this.saveFirstError(new Error('Test finished without running any assertions'));
}
}
}
trackThrows(pending) {
this.pendingThrowsAssertion = pending;
}
detectImproperThrows(error) {
if (!this.pendingThrowsAssertion) {
return false;
}
const pending = this.pendingThrowsAssertion;
this.pendingThrowsAssertion = null;
const values = [];
if (error) {
values.push(formatErrorValue(`The following error was thrown, possibly before \`t.${pending.assertion}()\` could be called:`, error));
}
this.saveFirstError(new assert.AssertionError({
assertion: pending.assertion,
fixedSource: {file: pending.file, line: pending.line},
improperUsage: true,
message: `Improper usage of \`t.${pending.assertion}()\` detected`,
savedError: error instanceof Error && error,
values
}));
return true;
}
waitForPendingThrowsAssertion() {
return new Promise(resolve => {
this.finishDueToAttributedError = () => {
resolve(this.finish());
};
this.finishDueToInactivity = () => {
this.detectImproperThrows();
resolve(this.finish());
};
// Wait up to a second to see if an error can be attributed to the
// pending assertion.
nowAndTimers.setTimeout(() => this.finishDueToInactivity(), 1000).unref();
});
}
attributeLeakedError(error) {
if (!this.detectImproperThrows(error)) {
return false;
}
this.finishDueToAttributedError();
return true;
}
callFn() {
try {
return {
ok: true,
retval: this.fn.call(null, this.createExecutionContext())
};
} catch (error) {
return {
ok: false,
error
};
}
}
run() {
this.startedAt = nowAndTimers.now();
const result = this.callFn();
if (!result.ok) {
if (!this.detectImproperThrows(result.error)) {
this.saveFirstError(new assert.AssertionError({
message: 'Error thrown in test',
savedError: result.error instanceof Error && result.error,
values: [formatErrorValue('Error thrown in test:', result.error)]
}));
}
return this.finish();
}
const returnedObservable = result.retval !== null && typeof result.retval === 'object' && typeof result.retval.subscribe === 'function';
const returnedPromise = isPromise(result.retval);
let promise;
if (returnedObservable) {
promise = new Promise((resolve, reject) => {
result.retval.subscribe({
error: reject,
complete: () => resolve()
});
});
} else if (returnedPromise) {
// `retval` can be any thenable, so convert to a proper promise.
promise = Promise.resolve(result.retval);
}
if (this.metadata.callback) {
if (returnedObservable || returnedPromise) {
const asyncType = returnedObservable ? 'observables' : 'promises';
this.saveFirstError(new Error(`Do not return ${asyncType} from tests declared via \`test.cb(…)\`. Use \`test.cb(…)\` for legacy callback APIs. When using promises, observables or async functions, use \`test(…)\`.`));
return this.finish();
}
if (this.calledEnd) {
return this.finish();
}
return new Promise(resolve => {
this.endCallbackFinisher = () => {
resolve(this.finish());
};
this.finishDueToAttributedError = () => {
resolve(this.finish());
};
this.finishDueToTimeout = () => {
resolve(this.finish());
};
this.finishDueToInactivity = () => {
this.saveFirstError(new Error('`t.end()` was never called'));
resolve(this.finish());
};
});
}
if (promise) {
return new Promise(resolve => {
this.finishDueToAttributedError = () => {
resolve(this.finish());
};
this.finishDueToTimeout = () => {
resolve(this.finish());
};
this.finishDueToInactivity = () => {
const error = returnedObservable ?
new Error('Observable returned by test never completed') :
new Error('Promise returned by test never resolved');
this.saveFirstError(error);
resolve(this.finish());
};
promise
.catch(error => {
if (!this.detectImproperThrows(error)) {
this.saveFirstError(new assert.AssertionError({
message: 'Rejected promise returned by test',
savedError: error instanceof Error && error,
values: [formatErrorValue('Rejected promise returned by test. Reason:', error)]
}));
}
})
.then(() => resolve(this.finish())); // eslint-disable-line promise/prefer-await-to-then
});
}
return this.finish();
}
async finish() {
this.finishing = true;
if (!this.assertError && this.pendingThrowsAssertion) {
return this.waitForPendingThrowsAssertion();
}
this.clearTimeout();
this.verifyPlan();
this.verifyAssertions();
await this.runTeardowns();
this.duration = nowAndTimers.now() - this.startedAt;
let error = this.assertError;
let passed = !error;
if (this.metadata.failing) {
passed = !passed;
if (passed) {
error = null;
} else {
error = new Error('Test was expected to fail, but succeeded, you should stop marking the test as failing');
}
}
return {
deferredSnapshotRecordings: this.deferredSnapshotRecordings,
duration: this.duration,
error,
logs: this.logs,
metadata: this.metadata,
passed,
snapshotCount: this.snapshotCount,
assertCount: this.assertCount,
title: this.title
};
}
}
module.exports = Test;

447
node_modules/ava/lib/watcher.js generated vendored Normal file
View file

@ -0,0 +1,447 @@
'use strict';
const nodePath = require('path');
const debug = require('debug')('ava:watcher');
const chokidar = require('chokidar');
const diff = require('lodash/difference');
const flatten = require('lodash/flatten');
const chalk = require('./chalk').get();
const {applyTestFileFilter, classify, getChokidarIgnorePatterns} = require('./globs');
const {levels: providerLevels} = require('./provider-manager');
function rethrowAsync(err) {
// Don't swallow exceptions. Note that any
// expected error should already have been logged
setImmediate(() => {
throw err;
});
}
const MIN_DEBOUNCE_DELAY = 10;
const INITIAL_DEBOUNCE_DELAY = 100;
const END_MESSAGE = chalk.gray('Type `r` and press enter to rerun tests\nType `u` and press enter to update snapshots\n');
class Debouncer {
constructor(watcher) {
this.watcher = watcher;
this.timer = null;
this.repeat = false;
}
debounce(delay) {
if (this.timer) {
this.again = true;
return;
}
delay = delay ? Math.max(delay, MIN_DEBOUNCE_DELAY) : INITIAL_DEBOUNCE_DELAY;
const timer = setTimeout(async () => {
await this.watcher.busy;
// Do nothing if debouncing was canceled while waiting for the busy
// promise to fulfil
if (this.timer !== timer) {
return;
}
if (this.again) {
this.timer = null;
this.again = false;
this.debounce(delay / 2);
} else {
this.watcher.runAfterChanges();
this.timer = null;
this.again = false;
}
}, delay);
this.timer = timer;
}
cancel() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
this.again = false;
}
}
}
class TestDependency {
constructor(file, dependencies) {
this.file = file;
this.dependencies = dependencies;
}
contains(dependency) {
return this.dependencies.includes(dependency);
}
}
class Watcher {
constructor({api, filter = [], globs, projectDir, providers, reporter}) {
this.debouncer = new Debouncer(this);
this.clearLogOnNextRun = true;
this.runVector = 0;
this.previousFiles = [];
this.globs = {cwd: projectDir, ...globs};
const patternFilters = filter.map(({pattern}) => pattern);
this.providers = providers.filter(({level}) => level >= providerLevels.pathRewrites);
this.run = (specificFiles = [], updateSnapshots = false) => {
const clearLogOnNextRun = this.clearLogOnNextRun && this.runVector > 0;
if (this.runVector > 0) {
this.clearLogOnNextRun = true;
}
this.runVector++;
let runOnlyExclusive = false;
if (specificFiles.length > 0) {
const exclusiveFiles = specificFiles.filter(file => this.filesWithExclusiveTests.includes(file));
runOnlyExclusive = exclusiveFiles.length !== this.filesWithExclusiveTests.length;
if (runOnlyExclusive) {
// The test files that previously contained exclusive tests are always
// run, together with the remaining specific files.
const remainingFiles = diff(specificFiles, exclusiveFiles);
specificFiles = this.filesWithExclusiveTests.concat(remainingFiles);
}
if (filter.length > 0) {
specificFiles = applyTestFileFilter({cwd: projectDir, filter: patternFilters, testFiles: specificFiles});
}
this.pruneFailures(specificFiles);
}
this.touchedFiles.clear();
this.previousFiles = specificFiles;
this.busy = api.run({
files: specificFiles,
filter,
runtimeOptions: {
clearLogOnNextRun,
previousFailures: this.sumPreviousFailures(this.runVector),
runOnlyExclusive,
runVector: this.runVector,
updateSnapshots: updateSnapshots === true
}
})
.then(runStatus => { // eslint-disable-line promise/prefer-await-to-then
reporter.endRun();
reporter.lineWriter.writeLine(END_MESSAGE);
if (this.clearLogOnNextRun && (
runStatus.stats.failedHooks > 0 ||
runStatus.stats.failedTests > 0 ||
runStatus.stats.failedWorkers > 0 ||
runStatus.stats.internalErrors > 0 ||
runStatus.stats.timeouts > 0 ||
runStatus.stats.uncaughtExceptions > 0 ||
runStatus.stats.unhandledRejections > 0
)) {
this.clearLogOnNextRun = false;
}
})
.catch(rethrowAsync);
};
this.testDependencies = [];
this.trackTestDependencies(api);
this.touchedFiles = new Set();
this.trackTouchedFiles(api);
this.filesWithExclusiveTests = [];
this.trackExclusivity(api);
this.filesWithFailures = [];
this.trackFailures(api);
this.dirtyStates = {};
this.watchFiles();
this.rerunAll();
}
watchFiles() {
chokidar.watch(['**/*'], {
cwd: this.globs.cwd,
ignored: getChokidarIgnorePatterns(this.globs),
ignoreInitial: true
}).on('all', (event, path) => {
if (event === 'add' || event === 'change' || event === 'unlink') {
debug('Detected %s of %s', event, path);
this.dirtyStates[nodePath.join(this.globs.cwd, path)] = event;
this.debouncer.debounce();
}
});
}
trackTestDependencies(api) {
api.on('run', plan => {
plan.status.on('stateChange', evt => {
if (evt.type !== 'dependencies') {
return;
}
const dependencies = evt.dependencies.filter(filePath => {
const {isIgnoredByWatcher} = classify(filePath, this.globs);
return !isIgnoredByWatcher;
});
this.updateTestDependencies(evt.testFile, dependencies);
});
});
}
updateTestDependencies(file, dependencies) {
// Ensure the rewritten test file path is included in the dependencies,
// since changes to non-rewritten paths are ignored.
for (const {main} of this.providers) {
const rewritten = main.resolveTestFile(file);
if (!dependencies.includes(rewritten)) {
dependencies = [rewritten, ...dependencies];
}
}
if (dependencies.length === 0) {
this.testDependencies = this.testDependencies.filter(dep => dep.file !== file);
return;
}
const isUpdate = this.testDependencies.some(dep => {
if (dep.file !== file) {
return false;
}
dep.dependencies = dependencies;
return true;
});
if (!isUpdate) {
this.testDependencies.push(new TestDependency(file, dependencies));
}
}
trackTouchedFiles(api) {
api.on('run', plan => {
plan.status.on('stateChange', evt => {
if (evt.type !== 'touched-files') {
return;
}
for (const file of evt.files) {
this.touchedFiles.add(file);
}
});
});
}
trackExclusivity(api) {
api.on('run', plan => {
plan.status.on('stateChange', evt => {
if (evt.type !== 'worker-finished') {
return;
}
const fileStats = plan.status.stats.byFile.get(evt.testFile);
const ranExclusiveTests = fileStats.selectedTests > 0 && fileStats.declaredTests > fileStats.selectedTests;
this.updateExclusivity(evt.testFile, ranExclusiveTests);
});
});
}
updateExclusivity(file, hasExclusiveTests) {
const index = this.filesWithExclusiveTests.indexOf(file);
if (hasExclusiveTests && index === -1) {
this.filesWithExclusiveTests.push(file);
} else if (!hasExclusiveTests && index !== -1) {
this.filesWithExclusiveTests.splice(index, 1);
}
}
trackFailures(api) {
api.on('run', plan => {
this.pruneFailures(plan.files);
const currentVector = this.runVector;
plan.status.on('stateChange', evt => {
if (!evt.testFile) {
return;
}
switch (evt.type) {
case 'hook-failed':
case 'internal-error':
case 'test-failed':
case 'uncaught-exception':
case 'unhandled-rejection':
case 'worker-failed':
this.countFailure(evt.testFile, currentVector);
break;
default:
break;
}
});
});
}
pruneFailures(files) {
const toPrune = new Set(files);
this.filesWithFailures = this.filesWithFailures.filter(state => !toPrune.has(state.file));
}
countFailure(file, vector) {
const isUpdate = this.filesWithFailures.some(state => {
if (state.file !== file) {
return false;
}
state.count++;
return true;
});
if (!isUpdate) {
this.filesWithFailures.push({
file,
vector,
count: 1
});
}
}
sumPreviousFailures(beforeVector) {
let total = 0;
for (const state of this.filesWithFailures) {
if (state.vector < beforeVector) {
total += state.count;
}
}
return total;
}
cleanUnlinkedTests(unlinkedTests) {
for (const testFile of unlinkedTests) {
this.updateTestDependencies(testFile, []);
this.updateExclusivity(testFile, false);
this.pruneFailures([testFile]);
}
}
observeStdin(stdin) {
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', async data => {
data = data.trim().toLowerCase();
if (data !== 'r' && data !== 'rs' && data !== 'u') {
return;
}
// Cancel the debouncer, it might rerun specific tests whereas *all* tests
// need to be rerun
this.debouncer.cancel();
await this.busy;
// Cancel the debouncer again, it might have restarted while waiting for
// the busy promise to fulfil
this.debouncer.cancel();
this.clearLogOnNextRun = false;
if (data === 'u') {
this.updatePreviousSnapshots();
} else {
this.rerunAll();
}
});
}
rerunAll() {
this.dirtyStates = {};
this.run();
}
updatePreviousSnapshots() {
this.dirtyStates = {};
this.run(this.previousFiles, true);
}
runAfterChanges() {
const {dirtyStates} = this;
this.dirtyStates = {};
let dirtyPaths = Object.keys(dirtyStates).filter(path => {
if (this.touchedFiles.has(path)) {
debug('Ignoring known touched file %s', path);
this.touchedFiles.delete(path);
return false;
}
return true;
});
for (const {main} of this.providers) {
dirtyPaths = dirtyPaths.filter(path => {
if (main.ignoreChange(path)) {
debug('Ignoring changed file %s', path);
return false;
}
return true;
});
}
const dirtyHelpersAndSources = [];
const dirtyTests = [];
for (const filePath of dirtyPaths) {
const {isIgnoredByWatcher, isTest} = classify(filePath, this.globs);
if (!isIgnoredByWatcher) {
if (isTest) {
dirtyTests.push(filePath);
} else {
dirtyHelpersAndSources.push(filePath);
}
}
}
const addedOrChangedTests = dirtyTests.filter(path => dirtyStates[path] !== 'unlink');
const unlinkedTests = diff(dirtyTests, addedOrChangedTests);
this.cleanUnlinkedTests(unlinkedTests);
// No need to rerun tests if the only change is that tests were deleted
if (unlinkedTests.length === dirtyPaths.length) {
return;
}
if (dirtyHelpersAndSources.length === 0) {
// Run any new or changed tests
this.run(addedOrChangedTests);
return;
}
// Try to find tests that depend on the changed source files
const testsByHelpersOrSource = dirtyHelpersAndSources.map(path => {
return this.testDependencies.filter(dep => dep.contains(path)).map(dep => {
debug('%s is a dependency of %s', path, dep.file);
return dep.file;
});
}, this).filter(tests => tests.length > 0);
// Rerun all tests if source files were changed that could not be traced to
// specific tests
if (testsByHelpersOrSource.length !== dirtyHelpersAndSources.length) {
debug('Files remain that cannot be traced to specific tests: %O', dirtyHelpersAndSources);
debug('Rerunning all tests');
this.run();
return;
}
// Run all affected tests
this.run([...new Set(addedOrChangedTests.concat(flatten(testsByHelpersOrSource)))]);
}
}
module.exports = Watcher;

47
node_modules/ava/lib/worker/dependency-tracker.js generated vendored Normal file
View file

@ -0,0 +1,47 @@
/* eslint-disable node/no-deprecated-api */
'use strict';
const ipc = require('./ipc');
const seenDependencies = new Set();
let newDependencies = [];
function flush() {
if (newDependencies.length === 0) {
return;
}
ipc.send({type: 'dependencies', dependencies: newDependencies});
newDependencies = [];
}
exports.flush = flush;
function track(filename) {
if (seenDependencies.has(filename)) {
return;
}
if (newDependencies.length === 0) {
process.nextTick(flush);
}
seenDependencies.add(filename);
newDependencies.push(filename);
}
exports.track = track;
function install(testPath) {
for (const ext of Object.keys(require.extensions)) {
const wrappedHandler = require.extensions[ext];
require.extensions[ext] = (module, filename) => {
if (filename !== testPath) {
track(filename);
}
wrappedHandler(module, filename);
};
}
}
exports.install = install;

18
node_modules/ava/lib/worker/ensure-forked.js generated vendored Normal file
View file

@ -0,0 +1,18 @@
'use strict';
const path = require('path');
const chalk = require('chalk'); // Use default Chalk instance.
// Check if the test is being run without AVA cli
const isForked = typeof process.send === 'function';
if (!isForked) {
if (process.argv[1]) {
const fp = path.relative('.', process.argv[1]);
console.log();
console.error(`Test files must be run with the AVA CLI:\n\n ${chalk.grey.dim('$')} ${chalk.cyan('ava ' + fp)}\n`);
process.exit(1); // eslint-disable-line unicorn/no-process-exit
} else {
throw new Error('The ava module can only be imported in test files');
}
}

56
node_modules/ava/lib/worker/ipc.js generated vendored Normal file
View file

@ -0,0 +1,56 @@
'use strict';
const Emittery = require('emittery');
const emitter = new Emittery();
process.on('message', message => {
if (!message.ava) {
return;
}
switch (message.ava.type) {
case 'options':
emitter.emit('options', message.ava.options);
break;
case 'peer-failed':
emitter.emit('peerFailed');
break;
case 'pong':
emitter.emit('pong');
break;
default:
break;
}
});
exports.options = emitter.once('options');
exports.peerFailed = emitter.once('peerFailed');
function send(evt) {
if (process.connected) {
process.send({ava: evt});
}
}
exports.send = send;
function unref() {
process.channel.unref();
}
exports.unref = unref;
let pendingPings = Promise.resolve();
async function flush() {
process.channel.ref();
const promise = pendingPings.then(async () => { // eslint-disable-line promise/prefer-await-to-then
send({type: 'ping'});
await emitter.once('pong');
if (promise === pendingPings) {
unref();
}
});
pendingPings = promise;
await promise;
}
exports.flush = flush;

90
node_modules/ava/lib/worker/line-numbers.js generated vendored Normal file
View file

@ -0,0 +1,90 @@
function parse(file) {
const fs = require('fs');
const acorn = require('acorn');
const walk = require('acorn-walk');
const ast = acorn.parse(fs.readFileSync(file, 'utf8'), {
ecmaVersion: 11,
locations: true
});
const locations = [];
walk.simple(ast, {
CallExpression(node) {
locations.push(node.loc);
}
});
// Walking is depth-first, but we want to sort these breadth-first.
locations.sort((a, b) => {
if (a.start.line === b.start.line) {
return a.start.column - b.start.column;
}
return a.start.line - b.start.line;
});
return locations;
}
function findTest(locations, declaration) {
// Find all calls that span the test declaration.
const spans = locations.filter(loc => {
if (loc.start.line > declaration.line || loc.end.line < declaration.line) {
return false;
}
if (loc.start.line === declaration.line && loc.start.column > declaration.column) {
return false;
}
if (loc.end.line === declaration.line && loc.end.column < declaration.column) {
return false;
}
return true;
});
// Locations should be sorted by source order, so the last span must be the test.
return spans.pop();
}
const range = (start, end) => new Array(end - start + 1).fill(start).map((element, index) => element + index);
module.exports = ({file, lineNumbers = []}) => {
if (lineNumbers.length === 0) {
return undefined;
}
// Avoid loading these until we actually need to select tests by line number.
const callsites = require('callsites');
const sourceMapSupport = require('source-map-support');
const locations = parse(file);
const selected = new Set(lineNumbers);
return () => {
// Assume this is called from a test declaration, which is located in the file.
// If not… don't select the test!
const callSite = callsites().find(callSite => callSite.getFileName() === file);
if (!callSite) {
return false;
}
// FIXME: This assumes the callSite hasn't already been adjusted. It's likely
// that if `source-map-support/register` has been loaded, this would result
// in the wrong location.
const sourceCallSite = sourceMapSupport.wrapCallSite(callSite);
const start = {
line: sourceCallSite.getLineNumber(),
column: sourceCallSite.getColumnNumber() - 1 // Use 0-indexed columns.
};
const test = findTest(locations, start);
if (!test) {
return false;
}
return range(test.start.line, test.end.line).some(line => selected.has(line));
};
};

21
node_modules/ava/lib/worker/main.js generated vendored Normal file
View file

@ -0,0 +1,21 @@
'use strict';
const runner = require('./subprocess').getRunner();
const makeCjsExport = () => {
function test(...args) {
return runner.chain(...args);
}
return Object.assign(test, runner.chain);
};
// Support CommonJS modules by exporting a test function that can be fully
// chained. Also support ES module loaders by exporting __esModule and a
// default. Support `import * as ava from 'ava'` use cases by exporting a
// `test` member. Do all this whilst preventing `test.test.test() or
// `test.default.test()` chains, though in CommonJS `test.test()` is
// unavoidable.
module.exports = Object.assign(makeCjsExport(), {
__esModule: true,
default: runner.chain
});

17
node_modules/ava/lib/worker/options.js generated vendored Normal file
View file

@ -0,0 +1,17 @@
'use strict';
let options = null;
exports.get = () => {
if (!options) {
throw new Error('Options have not yet been set');
}
return options;
};
exports.set = newOptions => {
if (options) {
throw new Error('Options have already been set');
}
options = newOptions;
};

235
node_modules/ava/lib/worker/subprocess.js generated vendored Normal file
View file

@ -0,0 +1,235 @@
'use strict';
const {pathToFileURL} = require('url');
const currentlyUnhandled = require('currently-unhandled')();
require('./ensure-forked'); // eslint-disable-line import/no-unassigned-import
const ipc = require('./ipc');
const supportsESM = async () => {
try {
await import('data:text/javascript,'); // eslint-disable-line node/no-unsupported-features/es-syntax
return true;
} catch {}
return false;
};
ipc.send({type: 'ready-for-options'});
ipc.options.then(async options => {
require('./options').set(options);
require('../chalk').set(options.chalkOptions);
if (options.chalkOptions.level > 0) {
const {stdout, stderr} = process;
global.console = Object.assign(global.console, new console.Console({stdout, stderr, colorMode: true}));
}
const nowAndTimers = require('../now-and-timers');
const providerManager = require('../provider-manager');
const Runner = require('../runner');
const serializeError = require('../serialize-error');
const dependencyTracking = require('./dependency-tracker');
const lineNumberSelection = require('./line-numbers');
async function exit(code) {
if (!process.exitCode) {
process.exitCode = code;
}
dependencyTracking.flush();
await ipc.flush();
process.exit(); // eslint-disable-line unicorn/no-process-exit
}
// TODO: Initialize providers here, then pass to lineNumberSelection() so they
// can be used to parse the test file.
let checkSelectedByLineNumbers;
try {
checkSelectedByLineNumbers = lineNumberSelection({
file: options.file,
lineNumbers: options.lineNumbers
});
} catch (error) {
ipc.send({type: 'line-number-selection-error', err: serializeError('Line number selection error', false, error, options.file)});
checkSelectedByLineNumbers = () => false;
}
const runner = new Runner({
checkSelectedByLineNumbers,
experiments: options.experiments,
failFast: options.failFast,
failWithoutAssertions: options.failWithoutAssertions,
file: options.file,
match: options.match,
projectDir: options.projectDir,
recordNewSnapshots: options.recordNewSnapshots,
runOnlyExclusive: options.runOnlyExclusive,
serial: options.serial,
snapshotDir: options.snapshotDir,
updateSnapshots: options.updateSnapshots
});
ipc.peerFailed.then(() => { // eslint-disable-line promise/prefer-await-to-then
runner.interrupt();
});
const attributedRejections = new Set();
process.on('unhandledRejection', (reason, promise) => {
if (runner.attributeLeakedError(reason)) {
attributedRejections.add(promise);
}
});
runner.on('dependency', dependencyTracking.track);
runner.on('stateChange', state => ipc.send(state));
runner.on('error', error => {
ipc.send({type: 'internal-error', err: serializeError('Internal runner error', false, error, runner.file)});
exit(1);
});
runner.on('finish', () => {
try {
const touchedFiles = runner.saveSnapshotState();
if (touchedFiles) {
ipc.send({type: 'touched-files', files: touchedFiles});
}
} catch (error) {
ipc.send({type: 'internal-error', err: serializeError('Internal runner error', false, error, runner.file)});
exit(1);
return;
}
nowAndTimers.setImmediate(() => {
currentlyUnhandled()
.filter(rejection => !attributedRejections.has(rejection.promise))
.forEach(rejection => {
ipc.send({type: 'unhandled-rejection', err: serializeError('Unhandled rejection', true, rejection.reason, runner.file)});
});
exit(0);
});
});
process.on('uncaughtException', error => {
if (runner.attributeLeakedError(error)) {
return;
}
ipc.send({type: 'uncaught-exception', err: serializeError('Uncaught exception', true, error, runner.file)});
exit(1);
});
let accessedRunner = false;
exports.getRunner = () => {
accessedRunner = true;
return runner;
};
// Store value to prevent required modules from modifying it.
const testPath = options.file;
// Install basic source map support.
const sourceMapSupport = require('source-map-support');
sourceMapSupport.install({
environment: 'node',
handleUncaughtExceptions: false
});
const extensionsToLoadAsModules = Object.entries(options.moduleTypes)
.filter(([, type]) => type === 'module')
.map(([extension]) => extension);
// Install before processing options.require, so if helpers are added to the
// require configuration the *compiled* helper will be loaded.
const {projectDir, providerStates = []} = options;
const providers = providerStates.map(({type, state}) => {
if (type === 'babel') {
const provider = providerManager.babel(projectDir).worker({extensionsToLoadAsModules, state});
runner.powerAssert = provider.powerAssert;
return provider;
}
if (type === 'typescript') {
return providerManager.typescript(projectDir).worker({extensionsToLoadAsModules, state});
}
return null;
}).filter(provider => provider !== null);
let requireFn = require;
let isESMSupported;
const load = async ref => {
for (const extension of extensionsToLoadAsModules) {
if (ref.endsWith(`.${extension}`)) {
if (typeof isESMSupported !== 'boolean') {
// Lazily determine support since this prints an experimental warning.
// eslint-disable-next-line no-await-in-loop
isESMSupported = await supportsESM();
}
if (isESMSupported) {
return import(pathToFileURL(ref)); // eslint-disable-line node/no-unsupported-features/es-syntax
}
ipc.send({type: 'internal-error', err: serializeError('Internal runner error', false, new Error('ECMAScript Modules are not supported in this Node.js version.'))});
exit(1);
return;
}
}
for (const provider of providers) {
if (provider.canLoad(ref)) {
return provider.load(ref, {requireFn});
}
}
return requireFn(ref);
};
try {
for await (const ref of (options.require || [])) {
const mod = await load(ref);
try {
if (Reflect.has(mod, Symbol.for('esm:package'))) {
requireFn = mod(module);
}
} catch (_) {}
}
// Install dependency tracker after the require configuration has been evaluated
// to make sure we also track dependencies with custom require hooks
dependencyTracking.install(testPath);
if (options.debug) {
require('inspector').open(options.debug.port, options.debug.host, true); // eslint-disable-line node/no-unsupported-features/node-builtins
if (options.debug.break) {
debugger; // eslint-disable-line no-debugger
}
}
await load(testPath);
if (accessedRunner) {
// Unreference the IPC channel if the test file required AVA. This stops it
// from keeping the event loop busy, which means the `beforeExit` event can be
// used to detect when tests stall.
ipc.unref();
} else {
ipc.send({type: 'missing-ava-import'});
exit(1);
}
} catch (error) {
ipc.send({type: 'uncaught-exception', err: serializeError('Uncaught exception', true, error, runner.file)});
exit(1);
}
}).catch(error => {
// There shouldn't be any errors, but if there are we may not have managed
// to bootstrap enough code to serialize them. Re-throw and let the process
// crash.
setImmediate(() => {
throw error;
});
});

9
node_modules/ava/license generated vendored Normal file
View file

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

121
node_modules/ava/node_modules/acorn-walk/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,121 @@
## 7.1.1 (2020-02-13)
### Bug fixes
Clean up the type definitions to actually work well with the main parser.
## 7.1.0 (2020-02-11)
### New features
Add a TypeScript definition file for the library.
## 7.0.0 (2017-08-12)
### New features
Support walking `ImportExpression` nodes.
## 6.2.0 (2017-07-04)
### New features
Add support for `Import` nodes.
## 6.1.0 (2018-09-28)
### New features
The walker now walks `TemplateElement` nodes.
## 6.0.1 (2018-09-14)
### Bug fixes
Fix bad "main" field in package.json.
## 6.0.0 (2018-09-14)
### Breaking changes
This is now a separate package, `acorn-walk`, rather than part of the main `acorn` package.
The `ScopeBody` and `ScopeExpression` meta-node-types are no longer supported.
## 5.7.1 (2018-06-15)
### Bug fixes
Make sure the walker and bin files are rebuilt on release (the previous release didn't get the up-to-date versions).
## 5.7.0 (2018-06-15)
### Bug fixes
Fix crash in walker when walking a binding-less catch node.
## 5.6.2 (2018-06-05)
### Bug fixes
In the walker, go back to allowing the `baseVisitor` argument to be null to default to the default base everywhere.
## 5.6.1 (2018-06-01)
### Bug fixes
Fix regression when passing `null` as fourth argument to `walk.recursive`.
## 5.6.0 (2018-05-31)
### Bug fixes
Fix a bug in the walker that caused a crash when walking an object pattern spread.
## 5.5.1 (2018-03-06)
### Bug fixes
Fix regression in walker causing property values in object patterns to be walked as expressions.
## 5.5.0 (2018-02-27)
### Bug fixes
Support object spread in the AST walker.
## 5.4.1 (2018-02-02)
### Bug fixes
5.4.0 somehow accidentally included an old version of walk.js.
## 5.2.0 (2017-10-30)
### Bug fixes
The `full` and `fullAncestor` walkers no longer visit nodes multiple times.
## 5.1.0 (2017-07-05)
### New features
New walker functions `full` and `fullAncestor`.
## 3.2.0 (2016-06-07)
### New features
Make it possible to use `visit.ancestor` with a walk state.
## 3.1.0 (2016-04-18)
### New features
The walker now allows defining handlers for `CatchClause` nodes.
## 2.5.2 (2015-10-27)
### Fixes
Fix bug where the walker walked an exported `let` statement as an expression.

19
node_modules/ava/node_modules/acorn-walk/LICENSE generated vendored Normal file
View file

@ -0,0 +1,19 @@
Copyright (C) 2012-2018 by various contributors (see AUTHORS)
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.

126
node_modules/ava/node_modules/acorn-walk/README.md generated vendored Normal file
View file

@ -0,0 +1,126 @@
# Acorn AST walker
An abstract syntax tree walker for the
[ESTree](https://github.com/estree/estree) format.
## Community
Acorn is open source software released under an
[MIT license](https://github.com/acornjs/acorn/blob/master/acorn-walk/LICENSE).
You are welcome to
[report bugs](https://github.com/acornjs/acorn/issues) or create pull
requests on [github](https://github.com/acornjs/acorn). For questions
and discussion, please use the
[Tern discussion forum](https://discuss.ternjs.net).
## Installation
The easiest way to install acorn is from [`npm`](https://www.npmjs.com/):
```sh
npm install acorn-walk
```
Alternately, you can download the source and build acorn yourself:
```sh
git clone https://github.com/acornjs/acorn.git
cd acorn
npm install
```
## Interface
An algorithm for recursing through a syntax tree is stored as an
object, with a property for each tree node type holding a function
that will recurse through such a node. There are several ways to run
such a walker.
**simple**`(node, visitors, base, state)` does a 'simple' walk over a
tree. `node` should be the AST node to walk, and `visitors` an object
with properties whose names correspond to node types in the [ESTree
spec](https://github.com/estree/estree). The properties should contain
functions that will be called with the node object and, if applicable
the state at that point. The last two arguments are optional. `base`
is a walker algorithm, and `state` is a start state. The default
walker will simply visit all statements and expressions and not
produce a meaningful state. (An example of a use of state is to track
scope at each point in the tree.)
```js
const acorn = require("acorn")
const walk = require("acorn-walk")
walk.simple(acorn.parse("let x = 10"), {
Literal(node) {
console.log(`Found a literal: ${node.value}`)
}
})
```
**ancestor**`(node, visitors, base, state)` does a 'simple' walk over
a tree, building up an array of ancestor nodes (including the current node)
and passing the array to the callbacks as a third parameter.
```js
const acorn = require("acorn")
const walk = require("acorn-walk")
walk.ancestor(acorn.parse("foo('hi')"), {
Literal(_, ancestors) {
console.log("This literal's ancestors are:", ancestors.map(n => n.type))
}
})
```
**recursive**`(node, state, functions, base)` does a 'recursive'
walk, where the walker functions are responsible for continuing the
walk on the child nodes of their target node. `state` is the start
state, and `functions` should contain an object that maps node types
to walker functions. Such functions are called with `(node, state, c)`
arguments, and can cause the walk to continue on a sub-node by calling
the `c` argument on it with `(node, state)` arguments. The optional
`base` argument provides the fallback walker functions for node types
that aren't handled in the `functions` object. If not given, the
default walkers will be used.
**make**`(functions, base)` builds a new walker object by using the
walker functions in `functions` and filling in the missing ones by
taking defaults from `base`.
**full**`(node, callback, base, state)` does a 'full' walk over a
tree, calling the callback with the arguments (node, state, type) for
each node
**fullAncestor**`(node, callback, base, state)` does a 'full' walk
over a tree, building up an array of ancestor nodes (including the
current node) and passing the array to the callbacks as a third
parameter.
```js
const acorn = require("acorn")
const walk = require("acorn-walk")
walk.full(acorn.parse("1 + 1"), node => {
console.log(`There's a ${node.type} node at ${node.ch}`)
})
```
**findNodeAt**`(node, start, end, test, base, state)` tries to locate
a node in a tree at the given start and/or end offsets, which
satisfies the predicate `test`. `start` and `end` can be either `null`
(as wildcard) or a number. `test` may be a string (indicating a node
type) or a function that takes `(nodeType, node)` arguments and
returns a boolean indicating whether this node is interesting. `base`
and `state` are optional, and can be used to specify a custom walker.
Nodes are tested from inner to outer, so if two nodes match the
boundaries, the inner one will be preferred.
**findNodeAround**`(node, pos, test, base, state)` is a lot like
`findNodeAt`, but will match any node that exists 'around' (spanning)
the given position.
**findNodeAfter**`(node, pos, test, base, state)` is similar to
`findNodeAround`, but will match all nodes *after* the given position
(testing outer nodes before inner nodes).

115
node_modules/ava/node_modules/acorn-walk/dist/walk.d.ts generated vendored Normal file
View file

@ -0,0 +1,115 @@
import {Node} from 'acorn';
declare module "acorn-walk" {
type FullWalkerCallback<TState> = (
node: Node,
state: TState,
type: string
) => void;
type FullAncestorWalkerCallback<TState> = (
node: Node,
state: TState | Node[],
ancestors: Node[],
type: string
) => void;
type WalkerCallback<TState> = (node: Node, state: TState) => void;
type SimpleWalkerFn<TState> = (
node: Node,
state: TState
) => void;
type AncestorWalkerFn<TState> = (
node: Node,
state: TState| Node[],
ancestors: Node[]
) => void;
type RecursiveWalkerFn<TState> = (
node: Node,
state: TState,
callback: WalkerCallback<TState>
) => void;
type SimpleVisitors<TState> = {
[type: string]: SimpleWalkerFn<TState>
};
type AncestorVisitors<TState> = {
[type: string]: AncestorWalkerFn<TState>
};
type RecursiveVisitors<TState> = {
[type: string]: RecursiveWalkerFn<TState>
};
type FindPredicate = (type: string, node: Node) => boolean;
interface Found<TState> {
node: Node,
state: TState
}
export function simple<TState>(
node: Node,
visitors: SimpleVisitors<TState>,
base?: RecursiveVisitors<TState>,
state?: TState
): void;
export function ancestor<TState>(
node: Node,
visitors: AncestorVisitors<TState>,
base?: RecursiveVisitors<TState>,
state?: TState
): void;
export function recursive<TState>(
node: Node,
state: TState,
functions: RecursiveVisitors<TState>,
base?: RecursiveVisitors<TState>
): void;
export function full<TState>(
node: Node,
callback: FullWalkerCallback<TState>,
base?: RecursiveVisitors<TState>,
state?: TState
): void;
export function fullAncestor<TState>(
node: Node,
callback: FullAncestorWalkerCallback<TState>,
base?: RecursiveVisitors<TState>,
state?: TState
): void;
export function make<TState>(
functions: RecursiveVisitors<TState>,
base?: RecursiveVisitors<TState>
): RecursiveVisitors<TState>;
export function findNodeAt<TState>(
node: Node,
start: number | undefined,
end: number | undefined,
type: string,
base?: RecursiveVisitors<TState>,
state?: TState
): Found<TState> | undefined;
export function findNodeAt<TState>(
node: Node,
start: number | undefined,
end: number | undefined,
type?: FindPredicate,
base?: RecursiveVisitors<TState>,
state?: TState
): Found<TState> | undefined;
export const findNodeAround: typeof findNodeAt;
export const findNodeAfter: typeof findNodeAt;
}

461
node_modules/ava/node_modules/acorn-walk/dist/walk.js generated vendored Normal file
View file

@ -0,0 +1,461 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory((global.acorn = global.acorn || {}, global.acorn.walk = {})));
}(this, function (exports) { 'use strict';
// AST walker module for Mozilla Parser API compatible trees
// A simple walk is one where you simply specify callbacks to be
// called on specific nodes. The last two arguments are optional. A
// simple use would be
//
// walk.simple(myTree, {
// Expression: function(node) { ... }
// });
//
// to do something with all expressions. All Parser API node types
// can be used to identify node types, as well as Expression and
// Statement, which denote categories of nodes.
//
// The base argument can be used to pass a custom (recursive)
// walker, and state can be used to give this walked an initial
// state.
function simple(node, visitors, baseVisitor, state, override) {
if (!baseVisitor) { baseVisitor = base
; }(function c(node, st, override) {
var type = override || node.type, found = visitors[type];
baseVisitor[type](node, st, c);
if (found) { found(node, st); }
})(node, state, override);
}
// An ancestor walk keeps an array of ancestor nodes (including the
// current node) and passes them to the callback as third parameter
// (and also as state parameter when no other state is present).
function ancestor(node, visitors, baseVisitor, state, override) {
var ancestors = [];
if (!baseVisitor) { baseVisitor = base
; }(function c(node, st, override) {
var type = override || node.type, found = visitors[type];
var isNew = node !== ancestors[ancestors.length - 1];
if (isNew) { ancestors.push(node); }
baseVisitor[type](node, st, c);
if (found) { found(node, st || ancestors, ancestors); }
if (isNew) { ancestors.pop(); }
})(node, state, override);
}
// A recursive walk is one where your functions override the default
// walkers. They can modify and replace the state parameter that's
// threaded through the walk, and can opt how and whether to walk
// their child nodes (by calling their third argument on these
// nodes).
function recursive(node, state, funcs, baseVisitor, override) {
var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor
;(function c(node, st, override) {
visitor[override || node.type](node, st, c);
})(node, state, override);
}
function makeTest(test) {
if (typeof test === "string")
{ return function (type) { return type === test; } }
else if (!test)
{ return function () { return true; } }
else
{ return test }
}
var Found = function Found(node, state) { this.node = node; this.state = state; };
// A full walk triggers the callback on each node
function full(node, callback, baseVisitor, state, override) {
if (!baseVisitor) { baseVisitor = base
; }(function c(node, st, override) {
var type = override || node.type;
baseVisitor[type](node, st, c);
if (!override) { callback(node, st, type); }
})(node, state, override);
}
// An fullAncestor walk is like an ancestor walk, but triggers
// the callback on each node
function fullAncestor(node, callback, baseVisitor, state) {
if (!baseVisitor) { baseVisitor = base; }
var ancestors = []
;(function c(node, st, override) {
var type = override || node.type;
var isNew = node !== ancestors[ancestors.length - 1];
if (isNew) { ancestors.push(node); }
baseVisitor[type](node, st, c);
if (!override) { callback(node, st || ancestors, ancestors, type); }
if (isNew) { ancestors.pop(); }
})(node, state);
}
// Find a node with a given start, end, and type (all are optional,
// null can be used as wildcard). Returns a {node, state} object, or
// undefined when it doesn't find a matching node.
function findNodeAt(node, start, end, test, baseVisitor, state) {
if (!baseVisitor) { baseVisitor = base; }
test = makeTest(test);
try {
(function c(node, st, override) {
var type = override || node.type;
if ((start == null || node.start <= start) &&
(end == null || node.end >= end))
{ baseVisitor[type](node, st, c); }
if ((start == null || node.start === start) &&
(end == null || node.end === end) &&
test(type, node))
{ throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the innermost node of a given type that contains the given
// position. Interface similar to findNodeAt.
function findNodeAround(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
var type = override || node.type;
if (node.start > pos || node.end < pos) { return }
baseVisitor[type](node, st, c);
if (test(type, node)) { throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the outermost matching node after a given position.
function findNodeAfter(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
if (node.end < pos) { return }
var type = override || node.type;
if (node.start >= pos && test(type, node)) { throw new Found(node, st) }
baseVisitor[type](node, st, c);
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the outermost matching node before a given position.
function findNodeBefore(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
var max
;(function c(node, st, override) {
if (node.start > pos) { return }
var type = override || node.type;
if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
{ max = new Found(node, st); }
baseVisitor[type](node, st, c);
})(node, state);
return max
}
// Fallback to an Object.create polyfill for older environments.
var create = Object.create || function(proto) {
function Ctor() {}
Ctor.prototype = proto;
return new Ctor
};
// Used to create a custom walker. Will fill in all missing node
// type properties with the defaults.
function make(funcs, baseVisitor) {
var visitor = create(baseVisitor || base);
for (var type in funcs) { visitor[type] = funcs[type]; }
return visitor
}
function skipThrough(node, st, c) { c(node, st); }
function ignore(_node, _st, _c) {}
// Node walkers.
var base = {};
base.Program = base.BlockStatement = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var stmt = list[i];
c(stmt, st, "Statement");
}
};
base.Statement = skipThrough;
base.EmptyStatement = ignore;
base.ExpressionStatement = base.ParenthesizedExpression =
function (node, st, c) { return c(node.expression, st, "Expression"); };
base.IfStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Statement");
if (node.alternate) { c(node.alternate, st, "Statement"); }
};
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
base.BreakStatement = base.ContinueStatement = ignore;
base.WithStatement = function (node, st, c) {
c(node.object, st, "Expression");
c(node.body, st, "Statement");
};
base.SwitchStatement = function (node, st, c) {
c(node.discriminant, st, "Expression");
for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
var cs = list$1[i$1];
if (cs.test) { c(cs.test, st, "Expression"); }
for (var i = 0, list = cs.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
}
};
base.SwitchCase = function (node, st, c) {
if (node.test) { c(node.test, st, "Expression"); }
for (var i = 0, list = node.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
};
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
if (node.argument) { c(node.argument, st, "Expression"); }
};
base.ThrowStatement = base.SpreadElement =
function (node, st, c) { return c(node.argument, st, "Expression"); };
base.TryStatement = function (node, st, c) {
c(node.block, st, "Statement");
if (node.handler) { c(node.handler, st); }
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
};
base.CatchClause = function (node, st, c) {
if (node.param) { c(node.param, st, "Pattern"); }
c(node.body, st, "Statement");
};
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.body, st, "Statement");
};
base.ForStatement = function (node, st, c) {
if (node.init) { c(node.init, st, "ForInit"); }
if (node.test) { c(node.test, st, "Expression"); }
if (node.update) { c(node.update, st, "Expression"); }
c(node.body, st, "Statement");
};
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
c(node.left, st, "ForInit");
c(node.right, st, "Expression");
c(node.body, st, "Statement");
};
base.ForInit = function (node, st, c) {
if (node.type === "VariableDeclaration") { c(node, st); }
else { c(node, st, "Expression"); }
};
base.DebuggerStatement = ignore;
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
base.VariableDeclaration = function (node, st, c) {
for (var i = 0, list = node.declarations; i < list.length; i += 1)
{
var decl = list[i];
c(decl, st);
}
};
base.VariableDeclarator = function (node, st, c) {
c(node.id, st, "Pattern");
if (node.init) { c(node.init, st, "Expression"); }
};
base.Function = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
for (var i = 0, list = node.params; i < list.length; i += 1)
{
var param = list[i];
c(param, st, "Pattern");
}
c(node.body, st, node.expression ? "Expression" : "Statement");
};
base.Pattern = function (node, st, c) {
if (node.type === "Identifier")
{ c(node, st, "VariablePattern"); }
else if (node.type === "MemberExpression")
{ c(node, st, "MemberPattern"); }
else
{ c(node, st); }
};
base.VariablePattern = ignore;
base.MemberPattern = skipThrough;
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
base.ArrayPattern = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Pattern"); }
}
};
base.ObjectPattern = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
if (prop.type === "Property") {
if (prop.computed) { c(prop.key, st, "Expression"); }
c(prop.value, st, "Pattern");
} else if (prop.type === "RestElement") {
c(prop.argument, st, "Pattern");
}
}
};
base.Expression = skipThrough;
base.ThisExpression = base.Super = base.MetaProperty = ignore;
base.ArrayExpression = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Expression"); }
}
};
base.ObjectExpression = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1)
{
var prop = list[i];
c(prop, st);
}
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function (node, st, c) {
for (var i = 0, list = node.expressions; i < list.length; i += 1)
{
var expr = list[i];
c(expr, st, "Expression");
}
};
base.TemplateLiteral = function (node, st, c) {
for (var i = 0, list = node.quasis; i < list.length; i += 1)
{
var quasi = list[i];
c(quasi, st);
}
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
{
var expr = list$1[i$1];
c(expr, st, "Expression");
}
};
base.TemplateElement = ignore;
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
c(node.argument, st, "Expression");
};
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
c(node.left, st, "Expression");
c(node.right, st, "Expression");
};
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
c(node.left, st, "Pattern");
c(node.right, st, "Expression");
};
base.ConditionalExpression = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Expression");
c(node.alternate, st, "Expression");
};
base.NewExpression = base.CallExpression = function (node, st, c) {
c(node.callee, st, "Expression");
if (node.arguments)
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
{
var arg = list[i];
c(arg, st, "Expression");
} }
};
base.MemberExpression = function (node, st, c) {
c(node.object, st, "Expression");
if (node.computed) { c(node.property, st, "Expression"); }
};
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
if (node.declaration)
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
if (node.source) { c(node.source, st, "Expression"); }
};
base.ExportAllDeclaration = function (node, st, c) {
c(node.source, st, "Expression");
};
base.ImportDeclaration = function (node, st, c) {
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
{
var spec = list[i];
c(spec, st);
}
c(node.source, st, "Expression");
};
base.ImportExpression = function (node, st, c) {
c(node.source, st, "Expression");
};
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;
base.TaggedTemplateExpression = function (node, st, c) {
c(node.tag, st, "Expression");
c(node.quasi, st, "Expression");
};
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
base.Class = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
if (node.superClass) { c(node.superClass, st, "Expression"); }
c(node.body, st);
};
base.ClassBody = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var elt = list[i];
c(elt, st);
}
};
base.MethodDefinition = base.Property = function (node, st, c) {
if (node.computed) { c(node.key, st, "Expression"); }
c(node.value, st, "Expression");
};
exports.ancestor = ancestor;
exports.base = base;
exports.findNodeAfter = findNodeAfter;
exports.findNodeAround = findNodeAround;
exports.findNodeAt = findNodeAt;
exports.findNodeBefore = findNodeBefore;
exports.full = full;
exports.fullAncestor = fullAncestor;
exports.make = make;
exports.recursive = recursive;
exports.simple = simple;
Object.defineProperty(exports, '__esModule', { value: true });
}));

File diff suppressed because one or more lines are too long

441
node_modules/ava/node_modules/acorn-walk/dist/walk.mjs generated vendored Normal file
View file

@ -0,0 +1,441 @@
// AST walker module for Mozilla Parser API compatible trees
// A simple walk is one where you simply specify callbacks to be
// called on specific nodes. The last two arguments are optional. A
// simple use would be
//
// walk.simple(myTree, {
// Expression: function(node) { ... }
// });
//
// to do something with all expressions. All Parser API node types
// can be used to identify node types, as well as Expression and
// Statement, which denote categories of nodes.
//
// The base argument can be used to pass a custom (recursive)
// walker, and state can be used to give this walked an initial
// state.
function simple(node, visitors, baseVisitor, state, override) {
if (!baseVisitor) { baseVisitor = base
; }(function c(node, st, override) {
var type = override || node.type, found = visitors[type];
baseVisitor[type](node, st, c);
if (found) { found(node, st); }
})(node, state, override);
}
// An ancestor walk keeps an array of ancestor nodes (including the
// current node) and passes them to the callback as third parameter
// (and also as state parameter when no other state is present).
function ancestor(node, visitors, baseVisitor, state, override) {
var ancestors = [];
if (!baseVisitor) { baseVisitor = base
; }(function c(node, st, override) {
var type = override || node.type, found = visitors[type];
var isNew = node !== ancestors[ancestors.length - 1];
if (isNew) { ancestors.push(node); }
baseVisitor[type](node, st, c);
if (found) { found(node, st || ancestors, ancestors); }
if (isNew) { ancestors.pop(); }
})(node, state, override);
}
// A recursive walk is one where your functions override the default
// walkers. They can modify and replace the state parameter that's
// threaded through the walk, and can opt how and whether to walk
// their child nodes (by calling their third argument on these
// nodes).
function recursive(node, state, funcs, baseVisitor, override) {
var visitor = funcs ? make(funcs, baseVisitor || undefined) : baseVisitor
;(function c(node, st, override) {
visitor[override || node.type](node, st, c);
})(node, state, override);
}
function makeTest(test) {
if (typeof test === "string")
{ return function (type) { return type === test; } }
else if (!test)
{ return function () { return true; } }
else
{ return test }
}
var Found = function Found(node, state) { this.node = node; this.state = state; };
// A full walk triggers the callback on each node
function full(node, callback, baseVisitor, state, override) {
if (!baseVisitor) { baseVisitor = base
; }(function c(node, st, override) {
var type = override || node.type;
baseVisitor[type](node, st, c);
if (!override) { callback(node, st, type); }
})(node, state, override);
}
// An fullAncestor walk is like an ancestor walk, but triggers
// the callback on each node
function fullAncestor(node, callback, baseVisitor, state) {
if (!baseVisitor) { baseVisitor = base; }
var ancestors = []
;(function c(node, st, override) {
var type = override || node.type;
var isNew = node !== ancestors[ancestors.length - 1];
if (isNew) { ancestors.push(node); }
baseVisitor[type](node, st, c);
if (!override) { callback(node, st || ancestors, ancestors, type); }
if (isNew) { ancestors.pop(); }
})(node, state);
}
// Find a node with a given start, end, and type (all are optional,
// null can be used as wildcard). Returns a {node, state} object, or
// undefined when it doesn't find a matching node.
function findNodeAt(node, start, end, test, baseVisitor, state) {
if (!baseVisitor) { baseVisitor = base; }
test = makeTest(test);
try {
(function c(node, st, override) {
var type = override || node.type;
if ((start == null || node.start <= start) &&
(end == null || node.end >= end))
{ baseVisitor[type](node, st, c); }
if ((start == null || node.start === start) &&
(end == null || node.end === end) &&
test(type, node))
{ throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the innermost node of a given type that contains the given
// position. Interface similar to findNodeAt.
function findNodeAround(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
var type = override || node.type;
if (node.start > pos || node.end < pos) { return }
baseVisitor[type](node, st, c);
if (test(type, node)) { throw new Found(node, st) }
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the outermost matching node after a given position.
function findNodeAfter(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
try {
(function c(node, st, override) {
if (node.end < pos) { return }
var type = override || node.type;
if (node.start >= pos && test(type, node)) { throw new Found(node, st) }
baseVisitor[type](node, st, c);
})(node, state);
} catch (e) {
if (e instanceof Found) { return e }
throw e
}
}
// Find the outermost matching node before a given position.
function findNodeBefore(node, pos, test, baseVisitor, state) {
test = makeTest(test);
if (!baseVisitor) { baseVisitor = base; }
var max
;(function c(node, st, override) {
if (node.start > pos) { return }
var type = override || node.type;
if (node.end <= pos && (!max || max.node.end < node.end) && test(type, node))
{ max = new Found(node, st); }
baseVisitor[type](node, st, c);
})(node, state);
return max
}
// Fallback to an Object.create polyfill for older environments.
var create = Object.create || function(proto) {
function Ctor() {}
Ctor.prototype = proto;
return new Ctor
};
// Used to create a custom walker. Will fill in all missing node
// type properties with the defaults.
function make(funcs, baseVisitor) {
var visitor = create(baseVisitor || base);
for (var type in funcs) { visitor[type] = funcs[type]; }
return visitor
}
function skipThrough(node, st, c) { c(node, st); }
function ignore(_node, _st, _c) {}
// Node walkers.
var base = {};
base.Program = base.BlockStatement = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var stmt = list[i];
c(stmt, st, "Statement");
}
};
base.Statement = skipThrough;
base.EmptyStatement = ignore;
base.ExpressionStatement = base.ParenthesizedExpression =
function (node, st, c) { return c(node.expression, st, "Expression"); };
base.IfStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Statement");
if (node.alternate) { c(node.alternate, st, "Statement"); }
};
base.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
base.BreakStatement = base.ContinueStatement = ignore;
base.WithStatement = function (node, st, c) {
c(node.object, st, "Expression");
c(node.body, st, "Statement");
};
base.SwitchStatement = function (node, st, c) {
c(node.discriminant, st, "Expression");
for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
var cs = list$1[i$1];
if (cs.test) { c(cs.test, st, "Expression"); }
for (var i = 0, list = cs.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
}
};
base.SwitchCase = function (node, st, c) {
if (node.test) { c(node.test, st, "Expression"); }
for (var i = 0, list = node.consequent; i < list.length; i += 1)
{
var cons = list[i];
c(cons, st, "Statement");
}
};
base.ReturnStatement = base.YieldExpression = base.AwaitExpression = function (node, st, c) {
if (node.argument) { c(node.argument, st, "Expression"); }
};
base.ThrowStatement = base.SpreadElement =
function (node, st, c) { return c(node.argument, st, "Expression"); };
base.TryStatement = function (node, st, c) {
c(node.block, st, "Statement");
if (node.handler) { c(node.handler, st); }
if (node.finalizer) { c(node.finalizer, st, "Statement"); }
};
base.CatchClause = function (node, st, c) {
if (node.param) { c(node.param, st, "Pattern"); }
c(node.body, st, "Statement");
};
base.WhileStatement = base.DoWhileStatement = function (node, st, c) {
c(node.test, st, "Expression");
c(node.body, st, "Statement");
};
base.ForStatement = function (node, st, c) {
if (node.init) { c(node.init, st, "ForInit"); }
if (node.test) { c(node.test, st, "Expression"); }
if (node.update) { c(node.update, st, "Expression"); }
c(node.body, st, "Statement");
};
base.ForInStatement = base.ForOfStatement = function (node, st, c) {
c(node.left, st, "ForInit");
c(node.right, st, "Expression");
c(node.body, st, "Statement");
};
base.ForInit = function (node, st, c) {
if (node.type === "VariableDeclaration") { c(node, st); }
else { c(node, st, "Expression"); }
};
base.DebuggerStatement = ignore;
base.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
base.VariableDeclaration = function (node, st, c) {
for (var i = 0, list = node.declarations; i < list.length; i += 1)
{
var decl = list[i];
c(decl, st);
}
};
base.VariableDeclarator = function (node, st, c) {
c(node.id, st, "Pattern");
if (node.init) { c(node.init, st, "Expression"); }
};
base.Function = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
for (var i = 0, list = node.params; i < list.length; i += 1)
{
var param = list[i];
c(param, st, "Pattern");
}
c(node.body, st, node.expression ? "Expression" : "Statement");
};
base.Pattern = function (node, st, c) {
if (node.type === "Identifier")
{ c(node, st, "VariablePattern"); }
else if (node.type === "MemberExpression")
{ c(node, st, "MemberPattern"); }
else
{ c(node, st); }
};
base.VariablePattern = ignore;
base.MemberPattern = skipThrough;
base.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
base.ArrayPattern = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Pattern"); }
}
};
base.ObjectPattern = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1) {
var prop = list[i];
if (prop.type === "Property") {
if (prop.computed) { c(prop.key, st, "Expression"); }
c(prop.value, st, "Pattern");
} else if (prop.type === "RestElement") {
c(prop.argument, st, "Pattern");
}
}
};
base.Expression = skipThrough;
base.ThisExpression = base.Super = base.MetaProperty = ignore;
base.ArrayExpression = function (node, st, c) {
for (var i = 0, list = node.elements; i < list.length; i += 1) {
var elt = list[i];
if (elt) { c(elt, st, "Expression"); }
}
};
base.ObjectExpression = function (node, st, c) {
for (var i = 0, list = node.properties; i < list.length; i += 1)
{
var prop = list[i];
c(prop, st);
}
};
base.FunctionExpression = base.ArrowFunctionExpression = base.FunctionDeclaration;
base.SequenceExpression = function (node, st, c) {
for (var i = 0, list = node.expressions; i < list.length; i += 1)
{
var expr = list[i];
c(expr, st, "Expression");
}
};
base.TemplateLiteral = function (node, st, c) {
for (var i = 0, list = node.quasis; i < list.length; i += 1)
{
var quasi = list[i];
c(quasi, st);
}
for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
{
var expr = list$1[i$1];
c(expr, st, "Expression");
}
};
base.TemplateElement = ignore;
base.UnaryExpression = base.UpdateExpression = function (node, st, c) {
c(node.argument, st, "Expression");
};
base.BinaryExpression = base.LogicalExpression = function (node, st, c) {
c(node.left, st, "Expression");
c(node.right, st, "Expression");
};
base.AssignmentExpression = base.AssignmentPattern = function (node, st, c) {
c(node.left, st, "Pattern");
c(node.right, st, "Expression");
};
base.ConditionalExpression = function (node, st, c) {
c(node.test, st, "Expression");
c(node.consequent, st, "Expression");
c(node.alternate, st, "Expression");
};
base.NewExpression = base.CallExpression = function (node, st, c) {
c(node.callee, st, "Expression");
if (node.arguments)
{ for (var i = 0, list = node.arguments; i < list.length; i += 1)
{
var arg = list[i];
c(arg, st, "Expression");
} }
};
base.MemberExpression = function (node, st, c) {
c(node.object, st, "Expression");
if (node.computed) { c(node.property, st, "Expression"); }
};
base.ExportNamedDeclaration = base.ExportDefaultDeclaration = function (node, st, c) {
if (node.declaration)
{ c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
if (node.source) { c(node.source, st, "Expression"); }
};
base.ExportAllDeclaration = function (node, st, c) {
c(node.source, st, "Expression");
};
base.ImportDeclaration = function (node, st, c) {
for (var i = 0, list = node.specifiers; i < list.length; i += 1)
{
var spec = list[i];
c(spec, st);
}
c(node.source, st, "Expression");
};
base.ImportExpression = function (node, st, c) {
c(node.source, st, "Expression");
};
base.ImportSpecifier = base.ImportDefaultSpecifier = base.ImportNamespaceSpecifier = base.Identifier = base.Literal = ignore;
base.TaggedTemplateExpression = function (node, st, c) {
c(node.tag, st, "Expression");
c(node.quasi, st, "Expression");
};
base.ClassDeclaration = base.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
base.Class = function (node, st, c) {
if (node.id) { c(node.id, st, "Pattern"); }
if (node.superClass) { c(node.superClass, st, "Expression"); }
c(node.body, st);
};
base.ClassBody = function (node, st, c) {
for (var i = 0, list = node.body; i < list.length; i += 1)
{
var elt = list[i];
c(elt, st);
}
};
base.MethodDefinition = base.Property = function (node, st, c) {
if (node.computed) { c(node.key, st, "Expression"); }
c(node.value, st, "Expression");
};
export { ancestor, base, findNodeAfter, findNodeAround, findNodeAt, findNodeBefore, full, fullAncestor, make, recursive, simple };

File diff suppressed because one or more lines are too long

36
node_modules/ava/node_modules/acorn-walk/package.json generated vendored Normal file
View file

@ -0,0 +1,36 @@
{
"name": "acorn-walk",
"description": "ECMAScript (ESTree) AST walker",
"homepage": "https://github.com/acornjs/acorn",
"main": "dist/walk.js",
"types": "dist/walk.d.ts",
"module": "dist/walk.mjs",
"version": "7.1.1",
"engines": {
"node": ">=0.4.0"
},
"maintainers": [
{
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"web": "https://marijnhaverbeke.nl"
},
{
"name": "Ingvar Stepanyan",
"email": "me@rreverser.com",
"web": "https://rreverser.com/"
},
{
"name": "Adrian Heine",
"web": "http://adrianheine.de"
}
],
"repository": {
"type": "git",
"url": "https://github.com/acornjs/acorn.git"
},
"scripts": {
"prepare": "cd ..; npm run build:walk"
},
"license": "MIT"
}

197
node_modules/ava/node_modules/ansi-styles/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,197 @@
import * as cssColors from 'color-name';
declare namespace ansiStyles {
interface ColorConvert {
/**
The RGB color space.
@param red - (`0`-`255`)
@param green - (`0`-`255`)
@param blue - (`0`-`255`)
*/
rgb(red: number, green: number, blue: number): string;
/**
The RGB HEX color space.
@param hex - A hexadecimal string containing RGB data.
*/
hex(hex: string): string;
/**
@param keyword - A CSS color name.
*/
keyword(keyword: keyof typeof cssColors): string;
/**
The HSL color space.
@param hue - (`0`-`360`)
@param saturation - (`0`-`100`)
@param lightness - (`0`-`100`)
*/
hsl(hue: number, saturation: number, lightness: number): string;
/**
The HSV color space.
@param hue - (`0`-`360`)
@param saturation - (`0`-`100`)
@param value - (`0`-`100`)
*/
hsv(hue: number, saturation: number, value: number): string;
/**
The HSV color space.
@param hue - (`0`-`360`)
@param whiteness - (`0`-`100`)
@param blackness - (`0`-`100`)
*/
hwb(hue: number, whiteness: number, blackness: number): string;
/**
Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color.
*/
ansi(ansi: number): string;
/**
Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
*/
ansi256(ansi: number): string;
}
interface CSPair {
/**
The ANSI terminal control sequence for starting this style.
*/
readonly open: string;
/**
The ANSI terminal control sequence for ending this style.
*/
readonly close: string;
}
interface ColorBase {
readonly ansi: ColorConvert;
readonly ansi256: ColorConvert;
readonly ansi16m: ColorConvert;
/**
The ANSI terminal control sequence for ending this color.
*/
readonly close: string;
}
interface Modifier {
/**
Resets the current color chain.
*/
readonly reset: CSPair;
/**
Make text bold.
*/
readonly bold: CSPair;
/**
Emitting only a small amount of light.
*/
readonly dim: CSPair;
/**
Make text italic. (Not widely supported)
*/
readonly italic: CSPair;
/**
Make text underline. (Not widely supported)
*/
readonly underline: CSPair;
/**
Inverse background and foreground colors.
*/
readonly inverse: CSPair;
/**
Prints the text, but makes it invisible.
*/
readonly hidden: CSPair;
/**
Puts a horizontal line through the center of the text. (Not widely supported)
*/
readonly strikethrough: CSPair;
}
interface ForegroundColor {
readonly black: CSPair;
readonly red: CSPair;
readonly green: CSPair;
readonly yellow: CSPair;
readonly blue: CSPair;
readonly cyan: CSPair;
readonly magenta: CSPair;
readonly white: CSPair;
/**
Alias for `blackBright`.
*/
readonly gray: CSPair;
/**
Alias for `blackBright`.
*/
readonly grey: CSPair;
readonly blackBright: CSPair;
readonly redBright: CSPair;
readonly greenBright: CSPair;
readonly yellowBright: CSPair;
readonly blueBright: CSPair;
readonly cyanBright: CSPair;
readonly magentaBright: CSPair;
readonly whiteBright: CSPair;
}
interface BackgroundColor {
readonly bgBlack: CSPair;
readonly bgRed: CSPair;
readonly bgGreen: CSPair;
readonly bgYellow: CSPair;
readonly bgBlue: CSPair;
readonly bgCyan: CSPair;
readonly bgMagenta: CSPair;
readonly bgWhite: CSPair;
/**
Alias for `bgBlackBright`.
*/
readonly bgGray: CSPair;
/**
Alias for `bgBlackBright`.
*/
readonly bgGrey: CSPair;
readonly bgBlackBright: CSPair;
readonly bgRedBright: CSPair;
readonly bgGreenBright: CSPair;
readonly bgYellowBright: CSPair;
readonly bgBlueBright: CSPair;
readonly bgCyanBright: CSPair;
readonly bgMagentaBright: CSPair;
readonly bgWhiteBright: CSPair;
}
}
declare const ansiStyles: {
readonly modifier: ansiStyles.Modifier;
readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase;
readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase;
readonly codes: ReadonlyMap<number, number>;
} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier;
export = ansiStyles;

163
node_modules/ava/node_modules/ansi-styles/index.js generated vendored Normal file
View file

@ -0,0 +1,163 @@
'use strict';
const wrapAnsi16 = (fn, offset) => (...args) => {
const code = fn(...args);
return `\u001B[${code + offset}m`;
};
const wrapAnsi256 = (fn, offset) => (...args) => {
const code = fn(...args);
return `\u001B[${38 + offset};5;${code}m`;
};
const wrapAnsi16m = (fn, offset) => (...args) => {
const rgb = fn(...args);
return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
};
const ansi2ansi = n => n;
const rgb2rgb = (r, g, b) => [r, g, b];
const setLazyProperty = (object, property, get) => {
Object.defineProperty(object, property, {
get: () => {
const value = get();
Object.defineProperty(object, property, {
value,
enumerable: true,
configurable: true
});
return value;
},
enumerable: true,
configurable: true
});
};
/** @type {typeof import('color-convert')} */
let colorConvert;
const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => {
if (colorConvert === undefined) {
colorConvert = require('color-convert');
}
const offset = isBackground ? 10 : 0;
const styles = {};
for (const [sourceSpace, suite] of Object.entries(colorConvert)) {
const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace;
if (sourceSpace === targetSpace) {
styles[name] = wrap(identity, offset);
} else if (typeof suite === 'object') {
styles[name] = wrap(suite[targetSpace], offset);
}
}
return styles;
};
function assembleStyles() {
const codes = new Map();
const styles = {
modifier: {
reset: [0, 0],
// 21 isn't widely supported and 22 does the same thing
bold: [1, 22],
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
color: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
// Bright color
blackBright: [90, 39],
redBright: [91, 39],
greenBright: [92, 39],
yellowBright: [93, 39],
blueBright: [94, 39],
magentaBright: [95, 39],
cyanBright: [96, 39],
whiteBright: [97, 39]
},
bgColor: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49],
// Bright color
bgBlackBright: [100, 49],
bgRedBright: [101, 49],
bgGreenBright: [102, 49],
bgYellowBright: [103, 49],
bgBlueBright: [104, 49],
bgMagentaBright: [105, 49],
bgCyanBright: [106, 49],
bgWhiteBright: [107, 49]
}
};
// Alias bright black as gray (and grey)
styles.color.gray = styles.color.blackBright;
styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
styles.color.grey = styles.color.blackBright;
styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
for (const [groupName, group] of Object.entries(styles)) {
for (const [styleName, style] of Object.entries(group)) {
styles[styleName] = {
open: `\u001B[${style[0]}m`,
close: `\u001B[${style[1]}m`
};
group[styleName] = styles[styleName];
codes.set(style[0], style[1]);
}
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
}
Object.defineProperty(styles, 'codes', {
value: codes,
enumerable: false
});
styles.color.close = '\u001B[39m';
styles.bgColor.close = '\u001B[49m';
setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
return styles;
}
// Make the export immutable
Object.defineProperty(module, 'exports', {
enumerable: true,
get: assembleStyles
});

9
node_modules/ava/node_modules/ansi-styles/license generated vendored Normal file
View file

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

57
node_modules/ava/node_modules/ansi-styles/package.json generated vendored Normal file
View file

@ -0,0 +1,57 @@
{
"name": "ansi-styles",
"version": "4.2.1",
"description": "ANSI escape codes for styling strings in the terminal",
"license": "MIT",
"repository": "chalk/ansi-styles",
"funding": "https://github.com/chalk/ansi-styles?sponsor=1",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && ava && tsd",
"screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"@types/color-name": "^1.1.1",
"color-convert": "^2.0.1"
},
"devDependencies": {
"@types/color-convert": "^1.9.0",
"ava": "^2.3.0",
"svg-term-cli": "^2.1.1",
"tsd": "^0.11.0",
"xo": "^0.25.3"
}
}

158
node_modules/ava/node_modules/ansi-styles/readme.md generated vendored Normal file
View file

@ -0,0 +1,158 @@
# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles)
> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal
You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings.
<img src="screenshot.svg" width="900">
## Install
```
$ npm install ansi-styles
```
## Usage
```js
const style = require('ansi-styles');
console.log(`${style.green.open}Hello world!${style.green.close}`);
// Color conversion between 16/256/truecolor
// NOTE: If conversion goes to 16 colors or 256 colors, the original color
// may be degraded to fit that color palette. This means terminals
// that do not support 16 million colors will best-match the
// original color.
console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close);
console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close);
console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close);
```
## API
Each style has an `open` and `close` property.
## Styles
### Modifiers
- `reset`
- `bold`
- `dim`
- `italic` *(Not widely supported)*
- `underline`
- `inverse`
- `hidden`
- `strikethrough` *(Not widely supported)*
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`
## Advanced usage
By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module.
- `style.modifier`
- `style.color`
- `style.bgColor`
###### Example
```js
console.log(style.color.green.open);
```
Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values.
###### Example
```js
console.log(style.codes.get(36));
//=> 39
```
## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728)
`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors.
The following color spaces from `color-convert` are supported:
- `rgb`
- `hex`
- `keyword`
- `hsl`
- `hsv`
- `hwb`
- `ansi`
- `ansi256`
To use these, call the associated conversion function with the intended output, for example:
```js
style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code
style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code
style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code
style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code
style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code
style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code
```
## Related
- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=readme">Get professional support for this package 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>

408
node_modules/ava/node_modules/chalk/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,408 @@
/**
Basic foreground colors.
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type ForegroundColor =
| 'black'
| 'red'
| 'green'
| 'yellow'
| 'blue'
| 'magenta'
| 'cyan'
| 'white'
| 'gray'
| 'grey'
| 'blackBright'
| 'redBright'
| 'greenBright'
| 'yellowBright'
| 'blueBright'
| 'magentaBright'
| 'cyanBright'
| 'whiteBright';
/**
Basic background colors.
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type BackgroundColor =
| 'bgBlack'
| 'bgRed'
| 'bgGreen'
| 'bgYellow'
| 'bgBlue'
| 'bgMagenta'
| 'bgCyan'
| 'bgWhite'
| 'bgGray'
| 'bgGrey'
| 'bgBlackBright'
| 'bgRedBright'
| 'bgGreenBright'
| 'bgYellowBright'
| 'bgBlueBright'
| 'bgMagentaBright'
| 'bgCyanBright'
| 'bgWhiteBright';
/**
Basic colors.
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type Color = ForegroundColor | BackgroundColor;
declare type Modifiers =
| 'reset'
| 'bold'
| 'dim'
| 'italic'
| 'underline'
| 'inverse'
| 'hidden'
| 'strikethrough'
| 'visible';
declare namespace chalk {
/**
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
type Level = 0 | 1 | 2 | 3;
interface Options {
/**
Specify the color support for Chalk.
By default, color support is automatically detected based on the environment.
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
level?: Level;
}
/**
Return a new Chalk instance.
*/
type Instance = new (options?: Options) => Chalk;
/**
Detect whether the terminal supports color.
*/
interface ColorSupport {
/**
The color level used by Chalk.
*/
level: Level;
/**
Return whether Chalk supports basic 16 colors.
*/
hasBasic: boolean;
/**
Return whether Chalk supports ANSI 256 colors.
*/
has256: boolean;
/**
Return whether Chalk supports Truecolor 16 million colors.
*/
has16m: boolean;
}
interface ChalkFunction {
/**
Use a template string.
@remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341))
@example
```
import chalk = require('chalk');
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);
```
*/
(text: TemplateStringsArray, ...placeholders: unknown[]): string;
(...text: unknown[]): string;
}
interface Chalk extends ChalkFunction {
/**
Return a new Chalk instance.
*/
Instance: Instance;
/**
The color support for Chalk.
By default, color support is automatically detected based on the environment.
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
level: Level;
/**
Use HEX value to set text color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.hex('#DEADED');
```
*/
hex(color: string): Chalk;
/**
Use keyword color value to set text color.
@param color - Keyword value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.keyword('orange');
```
*/
keyword(color: string): Chalk;
/**
Use RGB values to set text color.
*/
rgb(red: number, green: number, blue: number): Chalk;
/**
Use HSL values to set text color.
*/
hsl(hue: number, saturation: number, lightness: number): Chalk;
/**
Use HSV values to set text color.
*/
hsv(hue: number, saturation: number, value: number): Chalk;
/**
Use HWB values to set text color.
*/
hwb(hue: number, whiteness: number, blackness: number): Chalk;
/**
Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color.
30 <= code && code < 38 || 90 <= code && code < 98
For example, 31 for red, 91 for redBright.
*/
ansi(code: number): Chalk;
/**
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
*/
ansi256(index: number): Chalk;
/**
Use HEX value to set background color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.bgHex('#DEADED');
```
*/
bgHex(color: string): Chalk;
/**
Use keyword color value to set background color.
@param color - Keyword value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.bgKeyword('orange');
```
*/
bgKeyword(color: string): Chalk;
/**
Use RGB values to set background color.
*/
bgRgb(red: number, green: number, blue: number): Chalk;
/**
Use HSL values to set background color.
*/
bgHsl(hue: number, saturation: number, lightness: number): Chalk;
/**
Use HSV values to set background color.
*/
bgHsv(hue: number, saturation: number, value: number): Chalk;
/**
Use HWB values to set background color.
*/
bgHwb(hue: number, whiteness: number, blackness: number): Chalk;
/**
Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color.
30 <= code && code < 38 || 90 <= code && code < 98
For example, 31 for red, 91 for redBright.
Use the foreground code, not the background code (for example, not 41, nor 101).
*/
bgAnsi(code: number): Chalk;
/**
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
*/
bgAnsi256(index: number): Chalk;
/**
Modifier: Resets the current color chain.
*/
readonly reset: Chalk;
/**
Modifier: Make text bold.
*/
readonly bold: Chalk;
/**
Modifier: Emitting only a small amount of light.
*/
readonly dim: Chalk;
/**
Modifier: Make text italic. (Not widely supported)
*/
readonly italic: Chalk;
/**
Modifier: Make text underline. (Not widely supported)
*/
readonly underline: Chalk;
/**
Modifier: Inverse background and foreground colors.
*/
readonly inverse: Chalk;
/**
Modifier: Prints the text, but makes it invisible.
*/
readonly hidden: Chalk;
/**
Modifier: Puts a horizontal line through the center of the text. (Not widely supported)
*/
readonly strikethrough: Chalk;
/**
Modifier: Prints the text only when Chalk has a color support level > 0.
Can be useful for things that are purely cosmetic.
*/
readonly visible: Chalk;
readonly black: Chalk;
readonly red: Chalk;
readonly green: Chalk;
readonly yellow: Chalk;
readonly blue: Chalk;
readonly magenta: Chalk;
readonly cyan: Chalk;
readonly white: Chalk;
/*
Alias for `blackBright`.
*/
readonly gray: Chalk;
/*
Alias for `blackBright`.
*/
readonly grey: Chalk;
readonly blackBright: Chalk;
readonly redBright: Chalk;
readonly greenBright: Chalk;
readonly yellowBright: Chalk;
readonly blueBright: Chalk;
readonly magentaBright: Chalk;
readonly cyanBright: Chalk;
readonly whiteBright: Chalk;
readonly bgBlack: Chalk;
readonly bgRed: Chalk;
readonly bgGreen: Chalk;
readonly bgYellow: Chalk;
readonly bgBlue: Chalk;
readonly bgMagenta: Chalk;
readonly bgCyan: Chalk;
readonly bgWhite: Chalk;
/*
Alias for `bgBlackBright`.
*/
readonly bgGray: Chalk;
/*
Alias for `bgBlackBright`.
*/
readonly bgGrey: Chalk;
readonly bgBlackBright: Chalk;
readonly bgRedBright: Chalk;
readonly bgGreenBright: Chalk;
readonly bgYellowBright: Chalk;
readonly bgBlueBright: Chalk;
readonly bgMagentaBright: Chalk;
readonly bgCyanBright: Chalk;
readonly bgWhiteBright: Chalk;
}
}
/**
Main Chalk object that allows to chain styles together.
Call the last one as a method with a string argument.
Order doesn't matter, and later styles take precedent in case of a conflict.
This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
*/
declare const chalk: chalk.Chalk & chalk.ChalkFunction & {
supportsColor: chalk.ColorSupport | false;
Level: chalk.Level;
Color: Color;
ForegroundColor: ForegroundColor;
BackgroundColor: BackgroundColor;
Modifiers: Modifiers;
stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false};
};
export = chalk;

9
node_modules/ava/node_modules/chalk/license generated vendored Normal file
View file

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

68
node_modules/ava/node_modules/chalk/package.json generated vendored Normal file
View file

@ -0,0 +1,68 @@
{
"name": "chalk",
"version": "4.0.0",
"description": "Terminal string styling done right",
"license": "MIT",
"repository": "chalk/chalk",
"funding": "https://github.com/chalk/chalk?sponsor=1",
"main": "source",
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && nyc ava && tsd",
"bench": "matcha benchmark.js"
},
"files": [
"source",
"index.d.ts"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"str",
"ansi",
"style",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"devDependencies": {
"ava": "^2.4.0",
"coveralls": "^3.0.7",
"execa": "^4.0.0",
"import-fresh": "^3.1.0",
"matcha": "^0.7.0",
"nyc": "^15.0.0",
"resolve-from": "^5.0.0",
"tsd": "^0.7.4",
"xo": "^0.28.2"
},
"xo": {
"rules": {
"unicorn/prefer-string-slice": "off",
"unicorn/prefer-includes": "off",
"@typescript-eslint/member-ordering": "off",
"no-redeclare": "off",
"unicorn/string-content": "off",
"unicorn/better-regex": "off"
}
}
}

292
node_modules/ava/node_modules/chalk/readme.md generated vendored Normal file
View file

@ -0,0 +1,292 @@
<h1 align="center">
<br>
<br>
<img width="320" src="media/logo.svg" alt="Chalk">
<br>
<br>
<br>
</h1>
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](http://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk)
<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
## Highlights
- Expressive API
- Highly performant
- Ability to nest styles
- [256/Truecolor color support](#256-and-truecolor-color-support)
- Auto-detects color support
- Doesn't extend `String.prototype`
- Clean and focused
- Actively maintained
- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020
## Install
```console
$ npm install chalk
```
## Usage
```js
const chalk = require('chalk');
console.log(chalk.blue('Hello world!'));
```
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
```js
const chalk = require('chalk');
const log = console.log;
// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
// Nest styles of the same type even (color, underline, background)
log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
));
// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
// ES2015 tagged template literal
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);
// Use RGB colors in terminal emulators that support it.
log(chalk.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
```
Easily define your own themes:
```js
const chalk = require('chalk');
const error = chalk.bold.red;
const warning = chalk.keyword('orange');
console.log(error('Error!'));
console.log(warning('Warning!'));
```
Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
```js
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
Multiple arguments will be separated by space.
### chalk.level
Specifies the level of color support.
Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
If you need to change this in a reusable module, create a new instance:
```js
const ctx = new chalk.Instance({level: 0});
```
| Level | Description |
| :---: | :--- |
| `0` | All colors disabled |
| `1` | Basic color support (16 colors) |
| `2` | 256 color support |
| `3` | Truecolor support (16 million colors) |
### chalk.supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
### chalk.stderr and chalk.stderr.supportsColor
`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience.
## Styles
### Modifiers
- `reset` - Resets the current color chain.
- `bold` - Make text bold.
- `dim` - Emitting only a small amount of light.
- `italic` - Make text italic. *(Not widely supported)*
- `underline` - Make text underline. *(Not widely supported)*
- `inverse`- Inverse background and foreground colors.
- `hidden` - Prints the text, but makes it invisible.
- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
- `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`
## Tagged template literal
Chalk can be used as a [tagged template literal](http://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
```js
const chalk = require('chalk');
const miles = 18;
const calculateFeet = miles => miles * 5280;
console.log(chalk`
There are {bold 5280 feet} in a mile.
In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
`);
```
Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
Template styles are chained exactly like normal Chalk styles. The following two statements are equivalent:
```js
console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
```
Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
## 256 and Truecolor color support
Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
Examples:
- `chalk.hex('#DEADED').underline('Hello, world!')`
- `chalk.keyword('orange')('Some orange text')`
- `chalk.rgb(15, 100, 204).inverse('Hello!')`
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
- `chalk.bgHex('#DEADED').underline('Hello, world!')`
- `chalk.bgKeyword('orange')('Some orange text')`
- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
The following color models can be used:
- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
## Windows
If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
## Origin story
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
## chalk for enterprise
Available as part of the Tidelift Subscription.
The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Related
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)

222
node_modules/ava/node_modules/chalk/source/index.js generated vendored Normal file
View file

@ -0,0 +1,222 @@
'use strict';
const ansiStyles = require('ansi-styles');
const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color');
const {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
} = require('./util');
// `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = [
'ansi',
'ansi',
'ansi256',
'ansi16m'
];
const styles = Object.create(null);
const applyOptions = (object, options = {}) => {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error('The `level` option should be an integer from 0 to 3');
}
// Detect level if not set manually
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === undefined ? colorLevel : options.level;
};
class ChalkClass {
constructor(options) {
// eslint-disable-next-line no-constructor-return
return chalkFactory(options);
}
}
const chalkFactory = options => {
const chalk = {};
applyOptions(chalk, options);
chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
Object.setPrototypeOf(chalk, Chalk.prototype);
Object.setPrototypeOf(chalk.template, chalk);
chalk.template.constructor = () => {
throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
};
chalk.template.Instance = ChalkClass;
return chalk.template;
};
function Chalk(options) {
return chalkFactory(options);
}
for (const [styleName, style] of Object.entries(ansiStyles)) {
styles[styleName] = {
get() {
const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
Object.defineProperty(this, styleName, {value: builder});
return builder;
}
};
}
styles.visible = {
get() {
const builder = createBuilder(this, this._styler, true);
Object.defineProperty(this, 'visible', {value: builder});
return builder;
}
};
const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
for (const model of usedModels) {
styles[model] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
return createBuilder(this, styler, this._isEmpty);
};
}
};
}
for (const model of usedModels) {
const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
return createBuilder(this, styler, this._isEmpty);
};
}
};
}
const proto = Object.defineProperties(() => {}, {
...styles,
level: {
enumerable: true,
get() {
return this._generator.level;
},
set(level) {
this._generator.level = level;
}
}
});
const createStyler = (open, close, parent) => {
let openAll;
let closeAll;
if (parent === undefined) {
openAll = open;
closeAll = close;
} else {
openAll = parent.openAll + open;
closeAll = close + parent.closeAll;
}
return {
open,
close,
openAll,
closeAll,
parent
};
};
const createBuilder = (self, _styler, _isEmpty) => {
const builder = (...arguments_) => {
// Single argument is hot path, implicit coercion is faster than anything
// eslint-disable-next-line no-implicit-coercion
return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
};
// We alter the prototype because we must return a function, but there is
// no way to create a function with a different prototype
Object.setPrototypeOf(builder, proto);
builder._generator = self;
builder._styler = _styler;
builder._isEmpty = _isEmpty;
return builder;
};
const applyStyle = (self, string) => {
if (self.level <= 0 || !string) {
return self._isEmpty ? '' : string;
}
let styler = self._styler;
if (styler === undefined) {
return string;
}
const {openAll, closeAll} = styler;
if (string.indexOf('\u001B') !== -1) {
while (styler !== undefined) {
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
string = stringReplaceAll(string, styler.close, styler.open);
styler = styler.parent;
}
}
// We can move both next actions out of loop, because remaining actions in loop won't have
// any/visible effect on parts we add here. Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
const lfIndex = string.indexOf('\n');
if (lfIndex !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;
};
let template;
const chalkTag = (chalk, ...strings) => {
const [firstString] = strings;
if (!Array.isArray(firstString)) {
// If chalk() was called by itself or with a string,
// return the string itself as a string.
return strings.join(' ');
}
const arguments_ = strings.slice(1);
const parts = [firstString.raw[0]];
for (let i = 1; i < firstString.length; i++) {
parts.push(
String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
String(firstString.raw[i])
);
}
if (template === undefined) {
template = require('./templates');
}
return template(chalk, parts.join(''));
};
Object.defineProperties(Chalk.prototype, styles);
const chalk = Chalk(); // eslint-disable-line new-cap
chalk.supportsColor = stdoutColor;
chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
chalk.stderr.supportsColor = stderrColor;
module.exports = chalk;

134
node_modules/ava/node_modules/chalk/source/templates.js generated vendored Normal file
View file

@ -0,0 +1,134 @@
'use strict';
const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
const ESCAPES = new Map([
['n', '\n'],
['r', '\r'],
['t', '\t'],
['b', '\b'],
['f', '\f'],
['v', '\v'],
['0', '\0'],
['\\', '\\'],
['e', '\u001B'],
['a', '\u0007']
]);
function unescape(c) {
const u = c[0] === 'u';
const bracket = c[1] === '{';
if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
return String.fromCharCode(parseInt(c.slice(1), 16));
}
if (u && bracket) {
return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
}
return ESCAPES.get(c) || c;
}
function parseArguments(name, arguments_) {
const results = [];
const chunks = arguments_.trim().split(/\s*,\s*/g);
let matches;
for (const chunk of chunks) {
const number = Number(chunk);
if (!Number.isNaN(number)) {
results.push(number);
} else if ((matches = chunk.match(STRING_REGEX))) {
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
} else {
throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
}
}
return results;
}
function parseStyle(style) {
STYLE_REGEX.lastIndex = 0;
const results = [];
let matches;
while ((matches = STYLE_REGEX.exec(style)) !== null) {
const name = matches[1];
if (matches[2]) {
const args = parseArguments(name, matches[2]);
results.push([name].concat(args));
} else {
results.push([name]);
}
}
return results;
}
function buildStyle(chalk, styles) {
const enabled = {};
for (const layer of styles) {
for (const style of layer.styles) {
enabled[style[0]] = layer.inverse ? null : style.slice(1);
}
}
let current = chalk;
for (const [styleName, styles] of Object.entries(enabled)) {
if (!Array.isArray(styles)) {
continue;
}
if (!(styleName in current)) {
throw new Error(`Unknown Chalk style: ${styleName}`);
}
current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
}
return current;
}
module.exports = (chalk, temporary) => {
const styles = [];
const chunks = [];
let chunk = [];
// eslint-disable-next-line max-params
temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
if (escapeCharacter) {
chunk.push(unescape(escapeCharacter));
} else if (style) {
const string = chunk.join('');
chunk = [];
chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
styles.push({inverse, styles: parseStyle(style)});
} else if (close) {
if (styles.length === 0) {
throw new Error('Found extraneous } in Chalk template literal');
}
chunks.push(buildStyle(chalk, styles)(chunk.join('')));
chunk = [];
styles.pop();
} else {
chunk.push(character);
}
});
chunks.push(chunk.join(''));
if (styles.length > 0) {
const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
throw new Error(errMessage);
}
return chunks.join('');
};

39
node_modules/ava/node_modules/chalk/source/util.js generated vendored Normal file
View file

@ -0,0 +1,39 @@
'use strict';
const stringReplaceAll = (string, substring, replacer) => {
let index = string.indexOf(substring);
if (index === -1) {
return string;
}
const substringLength = substring.length;
let endIndex = 0;
let returnValue = '';
do {
returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
endIndex = index + substringLength;
index = string.indexOf(substring, endIndex);
} while (index !== -1);
returnValue += string.substr(endIndex);
return returnValue;
};
const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
let endIndex = 0;
let returnValue = '';
do {
const gotCR = string[index - 1] === '\r';
returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
endIndex = index + 1;
index = string.indexOf('\n', endIndex);
} while (index !== -1);
returnValue += string.substr(endIndex);
return returnValue;
};
module.exports = {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
};

View file

@ -0,0 +1,54 @@
# 1.0.0 - 2016-01-07
- Removed: unused speed test
- Added: Automatic routing between previously unsupported conversions
([#27](https://github.com/Qix-/color-convert/pull/27))
- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions
([#27](https://github.com/Qix-/color-convert/pull/27))
- Removed: `convert()` class
([#27](https://github.com/Qix-/color-convert/pull/27))
- Changed: all functions to lookup dictionary
([#27](https://github.com/Qix-/color-convert/pull/27))
- Changed: `ansi` to `ansi256`
([#27](https://github.com/Qix-/color-convert/pull/27))
- Fixed: argument grouping for functions requiring only one argument
([#27](https://github.com/Qix-/color-convert/pull/27))
# 0.6.0 - 2015-07-23
- Added: methods to handle
[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors:
- rgb2ansi16
- rgb2ansi
- hsl2ansi16
- hsl2ansi
- hsv2ansi16
- hsv2ansi
- hwb2ansi16
- hwb2ansi
- cmyk2ansi16
- cmyk2ansi
- keyword2ansi16
- keyword2ansi
- ansi162rgb
- ansi162hsl
- ansi162hsv
- ansi162hwb
- ansi162cmyk
- ansi162keyword
- ansi2rgb
- ansi2hsl
- ansi2hsv
- ansi2hwb
- ansi2cmyk
- ansi2keyword
([#18](https://github.com/harthur/color-convert/pull/18))
# 0.5.3 - 2015-06-02
- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]`
([#15](https://github.com/harthur/color-convert/issues/15))
---
Check out commit logs for older releases

21
node_modules/ava/node_modules/color-convert/LICENSE generated vendored Normal file
View file

@ -0,0 +1,21 @@
Copyright (c) 2011-2016 Heather Arthur <fayearthur@gmail.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.

68
node_modules/ava/node_modules/color-convert/README.md generated vendored Normal file
View file

@ -0,0 +1,68 @@
# color-convert
[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert)
Color-convert is a color conversion library for JavaScript and node.
It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest):
```js
var convert = require('color-convert');
convert.rgb.hsl(140, 200, 100); // [96, 48, 59]
convert.keyword.rgb('blue'); // [0, 0, 255]
var rgbChannels = convert.rgb.channels; // 3
var cmykChannels = convert.cmyk.channels; // 4
var ansiChannels = convert.ansi16.channels; // 1
```
# Install
```console
$ npm install color-convert
```
# API
Simply get the property of the _from_ and _to_ conversion that you're looking for.
All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function.
All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha).
```js
var convert = require('color-convert');
// Hex to LAB
convert.hex.lab('DEADBF'); // [ 76, 21, -2 ]
convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ]
// RGB to CMYK
convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ]
convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ]
```
### Arrays
All functions that accept multiple arguments also support passing an array.
Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.)
```js
var convert = require('color-convert');
convert.rgb.hex(123, 45, 67); // '7B2D43'
convert.rgb.hex([123, 45, 67]); // '7B2D43'
```
## Routing
Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex).
Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js).
# Contribute
If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request.
# License
Copyright &copy; 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE).

View file

@ -0,0 +1,839 @@
/* MIT license */
/* eslint-disable no-mixed-operators */
const cssKeywords = require('color-name');
// NOTE: conversions should only return primitive values (i.e. arrays, or
// values that give correct `typeof` results).
// do not use box values types (i.e. Number(), String(), etc.)
const reverseKeywords = {};
for (const key of Object.keys(cssKeywords)) {
reverseKeywords[cssKeywords[key]] = key;
}
const convert = {
rgb: {channels: 3, labels: 'rgb'},
hsl: {channels: 3, labels: 'hsl'},
hsv: {channels: 3, labels: 'hsv'},
hwb: {channels: 3, labels: 'hwb'},
cmyk: {channels: 4, labels: 'cmyk'},
xyz: {channels: 3, labels: 'xyz'},
lab: {channels: 3, labels: 'lab'},
lch: {channels: 3, labels: 'lch'},
hex: {channels: 1, labels: ['hex']},
keyword: {channels: 1, labels: ['keyword']},
ansi16: {channels: 1, labels: ['ansi16']},
ansi256: {channels: 1, labels: ['ansi256']},
hcg: {channels: 3, labels: ['h', 'c', 'g']},
apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
gray: {channels: 1, labels: ['gray']}
};
module.exports = convert;
// Hide .channels and .labels properties
for (const model of Object.keys(convert)) {
if (!('channels' in convert[model])) {
throw new Error('missing channels property: ' + model);
}
if (!('labels' in convert[model])) {
throw new Error('missing channel labels property: ' + model);
}
if (convert[model].labels.length !== convert[model].channels) {
throw new Error('channel and label counts mismatch: ' + model);
}
const {channels, labels} = convert[model];
delete convert[model].channels;
delete convert[model].labels;
Object.defineProperty(convert[model], 'channels', {value: channels});
Object.defineProperty(convert[model], 'labels', {value: labels});
}
convert.rgb.hsl = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const min = Math.min(r, g, b);
const max = Math.max(r, g, b);
const delta = max - min;
let h;
let s;
if (max === min) {
h = 0;
} else if (r === max) {
h = (g - b) / delta;
} else if (g === max) {
h = 2 + (b - r) / delta;
} else if (b === max) {
h = 4 + (r - g) / delta;
}
h = Math.min(h * 60, 360);
if (h < 0) {
h += 360;
}
const l = (min + max) / 2;
if (max === min) {
s = 0;
} else if (l <= 0.5) {
s = delta / (max + min);
} else {
s = delta / (2 - max - min);
}
return [h, s * 100, l * 100];
};
convert.rgb.hsv = function (rgb) {
let rdif;
let gdif;
let bdif;
let h;
let s;
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const v = Math.max(r, g, b);
const diff = v - Math.min(r, g, b);
const diffc = function (c) {
return (v - c) / 6 / diff + 1 / 2;
};
if (diff === 0) {
h = 0;
s = 0;
} else {
s = diff / v;
rdif = diffc(r);
gdif = diffc(g);
bdif = diffc(b);
if (r === v) {
h = bdif - gdif;
} else if (g === v) {
h = (1 / 3) + rdif - bdif;
} else if (b === v) {
h = (2 / 3) + gdif - rdif;
}
if (h < 0) {
h += 1;
} else if (h > 1) {
h -= 1;
}
}
return [
h * 360,
s * 100,
v * 100
];
};
convert.rgb.hwb = function (rgb) {
const r = rgb[0];
const g = rgb[1];
let b = rgb[2];
const h = convert.rgb.hsl(rgb)[0];
const w = 1 / 255 * Math.min(r, Math.min(g, b));
b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
return [h, w * 100, b * 100];
};
convert.rgb.cmyk = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const k = Math.min(1 - r, 1 - g, 1 - b);
const c = (1 - r - k) / (1 - k) || 0;
const m = (1 - g - k) / (1 - k) || 0;
const y = (1 - b - k) / (1 - k) || 0;
return [c * 100, m * 100, y * 100, k * 100];
};
function comparativeDistance(x, y) {
/*
See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
*/
return (
((x[0] - y[0]) ** 2) +
((x[1] - y[1]) ** 2) +
((x[2] - y[2]) ** 2)
);
}
convert.rgb.keyword = function (rgb) {
const reversed = reverseKeywords[rgb];
if (reversed) {
return reversed;
}
let currentClosestDistance = Infinity;
let currentClosestKeyword;
for (const keyword of Object.keys(cssKeywords)) {
const value = cssKeywords[keyword];
// Compute comparative distance
const distance = comparativeDistance(rgb, value);
// Check if its less, if so set as closest
if (distance < currentClosestDistance) {
currentClosestDistance = distance;
currentClosestKeyword = keyword;
}
}
return currentClosestKeyword;
};
convert.keyword.rgb = function (keyword) {
return cssKeywords[keyword];
};
convert.rgb.xyz = function (rgb) {
let r = rgb[0] / 255;
let g = rgb[1] / 255;
let b = rgb[2] / 255;
// Assume sRGB
r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
return [x * 100, y * 100, z * 100];
};
convert.rgb.lab = function (rgb) {
const xyz = convert.rgb.xyz(rgb);
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
const l = (116 * y) - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [l, a, b];
};
convert.hsl.rgb = function (hsl) {
const h = hsl[0] / 360;
const s = hsl[1] / 100;
const l = hsl[2] / 100;
let t2;
let t3;
let val;
if (s === 0) {
val = l * 255;
return [val, val, val];
}
if (l < 0.5) {
t2 = l * (1 + s);
} else {
t2 = l + s - l * s;
}
const t1 = 2 * l - t2;
const rgb = [0, 0, 0];
for (let i = 0; i < 3; i++) {
t3 = h + 1 / 3 * -(i - 1);
if (t3 < 0) {
t3++;
}
if (t3 > 1) {
t3--;
}
if (6 * t3 < 1) {
val = t1 + (t2 - t1) * 6 * t3;
} else if (2 * t3 < 1) {
val = t2;
} else if (3 * t3 < 2) {
val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
} else {
val = t1;
}
rgb[i] = val * 255;
}
return rgb;
};
convert.hsl.hsv = function (hsl) {
const h = hsl[0];
let s = hsl[1] / 100;
let l = hsl[2] / 100;
let smin = s;
const lmin = Math.max(l, 0.01);
l *= 2;
s *= (l <= 1) ? l : 2 - l;
smin *= lmin <= 1 ? lmin : 2 - lmin;
const v = (l + s) / 2;
const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
return [h, sv * 100, v * 100];
};
convert.hsv.rgb = function (hsv) {
const h = hsv[0] / 60;
const s = hsv[1] / 100;
let v = hsv[2] / 100;
const hi = Math.floor(h) % 6;
const f = h - Math.floor(h);
const p = 255 * v * (1 - s);
const q = 255 * v * (1 - (s * f));
const t = 255 * v * (1 - (s * (1 - f)));
v *= 255;
switch (hi) {
case 0:
return [v, t, p];
case 1:
return [q, v, p];
case 2:
return [p, v, t];
case 3:
return [p, q, v];
case 4:
return [t, p, v];
case 5:
return [v, p, q];
}
};
convert.hsv.hsl = function (hsv) {
const h = hsv[0];
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const vmin = Math.max(v, 0.01);
let sl;
let l;
l = (2 - s) * v;
const lmin = (2 - s) * vmin;
sl = s * vmin;
sl /= (lmin <= 1) ? lmin : 2 - lmin;
sl = sl || 0;
l /= 2;
return [h, sl * 100, l * 100];
};
// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
convert.hwb.rgb = function (hwb) {
const h = hwb[0] / 360;
let wh = hwb[1] / 100;
let bl = hwb[2] / 100;
const ratio = wh + bl;
let f;
// Wh + bl cant be > 1
if (ratio > 1) {
wh /= ratio;
bl /= ratio;
}
const i = Math.floor(6 * h);
const v = 1 - bl;
f = 6 * h - i;
if ((i & 0x01) !== 0) {
f = 1 - f;
}
const n = wh + f * (v - wh); // Linear interpolation
let r;
let g;
let b;
/* eslint-disable max-statements-per-line,no-multi-spaces */
switch (i) {
default:
case 6:
case 0: r = v; g = n; b = wh; break;
case 1: r = n; g = v; b = wh; break;
case 2: r = wh; g = v; b = n; break;
case 3: r = wh; g = n; b = v; break;
case 4: r = n; g = wh; b = v; break;
case 5: r = v; g = wh; b = n; break;
}
/* eslint-enable max-statements-per-line,no-multi-spaces */
return [r * 255, g * 255, b * 255];
};
convert.cmyk.rgb = function (cmyk) {
const c = cmyk[0] / 100;
const m = cmyk[1] / 100;
const y = cmyk[2] / 100;
const k = cmyk[3] / 100;
const r = 1 - Math.min(1, c * (1 - k) + k);
const g = 1 - Math.min(1, m * (1 - k) + k);
const b = 1 - Math.min(1, y * (1 - k) + k);
return [r * 255, g * 255, b * 255];
};
convert.xyz.rgb = function (xyz) {
const x = xyz[0] / 100;
const y = xyz[1] / 100;
const z = xyz[2] / 100;
let r;
let g;
let b;
r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
// Assume sRGB
r = r > 0.0031308
? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
: r * 12.92;
g = g > 0.0031308
? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
: g * 12.92;
b = b > 0.0031308
? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
: b * 12.92;
r = Math.min(Math.max(0, r), 1);
g = Math.min(Math.max(0, g), 1);
b = Math.min(Math.max(0, b), 1);
return [r * 255, g * 255, b * 255];
};
convert.xyz.lab = function (xyz) {
let x = xyz[0];
let y = xyz[1];
let z = xyz[2];
x /= 95.047;
y /= 100;
z /= 108.883;
x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
const l = (116 * y) - 16;
const a = 500 * (x - y);
const b = 200 * (y - z);
return [l, a, b];
};
convert.lab.xyz = function (lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
let x;
let y;
let z;
y = (l + 16) / 116;
x = a / 500 + y;
z = y - b / 200;
const y2 = y ** 3;
const x2 = x ** 3;
const z2 = z ** 3;
y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
x *= 95.047;
y *= 100;
z *= 108.883;
return [x, y, z];
};
convert.lab.lch = function (lab) {
const l = lab[0];
const a = lab[1];
const b = lab[2];
let h;
const hr = Math.atan2(b, a);
h = hr * 360 / 2 / Math.PI;
if (h < 0) {
h += 360;
}
const c = Math.sqrt(a * a + b * b);
return [l, c, h];
};
convert.lch.lab = function (lch) {
const l = lch[0];
const c = lch[1];
const h = lch[2];
const hr = h / 360 * 2 * Math.PI;
const a = c * Math.cos(hr);
const b = c * Math.sin(hr);
return [l, a, b];
};
convert.rgb.ansi16 = function (args, saturation = null) {
const [r, g, b] = args;
let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
value = Math.round(value / 50);
if (value === 0) {
return 30;
}
let ansi = 30
+ ((Math.round(b / 255) << 2)
| (Math.round(g / 255) << 1)
| Math.round(r / 255));
if (value === 2) {
ansi += 60;
}
return ansi;
};
convert.hsv.ansi16 = function (args) {
// Optimization here; we already know the value and don't need to get
// it converted for us.
return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
};
convert.rgb.ansi256 = function (args) {
const r = args[0];
const g = args[1];
const b = args[2];
// We use the extended greyscale palette here, with the exception of
// black and white. normal palette only has 4 greyscale shades.
if (r === g && g === b) {
if (r < 8) {
return 16;
}
if (r > 248) {
return 231;
}
return Math.round(((r - 8) / 247) * 24) + 232;
}
const ansi = 16
+ (36 * Math.round(r / 255 * 5))
+ (6 * Math.round(g / 255 * 5))
+ Math.round(b / 255 * 5);
return ansi;
};
convert.ansi16.rgb = function (args) {
let color = args % 10;
// Handle greyscale
if (color === 0 || color === 7) {
if (args > 50) {
color += 3.5;
}
color = color / 10.5 * 255;
return [color, color, color];
}
const mult = (~~(args > 50) + 1) * 0.5;
const r = ((color & 1) * mult) * 255;
const g = (((color >> 1) & 1) * mult) * 255;
const b = (((color >> 2) & 1) * mult) * 255;
return [r, g, b];
};
convert.ansi256.rgb = function (args) {
// Handle greyscale
if (args >= 232) {
const c = (args - 232) * 10 + 8;
return [c, c, c];
}
args -= 16;
let rem;
const r = Math.floor(args / 36) / 5 * 255;
const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
const b = (rem % 6) / 5 * 255;
return [r, g, b];
};
convert.rgb.hex = function (args) {
const integer = ((Math.round(args[0]) & 0xFF) << 16)
+ ((Math.round(args[1]) & 0xFF) << 8)
+ (Math.round(args[2]) & 0xFF);
const string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.hex.rgb = function (args) {
const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
if (!match) {
return [0, 0, 0];
}
let colorString = match[0];
if (match[0].length === 3) {
colorString = colorString.split('').map(char => {
return char + char;
}).join('');
}
const integer = parseInt(colorString, 16);
const r = (integer >> 16) & 0xFF;
const g = (integer >> 8) & 0xFF;
const b = integer & 0xFF;
return [r, g, b];
};
convert.rgb.hcg = function (rgb) {
const r = rgb[0] / 255;
const g = rgb[1] / 255;
const b = rgb[2] / 255;
const max = Math.max(Math.max(r, g), b);
const min = Math.min(Math.min(r, g), b);
const chroma = (max - min);
let grayscale;
let hue;
if (chroma < 1) {
grayscale = min / (1 - chroma);
} else {
grayscale = 0;
}
if (chroma <= 0) {
hue = 0;
} else
if (max === r) {
hue = ((g - b) / chroma) % 6;
} else
if (max === g) {
hue = 2 + (b - r) / chroma;
} else {
hue = 4 + (r - g) / chroma;
}
hue /= 6;
hue %= 1;
return [hue * 360, chroma * 100, grayscale * 100];
};
convert.hsl.hcg = function (hsl) {
const s = hsl[1] / 100;
const l = hsl[2] / 100;
const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
let f = 0;
if (c < 1.0) {
f = (l - 0.5 * c) / (1.0 - c);
}
return [hsl[0], c * 100, f * 100];
};
convert.hsv.hcg = function (hsv) {
const s = hsv[1] / 100;
const v = hsv[2] / 100;
const c = s * v;
let f = 0;
if (c < 1.0) {
f = (v - c) / (1 - c);
}
return [hsv[0], c * 100, f * 100];
};
convert.hcg.rgb = function (hcg) {
const h = hcg[0] / 360;
const c = hcg[1] / 100;
const g = hcg[2] / 100;
if (c === 0.0) {
return [g * 255, g * 255, g * 255];
}
const pure = [0, 0, 0];
const hi = (h % 1) * 6;
const v = hi % 1;
const w = 1 - v;
let mg = 0;
/* eslint-disable max-statements-per-line */
switch (Math.floor(hi)) {
case 0:
pure[0] = 1; pure[1] = v; pure[2] = 0; break;
case 1:
pure[0] = w; pure[1] = 1; pure[2] = 0; break;
case 2:
pure[0] = 0; pure[1] = 1; pure[2] = v; break;
case 3:
pure[0] = 0; pure[1] = w; pure[2] = 1; break;
case 4:
pure[0] = v; pure[1] = 0; pure[2] = 1; break;
default:
pure[0] = 1; pure[1] = 0; pure[2] = w;
}
/* eslint-enable max-statements-per-line */
mg = (1.0 - c) * g;
return [
(c * pure[0] + mg) * 255,
(c * pure[1] + mg) * 255,
(c * pure[2] + mg) * 255
];
};
convert.hcg.hsv = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1.0 - c);
let f = 0;
if (v > 0.0) {
f = c / v;
}
return [hcg[0], f * 100, v * 100];
};
convert.hcg.hsl = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const l = g * (1.0 - c) + 0.5 * c;
let s = 0;
if (l > 0.0 && l < 0.5) {
s = c / (2 * l);
} else
if (l >= 0.5 && l < 1.0) {
s = c / (2 * (1 - l));
}
return [hcg[0], s * 100, l * 100];
};
convert.hcg.hwb = function (hcg) {
const c = hcg[1] / 100;
const g = hcg[2] / 100;
const v = c + g * (1.0 - c);
return [hcg[0], (v - c) * 100, (1 - v) * 100];
};
convert.hwb.hcg = function (hwb) {
const w = hwb[1] / 100;
const b = hwb[2] / 100;
const v = 1 - b;
const c = v - w;
let g = 0;
if (c < 1) {
g = (v - c) / (1 - c);
}
return [hwb[0], c * 100, g * 100];
};
convert.apple.rgb = function (apple) {
return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
};
convert.rgb.apple = function (rgb) {
return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
};
convert.gray.rgb = function (args) {
return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
};
convert.gray.hsl = function (args) {
return [0, 0, args[0]];
};
convert.gray.hsv = convert.gray.hsl;
convert.gray.hwb = function (gray) {
return [0, 100, gray[0]];
};
convert.gray.cmyk = function (gray) {
return [0, 0, 0, gray[0]];
};
convert.gray.lab = function (gray) {
return [gray[0], 0, 0];
};
convert.gray.hex = function (gray) {
const val = Math.round(gray[0] / 100 * 255) & 0xFF;
const integer = (val << 16) + (val << 8) + val;
const string = integer.toString(16).toUpperCase();
return '000000'.substring(string.length) + string;
};
convert.rgb.gray = function (rgb) {
const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
return [val / 255 * 100];
};

81
node_modules/ava/node_modules/color-convert/index.js generated vendored Normal file
View file

@ -0,0 +1,81 @@
const conversions = require('./conversions');
const route = require('./route');
const convert = {};
const models = Object.keys(conversions);
function wrapRaw(fn) {
const wrappedFn = function (...args) {
const arg0 = args[0];
if (arg0 === undefined || arg0 === null) {
return arg0;
}
if (arg0.length > 1) {
args = arg0;
}
return fn(args);
};
// Preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
function wrapRounded(fn) {
const wrappedFn = function (...args) {
const arg0 = args[0];
if (arg0 === undefined || arg0 === null) {
return arg0;
}
if (arg0.length > 1) {
args = arg0;
}
const result = fn(args);
// We're assuming the result is an array here.
// see notice in conversions.js; don't use box types
// in conversion functions.
if (typeof result === 'object') {
for (let len = result.length, i = 0; i < len; i++) {
result[i] = Math.round(result[i]);
}
}
return result;
};
// Preserve .conversion property if there is one
if ('conversion' in fn) {
wrappedFn.conversion = fn.conversion;
}
return wrappedFn;
}
models.forEach(fromModel => {
convert[fromModel] = {};
Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
const routes = route(fromModel);
const routeModels = Object.keys(routes);
routeModels.forEach(toModel => {
const fn = routes[toModel];
convert[fromModel][toModel] = wrapRounded(fn);
convert[fromModel][toModel].raw = wrapRaw(fn);
});
});
module.exports = convert;

View file

@ -0,0 +1,48 @@
{
"name": "color-convert",
"description": "Plain color conversion functions",
"version": "2.0.1",
"author": "Heather Arthur <fayearthur@gmail.com>",
"license": "MIT",
"repository": "Qix-/color-convert",
"scripts": {
"pretest": "xo",
"test": "node test/basic.js"
},
"engines": {
"node": ">=7.0.0"
},
"keywords": [
"color",
"colour",
"convert",
"converter",
"conversion",
"rgb",
"hsl",
"hsv",
"hwb",
"cmyk",
"ansi",
"ansi16"
],
"files": [
"index.js",
"conversions.js",
"route.js"
],
"xo": {
"rules": {
"default-case": 0,
"no-inline-comments": 0,
"operator-linebreak": 0
}
},
"devDependencies": {
"chalk": "^2.4.2",
"xo": "^0.24.0"
},
"dependencies": {
"color-name": "~1.1.4"
}
}

97
node_modules/ava/node_modules/color-convert/route.js generated vendored Normal file
View file

@ -0,0 +1,97 @@
const conversions = require('./conversions');
/*
This function routes a model to all other models.
all functions that are routed have a property `.conversion` attached
to the returned synthetic function. This property is an array
of strings, each with the steps in between the 'from' and 'to'
color models (inclusive).
conversions that are not possible simply are not included.
*/
function buildGraph() {
const graph = {};
// https://jsperf.com/object-keys-vs-for-in-with-closure/3
const models = Object.keys(conversions);
for (let len = models.length, i = 0; i < len; i++) {
graph[models[i]] = {
// http://jsperf.com/1-vs-infinity
// micro-opt, but this is simple.
distance: -1,
parent: null
};
}
return graph;
}
// https://en.wikipedia.org/wiki/Breadth-first_search
function deriveBFS(fromModel) {
const graph = buildGraph();
const queue = [fromModel]; // Unshift -> queue -> pop
graph[fromModel].distance = 0;
while (queue.length) {
const current = queue.pop();
const adjacents = Object.keys(conversions[current]);
for (let len = adjacents.length, i = 0; i < len; i++) {
const adjacent = adjacents[i];
const node = graph[adjacent];
if (node.distance === -1) {
node.distance = graph[current].distance + 1;
node.parent = current;
queue.unshift(adjacent);
}
}
}
return graph;
}
function link(from, to) {
return function (args) {
return to(from(args));
};
}
function wrapConversion(toModel, graph) {
const path = [graph[toModel].parent, toModel];
let fn = conversions[graph[toModel].parent][toModel];
let cur = graph[toModel].parent;
while (graph[cur].parent) {
path.unshift(graph[cur].parent);
fn = link(conversions[graph[cur].parent][cur], fn);
cur = graph[cur].parent;
}
fn.conversion = path;
return fn;
}
module.exports = function (fromModel) {
const graph = deriveBFS(fromModel);
const conversion = {};
const models = Object.keys(graph);
for (let len = models.length, i = 0; i < len; i++) {
const toModel = models[i];
const node = graph[toModel];
if (node.parent === null) {
// No possible conversion, or this node is the source model.
continue;
}
conversion[toModel] = wrapConversion(toModel, graph);
}
return conversion;
};

8
node_modules/ava/node_modules/color-name/LICENSE generated vendored Normal file
View file

@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright (c) 2015 Dmitry Ivanov
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.

11
node_modules/ava/node_modules/color-name/README.md generated vendored Normal file
View file

@ -0,0 +1,11 @@
A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors.
[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/)
```js
var colors = require('color-name');
colors.red //[255,0,0]
```
<a href="LICENSE"><img src="https://upload.wikimedia.org/wikipedia/commons/0/0c/MIT_logo.svg" width="120"/></a>

152
node_modules/ava/node_modules/color-name/index.js generated vendored Normal file
View file

@ -0,0 +1,152 @@
'use strict'
module.exports = {
"aliceblue": [240, 248, 255],
"antiquewhite": [250, 235, 215],
"aqua": [0, 255, 255],
"aquamarine": [127, 255, 212],
"azure": [240, 255, 255],
"beige": [245, 245, 220],
"bisque": [255, 228, 196],
"black": [0, 0, 0],
"blanchedalmond": [255, 235, 205],
"blue": [0, 0, 255],
"blueviolet": [138, 43, 226],
"brown": [165, 42, 42],
"burlywood": [222, 184, 135],
"cadetblue": [95, 158, 160],
"chartreuse": [127, 255, 0],
"chocolate": [210, 105, 30],
"coral": [255, 127, 80],
"cornflowerblue": [100, 149, 237],
"cornsilk": [255, 248, 220],
"crimson": [220, 20, 60],
"cyan": [0, 255, 255],
"darkblue": [0, 0, 139],
"darkcyan": [0, 139, 139],
"darkgoldenrod": [184, 134, 11],
"darkgray": [169, 169, 169],
"darkgreen": [0, 100, 0],
"darkgrey": [169, 169, 169],
"darkkhaki": [189, 183, 107],
"darkmagenta": [139, 0, 139],
"darkolivegreen": [85, 107, 47],
"darkorange": [255, 140, 0],
"darkorchid": [153, 50, 204],
"darkred": [139, 0, 0],
"darksalmon": [233, 150, 122],
"darkseagreen": [143, 188, 143],
"darkslateblue": [72, 61, 139],
"darkslategray": [47, 79, 79],
"darkslategrey": [47, 79, 79],
"darkturquoise": [0, 206, 209],
"darkviolet": [148, 0, 211],
"deeppink": [255, 20, 147],
"deepskyblue": [0, 191, 255],
"dimgray": [105, 105, 105],
"dimgrey": [105, 105, 105],
"dodgerblue": [30, 144, 255],
"firebrick": [178, 34, 34],
"floralwhite": [255, 250, 240],
"forestgreen": [34, 139, 34],
"fuchsia": [255, 0, 255],
"gainsboro": [220, 220, 220],
"ghostwhite": [248, 248, 255],
"gold": [255, 215, 0],
"goldenrod": [218, 165, 32],
"gray": [128, 128, 128],
"green": [0, 128, 0],
"greenyellow": [173, 255, 47],
"grey": [128, 128, 128],
"honeydew": [240, 255, 240],
"hotpink": [255, 105, 180],
"indianred": [205, 92, 92],
"indigo": [75, 0, 130],
"ivory": [255, 255, 240],
"khaki": [240, 230, 140],
"lavender": [230, 230, 250],
"lavenderblush": [255, 240, 245],
"lawngreen": [124, 252, 0],
"lemonchiffon": [255, 250, 205],
"lightblue": [173, 216, 230],
"lightcoral": [240, 128, 128],
"lightcyan": [224, 255, 255],
"lightgoldenrodyellow": [250, 250, 210],
"lightgray": [211, 211, 211],
"lightgreen": [144, 238, 144],
"lightgrey": [211, 211, 211],
"lightpink": [255, 182, 193],
"lightsalmon": [255, 160, 122],
"lightseagreen": [32, 178, 170],
"lightskyblue": [135, 206, 250],
"lightslategray": [119, 136, 153],
"lightslategrey": [119, 136, 153],
"lightsteelblue": [176, 196, 222],
"lightyellow": [255, 255, 224],
"lime": [0, 255, 0],
"limegreen": [50, 205, 50],
"linen": [250, 240, 230],
"magenta": [255, 0, 255],
"maroon": [128, 0, 0],
"mediumaquamarine": [102, 205, 170],
"mediumblue": [0, 0, 205],
"mediumorchid": [186, 85, 211],
"mediumpurple": [147, 112, 219],
"mediumseagreen": [60, 179, 113],
"mediumslateblue": [123, 104, 238],
"mediumspringgreen": [0, 250, 154],
"mediumturquoise": [72, 209, 204],
"mediumvioletred": [199, 21, 133],
"midnightblue": [25, 25, 112],
"mintcream": [245, 255, 250],
"mistyrose": [255, 228, 225],
"moccasin": [255, 228, 181],
"navajowhite": [255, 222, 173],
"navy": [0, 0, 128],
"oldlace": [253, 245, 230],
"olive": [128, 128, 0],
"olivedrab": [107, 142, 35],
"orange": [255, 165, 0],
"orangered": [255, 69, 0],
"orchid": [218, 112, 214],
"palegoldenrod": [238, 232, 170],
"palegreen": [152, 251, 152],
"paleturquoise": [175, 238, 238],
"palevioletred": [219, 112, 147],
"papayawhip": [255, 239, 213],
"peachpuff": [255, 218, 185],
"peru": [205, 133, 63],
"pink": [255, 192, 203],
"plum": [221, 160, 221],
"powderblue": [176, 224, 230],
"purple": [128, 0, 128],
"rebeccapurple": [102, 51, 153],
"red": [255, 0, 0],
"rosybrown": [188, 143, 143],
"royalblue": [65, 105, 225],
"saddlebrown": [139, 69, 19],
"salmon": [250, 128, 114],
"sandybrown": [244, 164, 96],
"seagreen": [46, 139, 87],
"seashell": [255, 245, 238],
"sienna": [160, 82, 45],
"silver": [192, 192, 192],
"skyblue": [135, 206, 235],
"slateblue": [106, 90, 205],
"slategray": [112, 128, 144],
"slategrey": [112, 128, 144],
"snow": [255, 250, 250],
"springgreen": [0, 255, 127],
"steelblue": [70, 130, 180],
"tan": [210, 180, 140],
"teal": [0, 128, 128],
"thistle": [216, 191, 216],
"tomato": [255, 99, 71],
"turquoise": [64, 224, 208],
"violet": [238, 130, 238],
"wheat": [245, 222, 179],
"white": [255, 255, 255],
"whitesmoke": [245, 245, 245],
"yellow": [255, 255, 0],
"yellowgreen": [154, 205, 50]
};

28
node_modules/ava/node_modules/color-name/package.json generated vendored Normal file
View file

@ -0,0 +1,28 @@
{
"name": "color-name",
"version": "1.1.4",
"description": "A list of color names and its values",
"main": "index.js",
"files": [
"index.js"
],
"scripts": {
"test": "node test.js"
},
"repository": {
"type": "git",
"url": "git@github.com:colorjs/color-name.git"
},
"keywords": [
"color-name",
"color",
"color-keyword",
"keyword"
],
"author": "DY <dfcreative@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/colorjs/color-name/issues"
},
"homepage": "https://github.com/colorjs/color-name"
}

View file

@ -0,0 +1,18 @@
/**
Escape RegExp special characters.
You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class.
@example
```
import escapeStringRegexp = require('escape-string-regexp');
const escapedString = escapeStringRegexp('How much $ for a 🦄?');
//=> 'How much \\$ for a 🦄\\?'
new RegExp(escapedString);
```
*/
declare const escapeStringRegexp: (string: string) => string;
export = escapeStringRegexp;

View file

@ -0,0 +1,11 @@
'use strict';
const matchOperatorsRegex = /[|\\{}()[\]^$+*?.-]/g;
module.exports = string => {
if (typeof string !== 'string') {
throw new TypeError('Expected a string');
}
return string.replace(matchOperatorsRegex, '\\$&');
};

View file

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

View file

@ -0,0 +1,43 @@
{
"name": "escape-string-regexp",
"version": "2.0.0",
"description": "Escape RegExp special characters",
"license": "MIT",
"repository": "sindresorhus/escape-string-regexp",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"maintainers": [
"Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)",
"Joshua Boy Nicolai Appelman <joshua@jbna.nl> (jbna.nl)"
],
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"escape",
"regex",
"regexp",
"re",
"regular",
"expression",
"string",
"str",
"special",
"characters"
],
"devDependencies": {
"ava": "^1.4.1",
"tsd": "^0.7.2",
"xo": "^0.24.0"
}
}

View file

@ -0,0 +1,29 @@
# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp)
> Escape RegExp special characters
## Install
```
$ npm install escape-string-regexp
```
## Usage
```js
const escapeStringRegexp = require('escape-string-regexp');
const escapedString = escapeStringRegexp('How much $ for a 🦄?');
//=> 'How much \\$ for a 🦄\\?'
new RegExp(escapedString);
```
You can also use this to escape a string that is inserted into the middle of a regex, for example, into a character class.
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

39
node_modules/ava/node_modules/has-flag/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,39 @@
/**
Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag.
@param flag - CLI flag to look for. The `--` prefix is optional.
@param argv - CLI arguments. Default: `process.argv`.
@returns Whether the flag exists.
@example
```
// $ ts-node foo.ts -f --unicorn --foo=bar -- --rainbow
// foo.ts
import hasFlag = require('has-flag');
hasFlag('unicorn');
//=> true
hasFlag('--unicorn');
//=> true
hasFlag('f');
//=> true
hasFlag('-f');
//=> true
hasFlag('foo=bar');
//=> true
hasFlag('foo');
//=> false
hasFlag('rainbow');
//=> false
```
*/
declare function hasFlag(flag: string, argv?: string[]): boolean;
export = hasFlag;

8
node_modules/ava/node_modules/has-flag/index.js generated vendored Normal file
View file

@ -0,0 +1,8 @@
'use strict';
module.exports = (flag, argv = process.argv) => {
const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');
const position = argv.indexOf(prefix + flag);
const terminatorPosition = argv.indexOf('--');
return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
};

9
node_modules/ava/node_modules/has-flag/license generated vendored Normal file
View file

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

46
node_modules/ava/node_modules/has-flag/package.json generated vendored Normal file
View file

@ -0,0 +1,46 @@
{
"name": "has-flag",
"version": "4.0.0",
"description": "Check if argv has a specific flag",
"license": "MIT",
"repository": "sindresorhus/has-flag",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"has",
"check",
"detect",
"contains",
"find",
"flag",
"cli",
"command-line",
"argv",
"process",
"arg",
"args",
"argument",
"arguments",
"getopt",
"minimist",
"optimist"
],
"devDependencies": {
"ava": "^1.4.1",
"tsd": "^0.7.2",
"xo": "^0.24.0"
}
}

89
node_modules/ava/node_modules/has-flag/readme.md generated vendored Normal file
View file

@ -0,0 +1,89 @@
# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag)
> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag
Correctly stops looking after an `--` argument terminator.
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-has-flag?utm_source=npm-has-flag&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
---
## Install
```
$ npm install has-flag
```
## Usage
```js
// foo.js
const hasFlag = require('has-flag');
hasFlag('unicorn');
//=> true
hasFlag('--unicorn');
//=> true
hasFlag('f');
//=> true
hasFlag('-f');
//=> true
hasFlag('foo=bar');
//=> true
hasFlag('foo');
//=> false
hasFlag('rainbow');
//=> false
```
```
$ node foo.js -f --unicorn --foo=bar -- --rainbow
```
## API
### hasFlag(flag, [argv])
Returns a boolean for whether the flag exists.
#### flag
Type: `string`
CLI flag to look for. The `--` prefix is optional.
#### argv
Type: `string[]`<br>
Default: `process.argv`
CLI arguments.
## Security
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Evan Wallace
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,284 @@
# Source Map Support
[![Build Status](https://travis-ci.org/evanw/node-source-map-support.svg?branch=master)](https://travis-ci.org/evanw/node-source-map-support)
This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process.
## Installation and Usage
#### Node support
```
$ npm install source-map-support
```
Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler):
```
//# sourceMappingURL=path/to/source.map
```
If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be
respected (e.g. if a file mentions the comment in code, or went through multiple transpilers).
The path should either be absolute or relative to the compiled file.
From here you have two options.
##### CLI Usage
```bash
node -r source-map-support/register compiled.js
```
##### Programmatic Usage
Put the following line at the top of the compiled file.
```js
require('source-map-support').install();
```
It is also possible to install the source map support directly by
requiring the `register` module which can be handy with ES6:
```js
import 'source-map-support/register'
// Instead of:
import sourceMapSupport from 'source-map-support'
sourceMapSupport.install()
```
Note: if you're using babel-register, it includes source-map-support already.
It is also very useful with Mocha:
```
$ mocha --require source-map-support/register tests/
```
#### Browser support
This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code.
This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify.
```html
<script src="browser-source-map-support.js"></script>
<script>sourceMapSupport.install();</script>
```
This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency:
```html
<script>
define(['browser-source-map-support'], function(sourceMapSupport) {
sourceMapSupport.install();
});
</script>
```
## Options
This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer:
```js
require('source-map-support').install({
handleUncaughtExceptions: false
});
```
This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access.
```js
require('source-map-support').install({
retrieveSourceMap: function(source) {
if (source === 'compiled.js') {
return {
url: 'original.js',
map: fs.readFileSync('compiled.js.map', 'utf8')
};
}
return null;
}
});
```
The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment.
In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'.
```js
require('source-map-support').install({
environment: 'node'
});
```
To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps.
```js
require('source-map-support').install({
hookRequire: true
});
```
This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage.
## Demos
#### Basic Demo
original.js:
```js
throw new Error('test'); // This is the original code
```
compiled.js:
```js
require('source-map-support').install();
throw new Error('test'); // This is the compiled code
// The next line defines the sourceMapping.
//# sourceMappingURL=compiled.js.map
```
compiled.js.map:
```json
{
"version": 3,
"file": "compiled.js",
"sources": ["original.js"],
"names": [],
"mappings": ";;AAAA,MAAM,IAAI"
}
```
Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js):
```
$ node compiled.js
original.js:1
throw new Error('test'); // This is the original code
^
Error: test
at Object.<anonymous> (original.js:1:7)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
#### TypeScript Demo
demo.ts:
```typescript
declare function require(name: string);
require('source-map-support').install();
class Foo {
constructor() { this.bar(); }
bar() { throw new Error('this is a demo'); }
}
new Foo();
```
Compile and run the file using the TypeScript compiler from the terminal:
```
$ npm install source-map-support typescript
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
$ node demo.js
demo.ts:5
bar() { throw new Error('this is a demo'); }
^
Error: this is a demo
at Foo.bar (demo.ts:5:17)
at new Foo (demo.ts:4:24)
at Object.<anonymous> (demo.ts:7:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('source-map-support').install()` in the code base:
```
$ npm install source-map-support typescript
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
$ node -r source-map-support/register demo.js
demo.ts:5
bar() { throw new Error('this is a demo'); }
^
Error: this is a demo
at Foo.bar (demo.ts:5:17)
at new Foo (demo.ts:4:24)
at Object.<anonymous> (demo.ts:7:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
#### CoffeeScript Demo
demo.coffee:
```coffee
require('source-map-support').install()
foo = ->
bar = -> throw new Error 'this is a demo'
bar()
foo()
```
Compile and run the file using the CoffeeScript compiler from the terminal:
```sh
$ npm install source-map-support coffeescript
$ node_modules/.bin/coffee --map --compile demo.coffee
$ node demo.js
demo.coffee:3
bar = -> throw new Error 'this is a demo'
^
Error: this is a demo
at bar (demo.coffee:3:22)
at foo (demo.coffee:4:3)
at Object.<anonymous> (demo.coffee:5:1)
at Object.<anonymous> (demo.coffee:1:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
```
## Tests
This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests:
* Build the tests using `build.js`
* Launch the HTTP server (`npm run serve-tests`) and visit
* http://127.0.0.1:1336/amd-test
* http://127.0.0.1:1336/browser-test
* http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details).
* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/
## License
This code is available under the [MIT license](http://opensource.org/licenses/MIT).

View file

@ -0,0 +1,114 @@
/*
* Support for source maps in V8 stack traces
* https://github.com/evanw/node-source-map-support
*/
/*
The buffer module from node.js, for the browser.
@author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
license MIT
*/
(this.define||function(G,J){this.sourceMapSupport=J()})("browser-source-map-support",function(G){(function b(n,x,m){function e(d,a){if(!x[d]){if(!n[d]){var l="function"==typeof require&&require;if(!a&&l)return l(d,!0);if(g)return g(d,!0);throw Error("Cannot find module '"+d+"'");}l=x[d]={exports:{}};n[d][0].call(l.exports,function(a){var b=n[d][1][a];return e(b?b:a)},l,l.exports,b,n,x,m)}return x[d].exports}for(var g="function"==typeof require&&require,h=0;h<m.length;h++)e(m[h]);return e})({1:[function(n,
x,m){G=n("./source-map-support")},{"./source-map-support":21}],2:[function(n,x,m){(function(b){function e(b){b=b.charCodeAt(0);if(43===b)return 62;if(47===b)return 63;if(48>b)return-1;if(58>b)return b-48+52;if(91>b)return b-65;if(123>b)return b-97+26}var g="undefined"!==typeof Uint8Array?Uint8Array:Array;b.toByteArray=function(b){function d(a){r[v++]=a}if(0<b.length%4)throw Error("Invalid string. Length must be a multiple of 4");var a=b.length;var l="="===b.charAt(a-2)?2:"="===b.charAt(a-1)?1:0;var r=
new g(3*b.length/4-l);var q=0<l?b.length-4:b.length;var v=0;for(a=0;a<q;a+=4){var h=e(b.charAt(a))<<18|e(b.charAt(a+1))<<12|e(b.charAt(a+2))<<6|e(b.charAt(a+3));d((h&16711680)>>16);d((h&65280)>>8);d(h&255)}2===l?(h=e(b.charAt(a))<<2|e(b.charAt(a+1))>>4,d(h&255)):1===l&&(h=e(b.charAt(a))<<10|e(b.charAt(a+1))<<4|e(b.charAt(a+2))>>2,d(h>>8&255),d(h&255));return r};b.fromByteArray=function(b){var d=b.length%3,a="",l;var e=0;for(l=b.length-d;e<l;e+=3){var g=(b[e]<<16)+(b[e+1]<<8)+b[e+2];g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g>>
18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g&63);a+=g}switch(d){case 1:g=b[b.length-1];a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g>>2);a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g<<4&63);a+="==";break;case 2:g=(b[b.length-2]<<8)+
b[b.length-1],a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g>>10),a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g>>4&63),a+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(g<<2&63),a+="="}return a}})("undefined"===typeof m?this.base64js={}:m)},{}],3:[function(n,x,m){},{}],4:[function(n,x,m){(function(b){var e=Object.prototype.toString,g="function"===typeof b.alloc&&"function"===typeof b.allocUnsafe&&"function"===
typeof b.from;x.exports=function(h,d,a){if("number"===typeof h)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===e.call(h).slice(8,-1)){d>>>=0;var l=h.byteLength-d;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===a)a=l;else if(a>>>=0,a>l)throw new RangeError("'length' is out of bounds");return g?b.from(h.slice(d,d+a)):new b(new Uint8Array(h.slice(d,d+a)))}if("string"===typeof h){a=d;if("string"!==typeof a||""===a)a="utf8";if(!b.isEncoding(a))throw new TypeError('"encoding" must be a valid string encoding');
return g?b.from(h,a):new b(h,a)}return g?b.from(h):new b(h)}}).call(this,n("buffer").Buffer)},{buffer:5}],5:[function(n,x,m){function b(f,p,a){if(!(this instanceof b))return new b(f,p,a);var c=typeof f;if("number"===c)var d=0<f?f>>>0:0;else if("string"===c){if("base64"===p)for(f=(f.trim?f.trim():f.replace(/^\s+|\s+$/g,"")).replace(H,"");0!==f.length%4;)f+="=";d=b.byteLength(f,p)}else if("object"===c&&null!==f)"Buffer"===f.type&&F(f.data)&&(f=f.data),d=0<+f.length?Math.floor(+f.length):0;else throw new TypeError("must start with number, buffer, array or string");
if(this.length>D)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+D.toString(16)+" bytes");if(b.TYPED_ARRAY_SUPPORT)var k=b._augment(new Uint8Array(d));else k=this,k.length=d,k._isBuffer=!0;if(b.TYPED_ARRAY_SUPPORT&&"number"===typeof f.byteLength)k._set(f);else{var C=f;if(F(C)||b.isBuffer(C)||C&&"object"===typeof C&&"number"===typeof C.length)if(b.isBuffer(f))for(p=0;p<d;p++)k[p]=f.readUInt8(p);else for(p=0;p<d;p++)k[p]=(f[p]%256+256)%256;else if("string"===c)k.write(f,
0,p);else if("number"===c&&!b.TYPED_ARRAY_SUPPORT&&!a)for(p=0;p<d;p++)k[p]=0}return k}function e(f,p,b){var a="";for(b=Math.min(f.length,b);p<b;p++)a+=String.fromCharCode(f[p]);return a}function g(f,p,b){if(0!==f%1||0>f)throw new RangeError("offset is not uint");if(f+p>b)throw new RangeError("Trying to access beyond buffer length");}function h(f,p,a,c,d,k){if(!b.isBuffer(f))throw new TypeError("buffer must be a Buffer instance");if(p>d||p<k)throw new TypeError("value is out of bounds");if(a+c>f.length)throw new TypeError("index out of range");
}function d(f,p,b,a){0>p&&(p=65535+p+1);for(var c=0,d=Math.min(f.length-b,2);c<d;c++)f[b+c]=(p&255<<8*(a?c:1-c))>>>8*(a?c:1-c)}function a(f,p,b,a){0>p&&(p=4294967295+p+1);for(var c=0,d=Math.min(f.length-b,4);c<d;c++)f[b+c]=p>>>8*(a?c:3-c)&255}function l(f,p,b,a,c,d){if(p>c||p<d)throw new TypeError("value is out of bounds");if(b+a>f.length)throw new TypeError("index out of range");}function r(f,p,b,a,c){c||l(f,p,b,4,3.4028234663852886E38,-3.4028234663852886E38);y.write(f,p,b,a,23,4);return b+4}function q(f,
p,b,a,c){c||l(f,p,b,8,1.7976931348623157E308,-1.7976931348623157E308);y.write(f,p,b,a,52,8);return b+8}function v(f){for(var p=[],b=0;b<f.length;b++){var a=f.charCodeAt(b);if(127>=a)p.push(a);else{var c=b;55296<=a&&57343>=a&&b++;a=encodeURIComponent(f.slice(c,b+1)).substr(1).split("%");for(c=0;c<a.length;c++)p.push(parseInt(a[c],16))}}return p}function u(f){for(var b=[],a=0;a<f.length;a++)b.push(f.charCodeAt(a)&255);return b}function c(f,b,a,c,d){d&&(c-=c%d);for(d=0;d<c&&!(d+a>=b.length||d>=f.length);d++)b[d+
a]=f[d];return d}function k(f){try{return decodeURIComponent(f)}catch(p){return String.fromCharCode(65533)}}var w=n("base64-js"),y=n("ieee754"),F=n("is-array");m.Buffer=b;m.SlowBuffer=b;m.INSPECT_MAX_BYTES=50;b.poolSize=8192;var D=1073741823;b.TYPED_ARRAY_SUPPORT=function(){try{var f=new ArrayBuffer(0),b=new Uint8Array(f);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(C){return!1}}();b.isBuffer=function(f){return!(null==
f||!f._isBuffer)};b.compare=function(f,a){if(!b.isBuffer(f)||!b.isBuffer(a))throw new TypeError("Arguments must be Buffers");for(var c=f.length,p=a.length,d=0,k=Math.min(c,p);d<k&&f[d]===a[d];d++);d!==k&&(c=f[d],p=a[d]);return c<p?-1:p<c?1:0};b.isEncoding=function(f){switch(String(f).toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "binary":case "base64":case "raw":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return!0;default:return!1}};b.concat=function(f,a){if(!F(f))throw new TypeError("Usage: Buffer.concat(list[, length])");
if(0===f.length)return new b(0);if(1===f.length)return f[0];var c;if(void 0===a)for(c=a=0;c<f.length;c++)a+=f[c].length;var p=new b(a),d=0;for(c=0;c<f.length;c++){var k=f[c];k.copy(p,d);d+=k.length}return p};b.byteLength=function(f,a){f+="";switch(a||"utf8"){case "ascii":case "binary":case "raw":var b=f.length;break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=2*f.length;break;case "hex":b=f.length>>>1;break;case "utf8":case "utf-8":b=v(f).length;break;case "base64":b=w.toByteArray(f).length;
break;default:b=f.length}return b};b.prototype.length=void 0;b.prototype.parent=void 0;b.prototype.toString=function(f,b,a){var c=!1;b>>>=0;a=void 0===a||Infinity===a?this.length:a>>>0;f||(f="utf8");0>b&&(b=0);a>this.length&&(a=this.length);if(a<=b)return"";for(;;)switch(f){case "hex":f=b;b=a;a=this.length;if(!f||0>f)f=0;if(!b||0>b||b>a)b=a;c="";for(a=f;a<b;a++)f=c,c=this[a],c=16>c?"0"+c.toString(16):c.toString(16),c=f+c;return c;case "utf8":case "utf-8":c=f="";for(a=Math.min(this.length,a);b<a;b++)127>=
this[b]?(f+=k(c)+String.fromCharCode(this[b]),c=""):c+="%"+this[b].toString(16);return f+k(c);case "ascii":return e(this,b,a);case "binary":return e(this,b,a);case "base64":return b=0===b&&a===this.length?w.fromByteArray(this):w.fromByteArray(this.slice(b,a)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,a);a="";for(f=0;f<b.length;f+=2)a+=String.fromCharCode(b[f]+256*b[f+1]);return a;default:if(c)throw new TypeError("Unknown encoding: "+f);f=(f+"").toLowerCase();c=!0}};
b.prototype.equals=function(f){if(!b.isBuffer(f))throw new TypeError("Argument must be a Buffer");return 0===b.compare(this,f)};b.prototype.inspect=function(){var f="",b=m.INSPECT_MAX_BYTES;0<this.length&&(f=this.toString("hex",0,b).match(/.{2}/g).join(" "),this.length>b&&(f+=" ... "));return"<Buffer "+f+">"};b.prototype.compare=function(f){if(!b.isBuffer(f))throw new TypeError("Argument must be a Buffer");return b.compare(this,f)};b.prototype.get=function(f){console.log(".get() is deprecated. Access using array indexes instead.");
return this.readUInt8(f)};b.prototype.set=function(f,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(f,b)};b.prototype.write=function(f,b,a,d){if(isFinite(b))isFinite(a)||(d=a,a=void 0);else{var p=d;d=b;b=a;a=p}b=Number(b)||0;p=this.length-b;a?(a=Number(a),a>p&&(a=p)):a=p;d=String(d||"utf8").toLowerCase();switch(d){case "hex":b=Number(b)||0;d=this.length-b;a?(a=Number(a),a>d&&(a=d)):a=d;d=f.length;if(0!==d%2)throw Error("Invalid hex string");a>d/
2&&(a=d/2);for(d=0;d<a;d++){p=parseInt(f.substr(2*d,2),16);if(isNaN(p))throw Error("Invalid hex string");this[b+d]=p}f=d;break;case "utf8":case "utf-8":f=c(v(f),this,b,a);break;case "ascii":f=c(u(f),this,b,a);break;case "binary":f=c(u(f),this,b,a);break;case "base64":f=c(w.toByteArray(f),this,b,a);break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":p=[];for(var k=0;k<f.length;k++){var l=f.charCodeAt(k);d=l>>8;l%=256;p.push(l);p.push(d)}f=c(p,this,b,a,2);break;default:throw new TypeError("Unknown encoding: "+
d);}return f};b.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};b.prototype.slice=function(f,a){var c=this.length;f=~~f;a=void 0===a?c:~~a;0>f?(f+=c,0>f&&(f=0)):f>c&&(f=c);0>a?(a+=c,0>a&&(a=0)):a>c&&(a=c);a<f&&(a=f);if(b.TYPED_ARRAY_SUPPORT)return b._augment(this.subarray(f,a));c=a-f;for(var d=new b(c,void 0,!0),p=0;p<c;p++)d[p]=this[p+f];return d};b.prototype.readUInt8=function(f,a){a||g(f,1,this.length);return this[f]};b.prototype.readUInt16LE=
function(f,a){a||g(f,2,this.length);return this[f]|this[f+1]<<8};b.prototype.readUInt16BE=function(f,a){a||g(f,2,this.length);return this[f]<<8|this[f+1]};b.prototype.readUInt32LE=function(f,a){a||g(f,4,this.length);return(this[f]|this[f+1]<<8|this[f+2]<<16)+16777216*this[f+3]};b.prototype.readUInt32BE=function(f,a){a||g(f,4,this.length);return 16777216*this[f]+(this[f+1]<<16|this[f+2]<<8|this[f+3])};b.prototype.readInt8=function(f,a){a||g(f,1,this.length);return this[f]&128?-1*(255-this[f]+1):this[f]};
b.prototype.readInt16LE=function(f,a){a||g(f,2,this.length);var b=this[f]|this[f+1]<<8;return b&32768?b|4294901760:b};b.prototype.readInt16BE=function(f,a){a||g(f,2,this.length);var b=this[f+1]|this[f]<<8;return b&32768?b|4294901760:b};b.prototype.readInt32LE=function(f,a){a||g(f,4,this.length);return this[f]|this[f+1]<<8|this[f+2]<<16|this[f+3]<<24};b.prototype.readInt32BE=function(a,b){b||g(a,4,this.length);return this[a]<<24|this[a+1]<<16|this[a+2]<<8|this[a+3]};b.prototype.readFloatLE=function(a,
b){b||g(a,4,this.length);return y.read(this,a,!0,23,4)};b.prototype.readFloatBE=function(a,b){b||g(a,4,this.length);return y.read(this,a,!1,23,4)};b.prototype.readDoubleLE=function(a,b){b||g(a,8,this.length);return y.read(this,a,!0,52,8)};b.prototype.readDoubleBE=function(a,b){b||g(a,8,this.length);return y.read(this,a,!1,52,8)};b.prototype.writeUInt8=function(a,c,d){a=+a;c>>>=0;d||h(this,a,c,1,255,0);b.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[c]=a;return c+1};b.prototype.writeUInt16LE=function(a,
c,k){a=+a;c>>>=0;k||h(this,a,c,2,65535,0);b.TYPED_ARRAY_SUPPORT?(this[c]=a,this[c+1]=a>>>8):d(this,a,c,!0);return c+2};b.prototype.writeUInt16BE=function(a,c,k){a=+a;c>>>=0;k||h(this,a,c,2,65535,0);b.TYPED_ARRAY_SUPPORT?(this[c]=a>>>8,this[c+1]=a):d(this,a,c,!1);return c+2};b.prototype.writeUInt32LE=function(f,c,d){f=+f;c>>>=0;d||h(this,f,c,4,4294967295,0);b.TYPED_ARRAY_SUPPORT?(this[c+3]=f>>>24,this[c+2]=f>>>16,this[c+1]=f>>>8,this[c]=f):a(this,f,c,!0);return c+4};b.prototype.writeUInt32BE=function(f,
c,d){f=+f;c>>>=0;d||h(this,f,c,4,4294967295,0);b.TYPED_ARRAY_SUPPORT?(this[c]=f>>>24,this[c+1]=f>>>16,this[c+2]=f>>>8,this[c+3]=f):a(this,f,c,!1);return c+4};b.prototype.writeInt8=function(a,c,d){a=+a;c>>>=0;d||h(this,a,c,1,127,-128);b.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[c]=a;return c+1};b.prototype.writeInt16LE=function(a,c,k){a=+a;c>>>=0;k||h(this,a,c,2,32767,-32768);b.TYPED_ARRAY_SUPPORT?(this[c]=a,this[c+1]=a>>>8):d(this,a,c,!0);return c+2};b.prototype.writeInt16BE=function(a,
c,k){a=+a;c>>>=0;k||h(this,a,c,2,32767,-32768);b.TYPED_ARRAY_SUPPORT?(this[c]=a>>>8,this[c+1]=a):d(this,a,c,!1);return c+2};b.prototype.writeInt32LE=function(c,d,k){c=+c;d>>>=0;k||h(this,c,d,4,2147483647,-2147483648);b.TYPED_ARRAY_SUPPORT?(this[d]=c,this[d+1]=c>>>8,this[d+2]=c>>>16,this[d+3]=c>>>24):a(this,c,d,!0);return d+4};b.prototype.writeInt32BE=function(c,d,k){c=+c;d>>>=0;k||h(this,c,d,4,2147483647,-2147483648);0>c&&(c=4294967295+c+1);b.TYPED_ARRAY_SUPPORT?(this[d]=c>>>24,this[d+1]=c>>>16,this[d+
2]=c>>>8,this[d+3]=c):a(this,c,d,!1);return d+4};b.prototype.writeFloatLE=function(a,c,b){return r(this,a,c,!0,b)};b.prototype.writeFloatBE=function(a,c,b){return r(this,a,c,!1,b)};b.prototype.writeDoubleLE=function(a,c,b){return q(this,a,c,!0,b)};b.prototype.writeDoubleBE=function(a,c,b){return q(this,a,c,!1,b)};b.prototype.copy=function(a,c,d,k){d||(d=0);k||0===k||(k=this.length);c||(c=0);if(k!==d&&0!==a.length&&0!==this.length){if(k<d)throw new TypeError("sourceEnd < sourceStart");if(0>c||c>=a.length)throw new TypeError("targetStart out of bounds");
if(0>d||d>=this.length)throw new TypeError("sourceStart out of bounds");if(0>k||k>this.length)throw new TypeError("sourceEnd out of bounds");k>this.length&&(k=this.length);a.length-c<k-d&&(k=a.length-c+d);k-=d;if(1E3>k||!b.TYPED_ARRAY_SUPPORT)for(var f=0;f<k;f++)a[f+c]=this[f+d];else a._set(this.subarray(d,d+k),c)}};b.prototype.fill=function(a,c,b){a||(a=0);c||(c=0);b||(b=this.length);if(b<c)throw new TypeError("end < start");if(b!==c&&0!==this.length){if(0>c||c>=this.length)throw new TypeError("start out of bounds");
if(0>b||b>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;c<b;c++)this[c]=a;else{a=v(a.toString());for(var d=a.length;c<b;c++)this[c]=a[c%d]}return this}};b.prototype.toArrayBuffer=function(){if("undefined"!==typeof Uint8Array){if(b.TYPED_ARRAY_SUPPORT)return(new b(this)).buffer;for(var a=new Uint8Array(this.length),c=0,d=a.length;c<d;c+=1)a[c]=this[c];return a.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser");};var t=b.prototype;b._augment=
function(a){a.constructor=b;a._isBuffer=!0;a._get=a.get;a._set=a.set;a.get=t.get;a.set=t.set;a.write=t.write;a.toString=t.toString;a.toLocaleString=t.toString;a.toJSON=t.toJSON;a.equals=t.equals;a.compare=t.compare;a.copy=t.copy;a.slice=t.slice;a.readUInt8=t.readUInt8;a.readUInt16LE=t.readUInt16LE;a.readUInt16BE=t.readUInt16BE;a.readUInt32LE=t.readUInt32LE;a.readUInt32BE=t.readUInt32BE;a.readInt8=t.readInt8;a.readInt16LE=t.readInt16LE;a.readInt16BE=t.readInt16BE;a.readInt32LE=t.readInt32LE;a.readInt32BE=
t.readInt32BE;a.readFloatLE=t.readFloatLE;a.readFloatBE=t.readFloatBE;a.readDoubleLE=t.readDoubleLE;a.readDoubleBE=t.readDoubleBE;a.writeUInt8=t.writeUInt8;a.writeUInt16LE=t.writeUInt16LE;a.writeUInt16BE=t.writeUInt16BE;a.writeUInt32LE=t.writeUInt32LE;a.writeUInt32BE=t.writeUInt32BE;a.writeInt8=t.writeInt8;a.writeInt16LE=t.writeInt16LE;a.writeInt16BE=t.writeInt16BE;a.writeInt32LE=t.writeInt32LE;a.writeInt32BE=t.writeInt32BE;a.writeFloatLE=t.writeFloatLE;a.writeFloatBE=t.writeFloatBE;a.writeDoubleLE=
t.writeDoubleLE;a.writeDoubleBE=t.writeDoubleBE;a.fill=t.fill;a.inspect=t.inspect;a.toArrayBuffer=t.toArrayBuffer;return a};var H=/[^+\/0-9A-z]/g},{"base64-js":2,ieee754:6,"is-array":7}],6:[function(n,x,m){m.read=function(b,e,g,h,d){var a=8*d-h-1;var l=(1<<a)-1,r=l>>1,q=-7;d=g?d-1:0;var v=g?-1:1,u=b[e+d];d+=v;g=u&(1<<-q)-1;u>>=-q;for(q+=a;0<q;g=256*g+b[e+d],d+=v,q-=8);a=g&(1<<-q)-1;g>>=-q;for(q+=h;0<q;a=256*a+b[e+d],d+=v,q-=8);if(0===g)g=1-r;else{if(g===l)return a?NaN:Infinity*(u?-1:1);a+=Math.pow(2,
h);g-=r}return(u?-1:1)*a*Math.pow(2,g-h)};m.write=function(b,e,g,h,d,a){var l,r=8*a-d-1,q=(1<<r)-1,v=q>>1,u=23===d?Math.pow(2,-24)-Math.pow(2,-77):0;a=h?0:a-1;var c=h?1:-1,k=0>e||0===e&&0>1/e?1:0;e=Math.abs(e);isNaN(e)||Infinity===e?(e=isNaN(e)?1:0,h=q):(h=Math.floor(Math.log(e)/Math.LN2),1>e*(l=Math.pow(2,-h))&&(h--,l*=2),e=1<=h+v?e+u/l:e+u*Math.pow(2,1-v),2<=e*l&&(h++,l/=2),h+v>=q?(e=0,h=q):1<=h+v?(e=(e*l-1)*Math.pow(2,d),h+=v):(e=e*Math.pow(2,v-1)*Math.pow(2,d),h=0));for(;8<=d;b[g+a]=e&255,a+=
c,e/=256,d-=8);h=h<<d|e;for(r+=d;0<r;b[g+a]=h&255,a+=c,h/=256,r-=8);b[g+a-c]|=128*k}},{}],7:[function(n,x,m){var b=Object.prototype.toString;x.exports=Array.isArray||function(e){return!!e&&"[object Array]"==b.call(e)}},{}],8:[function(n,x,m){(function(b){function e(a,b){for(var d=0,l=a.length-1;0<=l;l--){var v=a[l];"."===v?a.splice(l,1):".."===v?(a.splice(l,1),d++):d&&(a.splice(l,1),d--)}if(b)for(;d--;d)a.unshift("..");return a}function g(a,b){if(a.filter)return a.filter(b);for(var d=[],l=0;l<a.length;l++)b(a[l],
l,a)&&d.push(a[l]);return d}var h=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;m.resolve=function(){for(var a="",d=!1,h=arguments.length-1;-1<=h&&!d;h--){var q=0<=h?arguments[h]:b.cwd();if("string"!==typeof q)throw new TypeError("Arguments to path.resolve must be strings");q&&(a=q+"/"+a,d="/"===q.charAt(0))}a=e(g(a.split("/"),function(a){return!!a}),!d).join("/");return(d?"/":"")+a||"."};m.normalize=function(a){var b=m.isAbsolute(a),h="/"===d(a,-1);(a=e(g(a.split("/"),function(a){return!!a}),
!b).join("/"))||b||(a=".");a&&h&&(a+="/");return(b?"/":"")+a};m.isAbsolute=function(a){return"/"===a.charAt(0)};m.join=function(){var a=Array.prototype.slice.call(arguments,0);return m.normalize(g(a,function(a,b){if("string"!==typeof a)throw new TypeError("Arguments to path.join must be strings");return a}).join("/"))};m.relative=function(a,b){function d(a){for(var c=0;c<a.length&&""===a[c];c++);for(var b=a.length-1;0<=b&&""===a[b];b--);return c>b?[]:a.slice(c,b-c+1)}a=m.resolve(a).substr(1);b=m.resolve(b).substr(1);
for(var l=d(a.split("/")),v=d(b.split("/")),e=Math.min(l.length,v.length),c=e,k=0;k<e;k++)if(l[k]!==v[k]){c=k;break}e=[];for(k=c;k<l.length;k++)e.push("..");e=e.concat(v.slice(c));return e.join("/")};m.sep="/";m.delimiter=":";m.dirname=function(a){var b=h.exec(a).slice(1);a=b[0];b=b[1];if(!a&&!b)return".";b&&(b=b.substr(0,b.length-1));return a+b};m.basename=function(a,b){var d=h.exec(a).slice(1)[2];b&&d.substr(-1*b.length)===b&&(d=d.substr(0,d.length-b.length));return d};m.extname=function(a){return h.exec(a).slice(1)[3]};
var d="b"==="ab".substr(-1)?function(a,b,d){return a.substr(b,d)}:function(a,b,d){0>b&&(b=a.length+b);return a.substr(b,d)}}).call(this,n("g5I+bs"))},{"g5I+bs":9}],9:[function(n,x,m){function b(){}n=x.exports={};n.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(b){return window.setImmediate(b)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var b=[];window.addEventListener("message",function(e){var g=e.source;g!==window&&null!==
g||"process-tick"!==e.data||(e.stopPropagation(),0<b.length&&b.shift()())},!0);return function(e){b.push(e);window.postMessage("process-tick","*")}}return function(b){setTimeout(b,0)}}();n.title="browser";n.browser=!0;n.env={};n.argv=[];n.on=b;n.addListener=b;n.once=b;n.off=b;n.removeListener=b;n.removeAllListeners=b;n.emit=b;n.binding=function(b){throw Error("process.binding is not supported");};n.cwd=function(){return"/"};n.chdir=function(b){throw Error("process.chdir is not supported");}},{}],
10:[function(n,x,m){function b(){this._array=[];this._set=h?new Map:Object.create(null)}var e=n("./util"),g=Object.prototype.hasOwnProperty,h="undefined"!==typeof Map;b.fromArray=function(d,a){for(var e=new b,g=0,h=d.length;g<h;g++)e.add(d[g],a);return e};b.prototype.size=function(){return h?this._set.size:Object.getOwnPropertyNames(this._set).length};b.prototype.add=function(b,a){var d=h?b:e.toSetString(b),r=h?this.has(b):g.call(this._set,d),q=this._array.length;r&&!a||this._array.push(b);r||(h?
this._set.set(b,q):this._set[d]=q)};b.prototype.has=function(b){if(h)return this._set.has(b);b=e.toSetString(b);return g.call(this._set,b)};b.prototype.indexOf=function(b){if(h){var a=this._set.get(b);if(0<=a)return a}else if(a=e.toSetString(b),g.call(this._set,a))return this._set[a];throw Error('"'+b+'" is not in the set.');};b.prototype.at=function(b){if(0<=b&&b<this._array.length)return this._array[b];throw Error("No element indexed by "+b);};b.prototype.toArray=function(){return this._array.slice()};
m.ArraySet=b},{"./util":19}],11:[function(n,x,m){var b=n("./base64");m.encode=function(e){var g="",h=0>e?(-e<<1)+1:e<<1;do e=h&31,h>>>=5,0<h&&(e|=32),g+=b.encode(e);while(0<h);return g};m.decode=function(e,g,h){var d=e.length,a=0,l=0;do{if(g>=d)throw Error("Expected more digits in base 64 VLQ value.");var r=b.decode(e.charCodeAt(g++));if(-1===r)throw Error("Invalid base64 digit: "+e.charAt(g-1));var q=!!(r&32);r&=31;a+=r<<l;l+=5}while(q);e=a>>1;h.value=1===(a&1)?-e:e;h.rest=g}},{"./base64":12}],12:[function(n,
x,m){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");m.encode=function(e){if(0<=e&&e<b.length)return b[e];throw new TypeError("Must be between 0 and 63: "+e);};m.decode=function(b){return 65<=b&&90>=b?b-65:97<=b&&122>=b?b-97+26:48<=b&&57>=b?b-48+52:43==b?62:47==b?63:-1}},{}],13:[function(n,x,m){function b(e,g,h,d,a,l){var r=Math.floor((g-e)/2)+e,q=a(h,d[r],!0);return 0===q?r:0<q?1<g-r?b(r,g,h,d,a,l):l==m.LEAST_UPPER_BOUND?g<d.length?g:-1:r:1<r-e?b(e,r,h,d,a,l):l==
m.LEAST_UPPER_BOUND?r:0>e?-1:e}m.GREATEST_LOWER_BOUND=1;m.LEAST_UPPER_BOUND=2;m.search=function(e,g,h,d){if(0===g.length)return-1;e=b(-1,g.length,e,g,h,d||m.GREATEST_LOWER_BOUND);if(0>e)return-1;for(;0<=e-1&&0===h(g[e],g[e-1],!0);)--e;return e}},{}],14:[function(n,x,m){function b(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var e=n("./util");b.prototype.unsortedForEach=function(b,e){this._array.forEach(b,e)};b.prototype.add=function(b){var g=this._last,d=g.generatedLine,
a=b.generatedLine,l=g.generatedColumn,r=b.generatedColumn;a>d||a==d&&r>=l||0>=e.compareByGeneratedPositionsInflated(g,b)?this._last=b:this._sorted=!1;this._array.push(b)};b.prototype.toArray=function(){this._sorted||(this._array.sort(e.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};m.MappingList=b},{"./util":19}],15:[function(n,x,m){function b(b,e,d){var a=b[e];b[e]=b[d];b[d]=a}function e(g,h,d,a){if(d<a){var l=d-1;b(g,Math.round(d+Math.random()*(a-d)),a);for(var r=g[a],
q=d;q<a;q++)0>=h(g[q],r)&&(l+=1,b(g,l,q));b(g,l+1,q);l+=1;e(g,h,d,l-1);e(g,h,l+1,a)}}m.quickSort=function(b,h){e(b,h,0,b.length-1)}},{}],16:[function(n,x,m){function b(a,b){var c=a;"string"===typeof a&&(c=d.parseSourceMapInput(a));return null!=c.sections?new h(c,b):new e(c,b)}function e(a,b){var c=a;"string"===typeof a&&(c=d.parseSourceMapInput(a));var k=d.getArg(c,"version"),e=d.getArg(c,"sources"),v=d.getArg(c,"names",[]),g=d.getArg(c,"sourceRoot",null),h=d.getArg(c,"sourcesContent",null),q=d.getArg(c,
"mappings");c=d.getArg(c,"file",null);if(k!=this._version)throw Error("Unsupported version: "+k);g&&(g=d.normalize(g));e=e.map(String).map(d.normalize).map(function(a){return g&&d.isAbsolute(g)&&d.isAbsolute(a)?d.relative(g,a):a});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(e,!0);this.sourceRoot=g;this.sourcesContent=h;this._mappings=q;this._sourceMapURL=b;this.file=c}function g(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source=
null}function h(a,e){var c=a;"string"===typeof a&&(c=d.parseSourceMapInput(a));var k=d.getArg(c,"version");c=d.getArg(c,"sections");if(k!=this._version)throw Error("Unsupported version: "+k);this._sources=new l;this._names=new l;var v={line:-1,column:0};this._sections=c.map(function(a){if(a.url)throw Error("Support for url field in sections not implemented.");var c=d.getArg(a,"offset"),k=d.getArg(c,"line"),g=d.getArg(c,"column");if(k<v.line||k===v.line&&g<v.column)throw Error("Section offsets must be ordered and non-overlapping.");
v=c;return{generatedOffset:{generatedLine:k+1,generatedColumn:g+1},consumer:new b(d.getArg(a,"map"),e)}})}var d=n("./util"),a=n("./binary-search"),l=n("./array-set").ArraySet,r=n("./base64-vlq"),q=n("./quick-sort").quickSort;b.fromSourceMap=function(a){return e.fromSourceMap(a)};b.prototype._version=3;b.prototype.__generatedMappings=null;Object.defineProperty(b.prototype,"_generatedMappings",{configurable:!0,enumerable:!0,get:function(){this.__generatedMappings||this._parseMappings(this._mappings,
this.sourceRoot);return this.__generatedMappings}});b.prototype.__originalMappings=null;Object.defineProperty(b.prototype,"_originalMappings",{configurable:!0,enumerable:!0,get:function(){this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot);return this.__originalMappings}});b.prototype._charIsMappingSeparator=function(a,b){var c=a.charAt(b);return";"===c||","===c};b.prototype._parseMappings=function(a,b){throw Error("Subclasses must implement _parseMappings");};b.GENERATED_ORDER=
1;b.ORIGINAL_ORDER=2;b.GREATEST_LOWER_BOUND=1;b.LEAST_UPPER_BOUND=2;b.prototype.eachMapping=function(a,e,c){e=e||null;switch(c||b.GENERATED_ORDER){case b.GENERATED_ORDER:c=this._generatedMappings;break;case b.ORIGINAL_ORDER:c=this._originalMappings;break;default:throw Error("Unknown order of iteration.");}var k=this.sourceRoot;c.map(function(a){var b=null===a.source?null:this._sources.at(a.source);b=d.computeSourceURL(k,b,this._sourceMapURL);return{source:b,generatedLine:a.generatedLine,generatedColumn:a.generatedColumn,
originalLine:a.originalLine,originalColumn:a.originalColumn,name:null===a.name?null:this._names.at(a.name)}},this).forEach(a,e)};b.prototype.allGeneratedPositionsFor=function(b){var e=d.getArg(b,"line"),c={source:d.getArg(b,"source"),originalLine:e,originalColumn:d.getArg(b,"column",0)};null!=this.sourceRoot&&(c.source=d.relative(this.sourceRoot,c.source));if(!this._sources.has(c.source))return[];c.source=this._sources.indexOf(c.source);var k=[];c=this._findMapping(c,this._originalMappings,"originalLine",
"originalColumn",d.compareByOriginalPositions,a.LEAST_UPPER_BOUND);if(0<=c){var g=this._originalMappings[c];if(void 0===b.column)for(e=g.originalLine;g&&g.originalLine===e;)k.push({line:d.getArg(g,"generatedLine",null),column:d.getArg(g,"generatedColumn",null),lastColumn:d.getArg(g,"lastGeneratedColumn",null)}),g=this._originalMappings[++c];else for(b=g.originalColumn;g&&g.originalLine===e&&g.originalColumn==b;)k.push({line:d.getArg(g,"generatedLine",null),column:d.getArg(g,"generatedColumn",null),
lastColumn:d.getArg(g,"lastGeneratedColumn",null)}),g=this._originalMappings[++c]}return k};m.SourceMapConsumer=b;e.prototype=Object.create(b.prototype);e.prototype.consumer=b;e.fromSourceMap=function(a,b){var c=Object.create(e.prototype),k=c._names=l.fromArray(a._names.toArray(),!0),v=c._sources=l.fromArray(a._sources.toArray(),!0);c.sourceRoot=a._sourceRoot;c.sourcesContent=a._generateSourcesContent(c._sources.toArray(),c.sourceRoot);c.file=a._file;c._sourceMapURL=b;for(var h=a._mappings.toArray().slice(),
r=c.__generatedMappings=[],m=c.__originalMappings=[],u=0,n=h.length;u<n;u++){var f=h[u],p=new g;p.generatedLine=f.generatedLine;p.generatedColumn=f.generatedColumn;f.source&&(p.source=v.indexOf(f.source),p.originalLine=f.originalLine,p.originalColumn=f.originalColumn,f.name&&(p.name=k.indexOf(f.name)),m.push(p));r.push(p)}q(c.__originalMappings,d.compareByOriginalPositions);return c};e.prototype._version=3;Object.defineProperty(e.prototype,"sources",{get:function(){return this._sources.toArray().map(function(a){return d.computeSourceURL(this.sourceRoot,
a,this._sourceMapURL)},this)}});e.prototype._parseMappings=function(a,b){for(var c=1,k=0,e=0,l=0,v=0,h=0,m=a.length,u=0,f={},p={},n=[],x=[],z,B,A,E,I;u<m;)if(";"===a.charAt(u))c++,u++,k=0;else if(","===a.charAt(u))u++;else{z=new g;z.generatedLine=c;for(E=u;E<m&&!this._charIsMappingSeparator(a,E);E++);B=a.slice(u,E);if(A=f[B])u+=B.length;else{for(A=[];u<E;)r.decode(a,u,p),I=p.value,u=p.rest,A.push(I);if(2===A.length)throw Error("Found a source, but no line and column");if(3===A.length)throw Error("Found a source and line, but no column");
f[B]=A}z.generatedColumn=k+A[0];k=z.generatedColumn;1<A.length&&(z.source=v+A[1],v+=A[1],z.originalLine=e+A[2],e=z.originalLine,z.originalLine+=1,z.originalColumn=l+A[3],l=z.originalColumn,4<A.length&&(z.name=h+A[4],h+=A[4]));x.push(z);"number"===typeof z.originalLine&&n.push(z)}q(x,d.compareByGeneratedPositionsDeflated);this.__generatedMappings=x;q(n,d.compareByOriginalPositions);this.__originalMappings=n};e.prototype._findMapping=function(b,d,c,k,e,g){if(0>=b[c])throw new TypeError("Line must be greater than or equal to 1, got "+
b[c]);if(0>b[k])throw new TypeError("Column must be greater than or equal to 0, got "+b[k]);return a.search(b,d,e,g)};e.prototype.computeColumnSpans=function(){for(var a=0;a<this._generatedMappings.length;++a){var b=this._generatedMappings[a];if(a+1<this._generatedMappings.length){var c=this._generatedMappings[a+1];if(b.generatedLine===c.generatedLine){b.lastGeneratedColumn=c.generatedColumn-1;continue}}b.lastGeneratedColumn=Infinity}};e.prototype.originalPositionFor=function(a){var e={generatedLine:d.getArg(a,
"line"),generatedColumn:d.getArg(a,"column")};a=this._findMapping(e,this._generatedMappings,"generatedLine","generatedColumn",d.compareByGeneratedPositionsDeflated,d.getArg(a,"bias",b.GREATEST_LOWER_BOUND));if(0<=a&&(a=this._generatedMappings[a],a.generatedLine===e.generatedLine)){e=d.getArg(a,"source",null);null!==e&&(e=this._sources.at(e),e=d.computeSourceURL(this.sourceRoot,e,this._sourceMapURL));var c=d.getArg(a,"name",null);null!==c&&(c=this._names.at(c));return{source:e,line:d.getArg(a,"originalLine",
null),column:d.getArg(a,"originalColumn",null),name:c}}return{source:null,line:null,column:null,name:null}};e.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(a){return null==a}):!1};e.prototype.sourceContentFor=function(a,b){if(!this.sourcesContent)return null;var c=a;null!=this.sourceRoot&&(c=d.relative(this.sourceRoot,c));if(this._sources.has(c))return this.sourcesContent[this._sources.indexOf(c)];
var k=this.sources,e;for(e=0;e<k.length;++e)if(k[e]==a)return this.sourcesContent[e];var g;if(null!=this.sourceRoot&&(g=d.urlParse(this.sourceRoot))){k=c.replace(/^file:\/\//,"");if("file"==g.scheme&&this._sources.has(k))return this.sourcesContent[this._sources.indexOf(k)];if((!g.path||"/"==g.path)&&this._sources.has("/"+c))return this.sourcesContent[this._sources.indexOf("/"+c)]}if(b)return null;throw Error('"'+c+'" is not in the SourceMap.');};e.prototype.generatedPositionFor=function(a){var e=
d.getArg(a,"source");null!=this.sourceRoot&&(e=d.relative(this.sourceRoot,e));if(!this._sources.has(e))return{line:null,column:null,lastColumn:null};e=this._sources.indexOf(e);e={source:e,originalLine:d.getArg(a,"line"),originalColumn:d.getArg(a,"column")};a=this._findMapping(e,this._originalMappings,"originalLine","originalColumn",d.compareByOriginalPositions,d.getArg(a,"bias",b.GREATEST_LOWER_BOUND));return 0<=a&&(a=this._originalMappings[a],a.source===e.source)?{line:d.getArg(a,"generatedLine",
null),column:d.getArg(a,"generatedColumn",null),lastColumn:d.getArg(a,"lastGeneratedColumn",null)}:{line:null,column:null,lastColumn:null}};m.BasicSourceMapConsumer=e;h.prototype=Object.create(b.prototype);h.prototype.constructor=b;h.prototype._version=3;Object.defineProperty(h.prototype,"sources",{get:function(){for(var a=[],b=0;b<this._sections.length;b++)for(var c=0;c<this._sections[b].consumer.sources.length;c++)a.push(this._sections[b].consumer.sources[c]);return a}});h.prototype.originalPositionFor=
function(b){var e={generatedLine:d.getArg(b,"line"),generatedColumn:d.getArg(b,"column")},c=a.search(e,this._sections,function(a,b){var c=a.generatedLine-b.generatedOffset.generatedLine;return c?c:a.generatedColumn-b.generatedOffset.generatedColumn});return(c=this._sections[c])?c.consumer.originalPositionFor({line:e.generatedLine-(c.generatedOffset.generatedLine-1),column:e.generatedColumn-(c.generatedOffset.generatedLine===e.generatedLine?c.generatedOffset.generatedColumn-1:0),bias:b.bias}):{source:null,
line:null,column:null,name:null}};h.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(a){return a.consumer.hasContentsOfAllSources()})};h.prototype.sourceContentFor=function(a,b){for(var c=0;c<this._sections.length;c++){var d=this._sections[c].consumer.sourceContentFor(a,!0);if(d)return d}if(b)return null;throw Error('"'+a+'" is not in the SourceMap.');};h.prototype.generatedPositionFor=function(a){for(var b=0;b<this._sections.length;b++){var c=this._sections[b];if(-1!==
c.consumer.sources.indexOf(d.getArg(a,"source"))){var k=c.consumer.generatedPositionFor(a);if(k)return{line:k.line+(c.generatedOffset.generatedLine-1),column:k.column+(c.generatedOffset.generatedLine===k.line?c.generatedOffset.generatedColumn-1:0)}}}return{line:null,column:null}};h.prototype._parseMappings=function(a,b){this.__generatedMappings=[];this.__originalMappings=[];for(var c=0;c<this._sections.length;c++)for(var k=this._sections[c],e=k.consumer._generatedMappings,g=0;g<e.length;g++){var l=
e[g],h=k.consumer._sources.at(l.source);h=d.computeSourceURL(k.consumer.sourceRoot,h,this._sourceMapURL);this._sources.add(h);h=this._sources.indexOf(h);var r=null;l.name&&(r=k.consumer._names.at(l.name),this._names.add(r),r=this._names.indexOf(r));l={source:h,generatedLine:l.generatedLine+(k.generatedOffset.generatedLine-1),generatedColumn:l.generatedColumn+(k.generatedOffset.generatedLine===l.generatedLine?k.generatedOffset.generatedColumn-1:0),originalLine:l.originalLine,originalColumn:l.originalColumn,
name:r};this.__generatedMappings.push(l);"number"===typeof l.originalLine&&this.__originalMappings.push(l)}q(this.__generatedMappings,d.compareByGeneratedPositionsDeflated);q(this.__originalMappings,d.compareByOriginalPositions)};m.IndexedSourceMapConsumer=h},{"./array-set":10,"./base64-vlq":11,"./binary-search":13,"./quick-sort":15,"./util":19}],17:[function(n,x,m){function b(a){a||(a={});this._file=g.getArg(a,"file",null);this._sourceRoot=g.getArg(a,"sourceRoot",null);this._skipValidation=g.getArg(a,
"skipValidation",!1);this._sources=new h;this._names=new h;this._mappings=new d;this._sourcesContents=null}var e=n("./base64-vlq"),g=n("./util"),h=n("./array-set").ArraySet,d=n("./mapping-list").MappingList;b.prototype._version=3;b.fromSourceMap=function(a){var d=a.sourceRoot,e=new b({file:a.file,sourceRoot:d});a.eachMapping(function(a){var b={generated:{line:a.generatedLine,column:a.generatedColumn}};null!=a.source&&(b.source=a.source,null!=d&&(b.source=g.relative(d,b.source)),b.original={line:a.originalLine,
column:a.originalColumn},null!=a.name&&(b.name=a.name));e.addMapping(b)});a.sources.forEach(function(b){var l=b;null!==d&&(l=g.relative(d,b));e._sources.has(l)||e._sources.add(l);l=a.sourceContentFor(b);null!=l&&e.setSourceContent(b,l)});return e};b.prototype.addMapping=function(a){var b=g.getArg(a,"generated"),d=g.getArg(a,"original",null),e=g.getArg(a,"source",null);a=g.getArg(a,"name",null);this._skipValidation||this._validateMapping(b,d,e,a);null!=e&&(e=String(e),this._sources.has(e)||this._sources.add(e));
null!=a&&(a=String(a),this._names.has(a)||this._names.add(a));this._mappings.add({generatedLine:b.line,generatedColumn:b.column,originalLine:null!=d&&d.line,originalColumn:null!=d&&d.column,source:e,name:a})};b.prototype.setSourceContent=function(a,b){var d=a;null!=this._sourceRoot&&(d=g.relative(this._sourceRoot,d));null!=b?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[g.toSetString(d)]=b):this._sourcesContents&&(delete this._sourcesContents[g.toSetString(d)],
0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))};b.prototype.applySourceMap=function(a,b,d){var e=b;if(null==b){if(null==a.file)throw Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');e=a.file}var l=this._sourceRoot;null!=l&&(e=g.relative(l,e));var m=new h,c=new h;this._mappings.unsortedForEach(function(b){if(b.source===e&&null!=b.originalLine){var k=a.originalPositionFor({line:b.originalLine,
column:b.originalColumn});null!=k.source&&(b.source=k.source,null!=d&&(b.source=g.join(d,b.source)),null!=l&&(b.source=g.relative(l,b.source)),b.originalLine=k.line,b.originalColumn=k.column,null!=k.name&&(b.name=k.name))}k=b.source;null==k||m.has(k)||m.add(k);b=b.name;null==b||c.has(b)||c.add(b)},this);this._sources=m;this._names=c;a.sources.forEach(function(b){var c=a.sourceContentFor(b);null!=c&&(null!=d&&(b=g.join(d,b)),null!=l&&(b=g.relative(l,b)),this.setSourceContent(b,c))},this)};b.prototype._validateMapping=
function(a,b,d,e){if(b&&"number"!==typeof b.line&&"number"!==typeof b.column)throw Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(a&&"line"in a&&"column"in a&&0<a.line&&0<=a.column&&!b&&!d&&!e||a&&"line"in a&&"column"in a&&b&&"line"in b&&"column"in b&&0<a.line&&0<=a.column&&0<b.line&&0<=b.column&&
d))throw Error("Invalid mapping: "+JSON.stringify({generated:a,source:d,original:b,name:e}));};b.prototype._serializeMappings=function(){for(var a=0,b=1,d=0,h=0,m=0,n=0,c="",k,w,y,F=this._mappings.toArray(),D=0,t=F.length;D<t;D++){w=F[D];k="";if(w.generatedLine!==b)for(a=0;w.generatedLine!==b;)k+=";",b++;else if(0<D){if(!g.compareByGeneratedPositionsInflated(w,F[D-1]))continue;k+=","}k+=e.encode(w.generatedColumn-a);a=w.generatedColumn;null!=w.source&&(y=this._sources.indexOf(w.source),k+=e.encode(y-
n),n=y,k+=e.encode(w.originalLine-1-h),h=w.originalLine-1,k+=e.encode(w.originalColumn-d),d=w.originalColumn,null!=w.name&&(w=this._names.indexOf(w.name),k+=e.encode(w-m),m=w));c+=k}return c};b.prototype._generateSourcesContent=function(a,b){return a.map(function(a){if(!this._sourcesContents)return null;null!=b&&(a=g.relative(b,a));a=g.toSetString(a);return Object.prototype.hasOwnProperty.call(this._sourcesContents,a)?this._sourcesContents[a]:null},this)};b.prototype.toJSON=function(){var a={version:this._version,
sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};null!=this._file&&(a.file=this._file);null!=this._sourceRoot&&(a.sourceRoot=this._sourceRoot);this._sourcesContents&&(a.sourcesContent=this._generateSourcesContent(a.sources,a.sourceRoot));return a};b.prototype.toString=function(){return JSON.stringify(this.toJSON())};m.SourceMapGenerator=b},{"./array-set":10,"./base64-vlq":11,"./mapping-list":14,"./util":19}],18:[function(n,x,m){function b(b,a,e,g,h){this.children=
[];this.sourceContents={};this.line=null==b?null:b;this.column=null==a?null:a;this.source=null==e?null:e;this.name=null==h?null:h;this.$$$isSourceNode$$$=!0;null!=g&&this.add(g)}var e=n("./source-map-generator").SourceMapGenerator,g=n("./util"),h=/(\r?\n)/;b.fromStringWithSourceMap=function(d,a,e){function l(a,c){if(null===a||void 0===a.source)m.add(c);else{var d=e?g.join(e,a.source):a.source;m.add(new b(a.originalLine,a.originalColumn,d,c,a.name))}}var m=new b,n=d.split(h),u=0,c=function(){var a=
u<n.length?n[u++]:void 0,b=(u<n.length?n[u++]:void 0)||"";return a+b},k=1,w=0,y=null;a.eachMapping(function(a){if(null!==y)if(k<a.generatedLine)l(y,c()),k++,w=0;else{var b=n[u]||"",d=b.substr(0,a.generatedColumn-w);n[u]=b.substr(a.generatedColumn-w);w=a.generatedColumn;l(y,d);y=a;return}for(;k<a.generatedLine;)m.add(c()),k++;w<a.generatedColumn&&(b=n[u]||"",m.add(b.substr(0,a.generatedColumn)),n[u]=b.substr(a.generatedColumn),w=a.generatedColumn);y=a},this);u<n.length&&(y&&l(y,c()),m.add(n.splice(u).join("")));
a.sources.forEach(function(b){var c=a.sourceContentFor(b);null!=c&&(null!=e&&(b=g.join(e,b)),m.setSourceContent(b,c))});return m};b.prototype.add=function(b){if(Array.isArray(b))b.forEach(function(a){this.add(a)},this);else if(b.$$$isSourceNode$$$||"string"===typeof b)b&&this.children.push(b);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+b);return this};b.prototype.prepend=function(b){if(Array.isArray(b))for(var a=b.length-1;0<=a;a--)this.prepend(b[a]);
else if(b.$$$isSourceNode$$$||"string"===typeof b)this.children.unshift(b);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+b);return this};b.prototype.walk=function(b){for(var a,d=0,e=this.children.length;d<e;d++)a=this.children[d],a.$$$isSourceNode$$$?a.walk(b):""!==a&&b(a,{source:this.source,line:this.line,column:this.column,name:this.name})};b.prototype.join=function(b){var a,d=this.children.length;if(0<d){var e=[];for(a=0;a<d-1;a++)e.push(this.children[a]),
e.push(b);e.push(this.children[a]);this.children=e}return this};b.prototype.replaceRight=function(b,a){var d=this.children[this.children.length-1];d.$$$isSourceNode$$$?d.replaceRight(b,a):"string"===typeof d?this.children[this.children.length-1]=d.replace(b,a):this.children.push("".replace(b,a));return this};b.prototype.setSourceContent=function(b,a){this.sourceContents[g.toSetString(b)]=a};b.prototype.walkSourceContents=function(b){for(var a=0,d=this.children.length;a<d;a++)this.children[a].$$$isSourceNode$$$&&
this.children[a].walkSourceContents(b);var e=Object.keys(this.sourceContents);a=0;for(d=e.length;a<d;a++)b(g.fromSetString(e[a]),this.sourceContents[e[a]])};b.prototype.toString=function(){var b="";this.walk(function(a){b+=a});return b};b.prototype.toStringWithSourceMap=function(b){var a="",d=1,g=0,h=new e(b),m=!1,n=null,c=null,k=null,w=null;this.walk(function(b,e){a+=b;null!==e.source&&null!==e.line&&null!==e.column?(n===e.source&&c===e.line&&k===e.column&&w===e.name||h.addMapping({source:e.source,
original:{line:e.line,column:e.column},generated:{line:d,column:g},name:e.name}),n=e.source,c=e.line,k=e.column,w=e.name,m=!0):m&&(h.addMapping({generated:{line:d,column:g}}),n=null,m=!1);for(var l=0,y=b.length;l<y;l++)10===b.charCodeAt(l)?(d++,g=0,l+1===y?(n=null,m=!1):m&&h.addMapping({source:e.source,original:{line:e.line,column:e.column},generated:{line:d,column:g},name:e.name})):g++});this.walkSourceContents(function(a,b){h.setSourceContent(a,b)});return{code:a,map:h}};m.SourceNode=b},{"./source-map-generator":17,
"./util":19}],19:[function(n,x,m){function b(a){return(a=a.match(v))?{scheme:a[1],auth:a[2],host:a[3],port:a[4],path:a[5]}:null}function e(a){var b="";a.scheme&&(b+=a.scheme+":");b+="//";a.auth&&(b+=a.auth+"@");a.host&&(b+=a.host);a.port&&(b+=":"+a.port);a.path&&(b+=a.path);return b}function g(a){var c=a,d=b(a);if(d){if(!d.path)return a;c=d.path}a=m.isAbsolute(c);c=c.split(/\/+/);for(var g,h=0,l=c.length-1;0<=l;l--)g=c[l],"."===g?c.splice(l,1):".."===g?h++:0<h&&(""===g?(c.splice(l+1,h),h=0):(c.splice(l,
2),h--));c=c.join("/");""===c&&(c=a?"/":".");return d?(d.path=c,e(d)):c}function h(a,d){""===a&&(a=".");""===d&&(d=".");var c=b(d),k=b(a);k&&(a=k.path||"/");if(c&&!c.scheme)return k&&(c.scheme=k.scheme),e(c);if(c||d.match(u))return d;if(k&&!k.host&&!k.path)return k.host=d,e(k);c="/"===d.charAt(0)?d:g(a.replace(/\/+$/,"")+"/"+d);return k?(k.path=c,e(k)):c}function d(a){return a}function a(a){return r(a)?"$"+a:a}function l(a){return r(a)?a.slice(1):a}function r(a){if(!a)return!1;var b=a.length;if(9>
b||95!==a.charCodeAt(b-1)||95!==a.charCodeAt(b-2)||111!==a.charCodeAt(b-3)||116!==a.charCodeAt(b-4)||111!==a.charCodeAt(b-5)||114!==a.charCodeAt(b-6)||112!==a.charCodeAt(b-7)||95!==a.charCodeAt(b-8)||95!==a.charCodeAt(b-9))return!1;for(b-=10;0<=b;b--)if(36!==a.charCodeAt(b))return!1;return!0}function q(a,b){return a===b?0:null===a?1:null===b?-1:a>b?1:-1}m.getArg=function(a,b,d){if(b in a)return a[b];if(3===arguments.length)return d;throw Error('"'+b+'" is a required argument.');};var v=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,
u=/^data:.+,.+$/;m.urlParse=b;m.urlGenerate=e;m.normalize=g;m.join=h;m.isAbsolute=function(a){return"/"===a.charAt(0)||v.test(a)};m.relative=function(a,b){""===a&&(a=".");a=a.replace(/\/$/,"");for(var c=0;0!==b.indexOf(a+"/");){var d=a.lastIndexOf("/");if(0>d)return b;a=a.slice(0,d);if(a.match(/^([^\/]+:\/)?\/*$/))return b;++c}return Array(c+1).join("../")+b.substr(a.length+1)};n=!("__proto__"in Object.create(null));m.toSetString=n?d:a;m.fromSetString=n?d:l;m.compareByOriginalPositions=function(a,
b,d){var c=q(a.source,b.source);if(0!==c)return c;c=a.originalLine-b.originalLine;if(0!==c)return c;c=a.originalColumn-b.originalColumn;if(0!==c||d)return c;c=a.generatedColumn-b.generatedColumn;if(0!==c)return c;c=a.generatedLine-b.generatedLine;return 0!==c?c:q(a.name,b.name)};m.compareByGeneratedPositionsDeflated=function(a,b,d){var c=a.generatedLine-b.generatedLine;if(0!==c)return c;c=a.generatedColumn-b.generatedColumn;if(0!==c||d)return c;c=q(a.source,b.source);if(0!==c)return c;c=a.originalLine-
b.originalLine;if(0!==c)return c;c=a.originalColumn-b.originalColumn;return 0!==c?c:q(a.name,b.name)};m.compareByGeneratedPositionsInflated=function(a,b){var c=a.generatedLine-b.generatedLine;if(0!==c)return c;c=a.generatedColumn-b.generatedColumn;if(0!==c)return c;c=q(a.source,b.source);if(0!==c)return c;c=a.originalLine-b.originalLine;if(0!==c)return c;c=a.originalColumn-b.originalColumn;return 0!==c?c:q(a.name,b.name)};m.parseSourceMapInput=function(a){return JSON.parse(a.replace(/^\)]}'[^\n]*\n/,
""))};m.computeSourceURL=function(a,d,l){d=d||"";a&&("/"!==a[a.length-1]&&"/"!==d[0]&&(a+="/"),d=a+d);if(l){a=b(l);if(!a)throw Error("sourceMapURL could not be parsed");a.path&&(l=a.path.lastIndexOf("/"),0<=l&&(a.path=a.path.substring(0,l+1)));d=h(e(a),d)}return g(d)}},{}],20:[function(n,x,m){m.SourceMapGenerator=n("./lib/source-map-generator").SourceMapGenerator;m.SourceMapConsumer=n("./lib/source-map-consumer").SourceMapConsumer;m.SourceNode=n("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16,
"./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(n,x,m){(function(b){function e(){return"browser"===f?!0:"node"===f?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function g(a){return function(b){for(var c=0;c<a.length;c++){var d=a[c](b);if(d)return d}return null}}function h(a,b){if(!a)return b;var c=w.dirname(a),d=/^\w+:\/\/[^\/]*/.exec(c);d=d?d[0]:"";var e=c.slice(d.length);
return d&&/^\/\w:/.test(e)?(d+="/",d+w.resolve(c.slice(d.length),b).replace(/\\/g,"/")):d+w.resolve(c.slice(d.length),b)}function d(a){var b=C[a.source];if(!b){var c=E(a.source);c?(b=C[a.source]={url:c.url,map:new k(c.map)},b.map.sourcesContent&&b.map.sources.forEach(function(a,c){var d=b.map.sourcesContent[c];if(d){var e=h(b.url,a);p[e]=d}})):b=C[a.source]={url:null,map:null}}return b&&b.map&&"function"===typeof b.map.originalPositionFor&&(c=b.map.originalPositionFor(a),null!==c.source)?(c.source=
h(b.url,c.source),c):a}function a(b){var c=/^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(b);return c?(b=d({source:c[2],line:+c[3],column:c[4]-1}),"eval at "+c[1]+" ("+b.source+":"+b.line+":"+(b.column+1)+")"):(c=/^eval at ([^(]+) \((.+)\)$/.exec(b))?"eval at "+c[1]+" ("+a(c[2])+")":b}function l(){var a="";if(this.isNative())a="native";else{var b=this.getScriptNameOrSourceURL();!b&&this.isEval()&&(a=this.getEvalOrigin(),a+=", ");a=b?a+b:a+"<anonymous>";b=this.getLineNumber();null!=b&&(a+=":"+b,(b=
this.getColumnNumber())&&(a+=":"+b))}b="";var c=this.getFunctionName(),d=!0,e=this.isConstructor();if(this.isToplevel()||e)e?b+="new "+(c||"<anonymous>"):c?b+=c:(b+=a,d=!1);else{e=this.getTypeName();"[object Object]"===e&&(e="null");var f=this.getMethodName();c?(e&&0!=c.indexOf(e)&&(b+=e+"."),b+=c,f&&c.indexOf("."+f)!=c.length-f.length-1&&(b+=" [as "+f+"]")):b+=e+"."+(f||"<anonymous>")}d&&(b+=" ("+a+")");return b}function r(a){var b={};Object.getOwnPropertyNames(Object.getPrototypeOf(a)).forEach(function(c){b[c]=
/^(?:is|get)/.test(c)?function(){return a[c].call(a)}:a[c]});b.toString=l;return b}function q(c,f){void 0===f&&(f={nextPosition:null,curPosition:null});if(c.isNative())return f.curPosition=null,c;var g=c.getFileName()||c.getScriptNameOrSourceURL();if(g){var h=c.getLineNumber(),k=c.getColumnNumber()-1,l=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/.test(b.version)?0:62;1===h&&k>l&&!e()&&!c.isEval()&&(k-=l);var m=d({source:g,line:h,column:k});f.curPosition=m;c=r(c);var p=
c.getFunctionName;c.getFunctionName=function(){return null==f.nextPosition?p():f.nextPosition.name||p()};c.getFileName=function(){return m.source};c.getLineNumber=function(){return m.line};c.getColumnNumber=function(){return m.column+1};c.getScriptNameOrSourceURL=function(){return m.source};return c}var n=c.isEval()&&c.getEvalOrigin();n&&(n=a(n),c=r(c),c.getEvalOrigin=function(){return n});return c}function v(a,b){H&&(p={},C={});for(var c=(a.name||"Error")+": "+(a.message||""),d={nextPosition:null,
curPosition:null},e=[],f=b.length-1;0<=f;f--)e.push("\n at "+q(b[f],d)),d.nextPosition=d.curPosition;d.curPosition=d.nextPosition=null;return c+e.reverse().join("")}function u(a){var b=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(a.stack);if(b){a=b[1];var c=+b[2];b=+b[3];var d=p[a];if(!d&&y&&y.existsSync(a))try{d=y.readFileSync(a,"utf8")}catch(N){d=""}if(d&&(d=d.split(/(?:\r\n|\r|\n)/)[c-1]))return a+":"+c+"\n"+d+"\n"+Array(b).join(" ")+"^"}return null}function c(){var a=b.emit;b.emit=function(c){if("uncaughtException"===
c){var d=arguments[1]&&arguments[1].stack,e=0<this.listeners(c).length;if(d&&!e){d=arguments[1];e=u(d);b.stderr._handle&&b.stderr._handle.setBlocking&&b.stderr._handle.setBlocking(!0);e&&(console.error(),console.error(e));console.error(d.stack);b.exit(1);return}}return a.apply(this,arguments)}}var k=n("source-map").SourceMapConsumer,w=n("path");try{var y=n("fs");y.existsSync&&y.readFileSync||(y=null)}catch(M){}var F=n("buffer-from"),D=!1,t=!1,H=!1,f="auto",p={},C={},G=/^data:application\/json[^,]+base64,/,
z=[],B=[],A=g(z);z.push(function(a){a=a.trim();/^file:/.test(a)&&(a=a.replace(/file:\/\/\/(\w:)?/,function(a,b){return b?"":"/"}));if(a in p)return p[a];var b="";try{if(y)y.existsSync(a)&&(b=y.readFileSync(a,"utf8"));else{var c=new XMLHttpRequest;c.open("GET",a,!1);c.send(null);4===c.readyState&&200===c.status&&(b=c.responseText)}}catch(K){}return p[a]=b});var E=g(B);B.push(function(a){a:{if(e())try{var b=new XMLHttpRequest;b.open("GET",a,!1);b.send(null);var c=b.getResponseHeader("SourceMap")||b.getResponseHeader("X-SourceMap");
if(c){var d=c;break a}}catch(O){}d=A(a);b=/(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;for(var f;c=b.exec(d);)f=c;d=f?f[1]:null}if(!d)return null;G.test(d)?(f=d.slice(d.indexOf(",")+1),f=F(f,"base64").toString(),d=a):(d=h(a,d),f=A(d));return f?{url:d,map:f}:null});var I=z.slice(0),L=B.slice(0);m.wrapCallSite=q;m.getErrorSource=u;m.mapSourcePosition=d;m.retrieveSourceMap=E;m.install=function(a){a=a||{};if(a.environment&&(f=
a.environment,-1===["node","browser","auto"].indexOf(f)))throw Error("environment "+f+" was unknown. Available options are {auto, browser, node}");a.retrieveFile&&(a.overrideRetrieveFile&&(z.length=0),z.unshift(a.retrieveFile));a.retrieveSourceMap&&(a.overrideRetrieveSourceMap&&(B.length=0),B.unshift(a.retrieveSourceMap));if(a.hookRequire&&!e()){var d=x.require("module"),g=d.prototype._compile;g.__sourceMapSupport||(d.prototype._compile=function(a,b){p[b]=a;C[b]=void 0;return g.call(this,a,b)},d.prototype._compile.__sourceMapSupport=
!0)}H||(H="emptyCacheBetweenOperations"in a?a.emptyCacheBetweenOperations:!1);D||(D=!0,Error.prepareStackTrace=v);if(!t){a="handleUncaughtExceptions"in a?a.handleUncaughtExceptions:!0;try{!1===x.require("worker_threads").isMainThread&&(a=!1)}catch(K){}a&&"object"===typeof b&&null!==b&&"function"===typeof b.on&&(t=!0,c())}};m.resetRetrieveHandlers=function(){z.length=0;B.length=0;z=I.slice(0);B=L.slice(0);E=g(B);A=g(z)}}).call(this,n("g5I+bs"))},{"buffer-from":4,fs:3,"g5I+bs":9,path:8,"source-map":20}]},
{},[1]);return G});

View file

@ -0,0 +1,31 @@
{
"name": "source-map-support",
"description": "Fixes stack traces for files with source maps",
"version": "0.5.19",
"main": "./source-map-support.js",
"scripts": {
"build": "node build.js",
"serve-tests": "http-server -p 1336",
"prepublish": "npm run build",
"test": "mocha"
},
"dependencies": {
"buffer-from": "^1.0.0",
"source-map": "^0.6.0"
},
"devDependencies": {
"browserify": "^4.2.3",
"coffeescript": "^1.12.7",
"http-server": "^0.11.1",
"mocha": "^3.5.3",
"webpack": "^1.15.0"
},
"repository": {
"type": "git",
"url": "https://github.com/evanw/node-source-map-support"
},
"bugs": {
"url": "https://github.com/evanw/node-source-map-support/issues"
},
"license": "MIT"
}

View file

@ -0,0 +1 @@
require('./').install();

View file

@ -0,0 +1,604 @@
var SourceMapConsumer = require('source-map').SourceMapConsumer;
var path = require('path');
var fs;
try {
fs = require('fs');
if (!fs.existsSync || !fs.readFileSync) {
// fs doesn't have all methods we need
fs = null;
}
} catch (err) {
/* nop */
}
var bufferFrom = require('buffer-from');
/**
* Requires a module which is protected against bundler minification.
*
* @param {NodeModule} mod
* @param {string} request
*/
function dynamicRequire(mod, request) {
return mod.require(request);
}
// Only install once if called multiple times
var errorFormatterInstalled = false;
var uncaughtShimInstalled = false;
// If true, the caches are reset before a stack trace formatting operation
var emptyCacheBetweenOperations = false;
// Supports {browser, node, auto}
var environment = "auto";
// Maps a file path to a string containing the file contents
var fileContentsCache = {};
// Maps a file path to a source map for that file
var sourceMapCache = {};
// Regex for detecting source maps
var reSourceMap = /^data:application\/json[^,]+base64,/;
// Priority list of retrieve handlers
var retrieveFileHandlers = [];
var retrieveMapHandlers = [];
function isInBrowser() {
if (environment === "browser")
return true;
if (environment === "node")
return false;
return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
}
function hasGlobalProcessEventEmitter() {
return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
}
function handlerExec(list) {
return function(arg) {
for (var i = 0; i < list.length; i++) {
var ret = list[i](arg);
if (ret) {
return ret;
}
}
return null;
};
}
var retrieveFile = handlerExec(retrieveFileHandlers);
retrieveFileHandlers.push(function(path) {
// Trim the path to make sure there is no extra whitespace.
path = path.trim();
if (/^file:/.test(path)) {
// existsSync/readFileSync can't handle file protocol, but once stripped, it works
path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
return drive ?
'' : // file:///C:/dir/file -> C:/dir/file
'/'; // file:///root-dir/file -> /root-dir/file
});
}
if (path in fileContentsCache) {
return fileContentsCache[path];
}
var contents = '';
try {
if (!fs) {
// Use SJAX if we are in the browser
var xhr = new XMLHttpRequest();
xhr.open('GET', path, /** async */ false);
xhr.send(null);
if (xhr.readyState === 4 && xhr.status === 200) {
contents = xhr.responseText;
}
} else if (fs.existsSync(path)) {
// Otherwise, use the filesystem
contents = fs.readFileSync(path, 'utf8');
}
} catch (er) {
/* ignore any errors */
}
return fileContentsCache[path] = contents;
});
// Support URLs relative to a directory, but be careful about a protocol prefix
// in case we are in the browser (i.e. directories may start with "http://" or "file:///")
function supportRelativeURL(file, url) {
if (!file) return url;
var dir = path.dirname(file);
var match = /^\w+:\/\/[^\/]*/.exec(dir);
var protocol = match ? match[0] : '';
var startPath = dir.slice(protocol.length);
if (protocol && /^\/\w\:/.test(startPath)) {
// handle file:///C:/ paths
protocol += '/';
return protocol + path.resolve(dir.slice(protocol.length), url).replace(/\\/g, '/');
}
return protocol + path.resolve(dir.slice(protocol.length), url);
}
function retrieveSourceMapURL(source) {
var fileData;
if (isInBrowser()) {
try {
var xhr = new XMLHttpRequest();
xhr.open('GET', source, false);
xhr.send(null);
fileData = xhr.readyState === 4 ? xhr.responseText : null;
// Support providing a sourceMappingURL via the SourceMap header
var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
xhr.getResponseHeader("X-SourceMap");
if (sourceMapHeader) {
return sourceMapHeader;
}
} catch (e) {
}
}
// Get the URL of the source map
fileData = retrieveFile(source);
var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
// Keep executing the search to find the *last* sourceMappingURL to avoid
// picking up sourceMappingURLs from comments, strings, etc.
var lastMatch, match;
while (match = re.exec(fileData)) lastMatch = match;
if (!lastMatch) return null;
return lastMatch[1];
};
// Can be overridden by the retrieveSourceMap option to install. Takes a
// generated source filename; returns a {map, optional url} object, or null if
// there is no source map. The map field may be either a string or the parsed
// JSON object (ie, it must be a valid argument to the SourceMapConsumer
// constructor).
var retrieveSourceMap = handlerExec(retrieveMapHandlers);
retrieveMapHandlers.push(function(source) {
var sourceMappingURL = retrieveSourceMapURL(source);
if (!sourceMappingURL) return null;
// Read the contents of the source map
var sourceMapData;
if (reSourceMap.test(sourceMappingURL)) {
// Support source map URL as a data url
var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
sourceMapData = bufferFrom(rawData, "base64").toString();
sourceMappingURL = source;
} else {
// Support source map URLs relative to the source URL
sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
sourceMapData = retrieveFile(sourceMappingURL);
}
if (!sourceMapData) {
return null;
}
return {
url: sourceMappingURL,
map: sourceMapData
};
});
function mapSourcePosition(position) {
var sourceMap = sourceMapCache[position.source];
if (!sourceMap) {
// Call the (overrideable) retrieveSourceMap function to get the source map.
var urlAndMap = retrieveSourceMap(position.source);
if (urlAndMap) {
sourceMap = sourceMapCache[position.source] = {
url: urlAndMap.url,
map: new SourceMapConsumer(urlAndMap.map)
};
// Load all sources stored inline with the source map into the file cache
// to pretend like they are already loaded. They may not exist on disk.
if (sourceMap.map.sourcesContent) {
sourceMap.map.sources.forEach(function(source, i) {
var contents = sourceMap.map.sourcesContent[i];
if (contents) {
var url = supportRelativeURL(sourceMap.url, source);
fileContentsCache[url] = contents;
}
});
}
} else {
sourceMap = sourceMapCache[position.source] = {
url: null,
map: null
};
}
}
// Resolve the source URL relative to the URL of the source map
if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === 'function') {
var originalPosition = sourceMap.map.originalPositionFor(position);
// Only return the original position if a matching line was found. If no
// matching line is found then we return position instead, which will cause
// the stack trace to print the path and line for the compiled file. It is
// better to give a precise location in the compiled file than a vague
// location in the original file.
if (originalPosition.source !== null) {
originalPosition.source = supportRelativeURL(
sourceMap.url, originalPosition.source);
return originalPosition;
}
}
return position;
}
// Parses code generated by FormatEvalOrigin(), a function inside V8:
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
function mapEvalOrigin(origin) {
// Most eval() calls are in this format
var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
if (match) {
var position = mapSourcePosition({
source: match[2],
line: +match[3],
column: match[4] - 1
});
return 'eval at ' + match[1] + ' (' + position.source + ':' +
position.line + ':' + (position.column + 1) + ')';
}
// Parse nested eval() calls using recursion
match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
if (match) {
return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
}
// Make sure we still return useful information if we didn't find anything
return origin;
}
// This is copied almost verbatim from the V8 source code at
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js. The
// implementation of wrapCallSite() used to just forward to the actual source
// code of CallSite.prototype.toString but unfortunately a new release of V8
// did something to the prototype chain and broke the shim. The only fix I
// could find was copy/paste.
function CallSiteToString() {
var fileName;
var fileLocation = "";
if (this.isNative()) {
fileLocation = "native";
} else {
fileName = this.getScriptNameOrSourceURL();
if (!fileName && this.isEval()) {
fileLocation = this.getEvalOrigin();
fileLocation += ", "; // Expecting source position to follow.
}
if (fileName) {
fileLocation += fileName;
} else {
// Source code does not originate from a file and is not native, but we
// can still get the source position inside the source string, e.g. in
// an eval string.
fileLocation += "<anonymous>";
}
var lineNumber = this.getLineNumber();
if (lineNumber != null) {
fileLocation += ":" + lineNumber;
var columnNumber = this.getColumnNumber();
if (columnNumber) {
fileLocation += ":" + columnNumber;
}
}
}
var line = "";
var functionName = this.getFunctionName();
var addSuffix = true;
var isConstructor = this.isConstructor();
var isMethodCall = !(this.isToplevel() || isConstructor);
if (isMethodCall) {
var typeName = this.getTypeName();
// Fixes shim to be backward compatable with Node v0 to v4
if (typeName === "[object Object]") {
typeName = "null";
}
var methodName = this.getMethodName();
if (functionName) {
if (typeName && functionName.indexOf(typeName) != 0) {
line += typeName + ".";
}
line += functionName;
if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
line += " [as " + methodName + "]";
}
} else {
line += typeName + "." + (methodName || "<anonymous>");
}
} else if (isConstructor) {
line += "new " + (functionName || "<anonymous>");
} else if (functionName) {
line += functionName;
} else {
line += fileLocation;
addSuffix = false;
}
if (addSuffix) {
line += " (" + fileLocation + ")";
}
return line;
}
function cloneCallSite(frame) {
var object = {};
Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
});
object.toString = CallSiteToString;
return object;
}
function wrapCallSite(frame, state) {
// provides interface backward compatibility
if (state === undefined) {
state = { nextPosition: null, curPosition: null }
}
if(frame.isNative()) {
state.curPosition = null;
return frame;
}
// Most call sites will return the source file from getFileName(), but code
// passed to eval() ending in "//# sourceURL=..." will return the source file
// from getScriptNameOrSourceURL() instead
var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
if (source) {
var line = frame.getLineNumber();
var column = frame.getColumnNumber() - 1;
// Fix position in Node where some (internal) code is prepended.
// See https://github.com/evanw/node-source-map-support/issues/36
// Header removed in node at ^10.16 || >=11.11.0
// v11 is not an LTS candidate, we can just test the one version with it.
// Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11
var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
var headerLength = noHeader.test(process.version) ? 0 : 62;
if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
column -= headerLength;
}
var position = mapSourcePosition({
source: source,
line: line,
column: column
});
state.curPosition = position;
frame = cloneCallSite(frame);
var originalFunctionName = frame.getFunctionName;
frame.getFunctionName = function() {
if (state.nextPosition == null) {
return originalFunctionName();
}
return state.nextPosition.name || originalFunctionName();
};
frame.getFileName = function() { return position.source; };
frame.getLineNumber = function() { return position.line; };
frame.getColumnNumber = function() { return position.column + 1; };
frame.getScriptNameOrSourceURL = function() { return position.source; };
return frame;
}
// Code called using eval() needs special handling
var origin = frame.isEval() && frame.getEvalOrigin();
if (origin) {
origin = mapEvalOrigin(origin);
frame = cloneCallSite(frame);
frame.getEvalOrigin = function() { return origin; };
return frame;
}
// If we get here then we were unable to change the source position
return frame;
}
// This function is part of the V8 stack trace API, for more info see:
// https://v8.dev/docs/stack-trace-api
function prepareStackTrace(error, stack) {
if (emptyCacheBetweenOperations) {
fileContentsCache = {};
sourceMapCache = {};
}
var name = error.name || 'Error';
var message = error.message || '';
var errorString = name + ": " + message;
var state = { nextPosition: null, curPosition: null };
var processedStack = [];
for (var i = stack.length - 1; i >= 0; i--) {
processedStack.push('\n at ' + wrapCallSite(stack[i], state));
state.nextPosition = state.curPosition;
}
state.curPosition = state.nextPosition = null;
return errorString + processedStack.reverse().join('');
}
// Generate position and snippet of original source with pointer
function getErrorSource(error) {
var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
if (match) {
var source = match[1];
var line = +match[2];
var column = +match[3];
// Support the inline sourceContents inside the source map
var contents = fileContentsCache[source];
// Support files on disk
if (!contents && fs && fs.existsSync(source)) {
try {
contents = fs.readFileSync(source, 'utf8');
} catch (er) {
contents = '';
}
}
// Format the line from the original source code like node does
if (contents) {
var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
if (code) {
return source + ':' + line + '\n' + code + '\n' +
new Array(column).join(' ') + '^';
}
}
}
return null;
}
function printErrorAndExit (error) {
var source = getErrorSource(error);
// Ensure error is printed synchronously and not truncated
if (process.stderr._handle && process.stderr._handle.setBlocking) {
process.stderr._handle.setBlocking(true);
}
if (source) {
console.error();
console.error(source);
}
console.error(error.stack);
process.exit(1);
}
function shimEmitUncaughtException () {
var origEmit = process.emit;
process.emit = function (type) {
if (type === 'uncaughtException') {
var hasStack = (arguments[1] && arguments[1].stack);
var hasListeners = (this.listeners(type).length > 0);
if (hasStack && !hasListeners) {
return printErrorAndExit(arguments[1]);
}
}
return origEmit.apply(this, arguments);
};
}
var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
exports.wrapCallSite = wrapCallSite;
exports.getErrorSource = getErrorSource;
exports.mapSourcePosition = mapSourcePosition;
exports.retrieveSourceMap = retrieveSourceMap;
exports.install = function(options) {
options = options || {};
if (options.environment) {
environment = options.environment;
if (["node", "browser", "auto"].indexOf(environment) === -1) {
throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
}
}
// Allow sources to be found by methods other than reading the files
// directly from disk.
if (options.retrieveFile) {
if (options.overrideRetrieveFile) {
retrieveFileHandlers.length = 0;
}
retrieveFileHandlers.unshift(options.retrieveFile);
}
// Allow source maps to be found by methods other than reading the files
// directly from disk.
if (options.retrieveSourceMap) {
if (options.overrideRetrieveSourceMap) {
retrieveMapHandlers.length = 0;
}
retrieveMapHandlers.unshift(options.retrieveSourceMap);
}
// Support runtime transpilers that include inline source maps
if (options.hookRequire && !isInBrowser()) {
// Use dynamicRequire to avoid including in browser bundles
var Module = dynamicRequire(module, 'module');
var $compile = Module.prototype._compile;
if (!$compile.__sourceMapSupport) {
Module.prototype._compile = function(content, filename) {
fileContentsCache[filename] = content;
sourceMapCache[filename] = undefined;
return $compile.call(this, content, filename);
};
Module.prototype._compile.__sourceMapSupport = true;
}
}
// Configure options
if (!emptyCacheBetweenOperations) {
emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
options.emptyCacheBetweenOperations : false;
}
// Install the error reformatter
if (!errorFormatterInstalled) {
errorFormatterInstalled = true;
Error.prepareStackTrace = prepareStackTrace;
}
if (!uncaughtShimInstalled) {
var installHandler = 'handleUncaughtExceptions' in options ?
options.handleUncaughtExceptions : true;
// Do not override 'uncaughtException' with our own handler in Node.js
// Worker threads. Workers pass the error to the main thread as an event,
// rather than printing something to stderr and exiting.
try {
// We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.
var worker_threads = dynamicRequire(module, 'worker_threads');
if (worker_threads.isMainThread === false) {
installHandler = false;
}
} catch(e) {}
// Provide the option to not install the uncaught exception handler. This is
// to support other uncaught exception handlers (in test frameworks, for
// example). If this handler is not installed and there are no other uncaught
// exception handlers, uncaught exceptions will be caught by node's built-in
// exception handler and the process will still be terminated. However, the
// generated JavaScript code will be shown above the stack trace instead of
// the original source code.
if (installHandler && hasGlobalProcessEventEmitter()) {
uncaughtShimInstalled = true;
shimEmitUncaughtException();
}
}
};
exports.resetRetrieveHandlers = function() {
retrieveFileHandlers.length = 0;
retrieveMapHandlers.length = 0;
retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
retrieveSourceMap = handlerExec(retrieveMapHandlers);
retrieveFile = handlerExec(retrieveFileHandlers);
}

334
node_modules/ava/node_modules/stack-utils/index.js generated vendored Normal file
View file

@ -0,0 +1,334 @@
'use strict';
const escapeStringRegexp = require('escape-string-regexp');
const natives = [].concat(
require('module').builtinModules,
'bootstrap_node',
'node',
).map(n => new RegExp(`(?:\\(${n}\\.js:\\d+:\\d+\\)$|^\\s*at ${n}\\.js:\\d+:\\d+$)`));
natives.push(
/\(internal\/[^:]+:\d+:\d+\)$/,
/\s*at internal\/[^:]+:\d+:\d+$/,
/\/\.node-spawn-wrap-\w+-\w+\/node:\d+:\d+\)?$/
);
class StackUtils {
constructor (opts) {
opts = {
ignoredPackages: [],
...opts
};
if ('internals' in opts === false) {
opts.internals = StackUtils.nodeInternals();
}
if ('cwd' in opts === false) {
opts.cwd = process.cwd()
}
this._cwd = opts.cwd.replace(/\\/g, '/');
this._internals = [].concat(
opts.internals,
ignoredPackagesRegExp(opts.ignoredPackages)
);
this._wrapCallSite = opts.wrapCallSite || false;
}
static nodeInternals () {
return [...natives];
}
clean (stack, indent = 0) {
indent = ' '.repeat(indent);
if (!Array.isArray(stack)) {
stack = stack.split('\n');
}
if (!(/^\s*at /.test(stack[0])) && (/^\s*at /.test(stack[1]))) {
stack = stack.slice(1);
}
let outdent = false;
let lastNonAtLine = null;
const result = [];
stack.forEach(st => {
st = st.replace(/\\/g, '/');
if (this._internals.some(internal => internal.test(st))) {
return;
}
const isAtLine = /^\s*at /.test(st);
if (outdent) {
st = st.trimEnd().replace(/^(\s+)at /, '$1');
} else {
st = st.trim();
if (isAtLine) {
st = st.slice(3);
}
}
st = st.replace(`${this._cwd}/`, '');
if (st) {
if (isAtLine) {
if (lastNonAtLine) {
result.push(lastNonAtLine);
lastNonAtLine = null;
}
result.push(st);
} else {
outdent = true;
lastNonAtLine = st;
}
}
});
return result.map(line => `${indent}${line}\n`).join('');
}
captureString (limit, fn = this.captureString) {
if (typeof limit === 'function') {
fn = limit;
limit = Infinity;
}
const {stackTraceLimit} = Error;
if (limit) {
Error.stackTraceLimit = limit;
}
const obj = {};
Error.captureStackTrace(obj, fn);
const {stack} = obj;
Error.stackTraceLimit = stackTraceLimit;
return this.clean(stack);
}
capture (limit, fn = this.capture) {
if (typeof limit === 'function') {
fn = limit;
limit = Infinity;
}
const {prepareStackTrace, stackTraceLimit} = Error;
Error.prepareStackTrace = (obj, site) => {
if (this._wrapCallSite) {
return site.map(this._wrapCallSite);
}
return site;
};
if (limit) {
Error.stackTraceLimit = limit;
}
const obj = {};
Error.captureStackTrace(obj, fn);
const { stack } = obj;
Object.assign(Error, {prepareStackTrace, stackTraceLimit});
return stack;
}
at (fn = this.at) {
const [site] = this.capture(1, fn);
if (!site) {
return {};
}
const res = {
line: site.getLineNumber(),
column: site.getColumnNumber()
};
setFile(res, site.getFileName(), this._cwd);
if (site.isConstructor()) {
res.constructor = true;
}
if (site.isEval()) {
res.evalOrigin = site.getEvalOrigin();
}
// Node v10 stopped with the isNative() on callsites, apparently
/* istanbul ignore next */
if (site.isNative()) {
res.native = true;
}
let typename;
try {
typename = site.getTypeName();
} catch (_) {
}
if (typename && typename !== 'Object' && typename !== '[object Object]') {
res.type = typename;
}
const fname = site.getFunctionName();
if (fname) {
res.function = fname;
}
const meth = site.getMethodName();
if (meth && fname !== meth) {
res.method = meth;
}
return res;
}
parseLine (line) {
const match = line && line.match(re);
if (!match) {
return null;
}
const ctor = match[1] === 'new';
let fname = match[2];
const evalOrigin = match[3];
const evalFile = match[4];
const evalLine = Number(match[5]);
const evalCol = Number(match[6]);
let file = match[7];
const lnum = match[8];
const col = match[9];
const native = match[10] === 'native';
const closeParen = match[11] === ')';
let method;
const res = {};
if (lnum) {
res.line = Number(lnum);
}
if (col) {
res.column = Number(col);
}
if (closeParen && file) {
// make sure parens are balanced
// if we have a file like "asdf) [as foo] (xyz.js", then odds are
// that the fname should be += " (asdf) [as foo]" and the file
// should be just "xyz.js"
// walk backwards from the end to find the last unbalanced (
let closes = 0;
for (let i = file.length - 1; i > 0; i--) {
if (file.charAt(i) === ')') {
closes++;
} else if (file.charAt(i) === '(' && file.charAt(i - 1) === ' ') {
closes--;
if (closes === -1 && file.charAt(i - 1) === ' ') {
const before = file.slice(0, i - 1);
const after = file.slice(i + 1);
file = after;
fname += ` (${before}`;
break;
}
}
}
}
if (fname) {
const methodMatch = fname.match(methodRe);
if (methodMatch) {
fname = methodMatch[1];
method = methodMatch[2];
}
}
setFile(res, file, this._cwd);
if (ctor) {
res.constructor = true;
}
if (evalOrigin) {
res.evalOrigin = evalOrigin;
res.evalLine = evalLine;
res.evalColumn = evalCol;
res.evalFile = evalFile && evalFile.replace(/\\/g, '/');
}
if (native) {
res.native = true;
}
if (fname) {
res.function = fname;
}
if (method && fname !== method) {
res.method = method;
}
return res;
}
}
function setFile (result, filename, cwd) {
if (filename) {
filename = filename.replace(/\\/g, '/');
if (filename.startsWith(`${cwd}/`)) {
filename = filename.slice(cwd.length + 1);
}
result.file = filename;
}
}
function ignoredPackagesRegExp(ignoredPackages) {
if (ignoredPackages.length === 0) {
return [];
}
const packages = ignoredPackages.map(mod => escapeStringRegexp(mod));
return new RegExp(`[\/\\\\]node_modules[\/\\\\](?:${packages.join('|')})[\/\\\\][^:]+:\\d+:\\d+`)
}
const re = new RegExp(
'^' +
// Sometimes we strip out the ' at' because it's noisy
'(?:\\s*at )?' +
// $1 = ctor if 'new'
'(?:(new) )?' +
// $2 = function name (can be literally anything)
// May contain method at the end as [as xyz]
'(?:(.*?) \\()?' +
// (eval at <anonymous> (file.js:1:1),
// $3 = eval origin
// $4:$5:$6 are eval file/line/col, but not normally reported
'(?:eval at ([^ ]+) \\((.+?):(\\d+):(\\d+)\\), )?' +
// file:line:col
// $7:$8:$9
// $10 = 'native' if native
'(?:(.+?):(\\d+):(\\d+)|(native))' +
// maybe close the paren, then end
// if $11 is ), then we only allow balanced parens in the filename
// any imbalance is placed on the fname. This is a heuristic, and
// bound to be incorrect in some edge cases. The bet is that
// having weird characters in method names is more common than
// having weird characters in filenames, which seems reasonable.
'(\\)?)$'
);
const methodRe = /^(.*?) \[as (.*?)\]$/;
module.exports = StackUtils;

21
node_modules/ava/node_modules/stack-utils/license generated vendored Normal file
View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Isaac Z. Schlueter <i@izs.me>, James Talmage <james@talmage.io> (github.com/jamestalmage), and Contributors
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.

35
node_modules/ava/node_modules/stack-utils/package.json generated vendored Normal file
View file

@ -0,0 +1,35 @@
{
"name": "stack-utils",
"version": "2.0.2",
"description": "Captures and cleans stack traces",
"license": "MIT",
"repository": "tapjs/stack-utils",
"author": {
"name": "James Talmage",
"email": "james@talmage.io",
"url": "github.com/jamestalmage"
},
"engines": {
"node": ">=10"
},
"scripts": {
"test": "tap --no-esm --100",
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags"
},
"files": [
"index.js"
],
"dependencies": {
"escape-string-regexp": "^2.0.0"
},
"devDependencies": {
"bluebird": "^3.7.2",
"coveralls": "^3.0.9",
"nested-error-stacks": "^2.1.0",
"pify": "^4.0.1",
"q": "^1.5.1",
"tap": "=14.10.2-unbundled"
}
}

143
node_modules/ava/node_modules/stack-utils/readme.md generated vendored Normal file
View file

@ -0,0 +1,143 @@
# stack-utils
> Captures and cleans stack traces.
[![Linux Build](https://travis-ci.org/tapjs/stack-utils.svg?branch=master)](https://travis-ci.org/tapjs/stack-utils) [![Build status](https://ci.appveyor.com/api/projects/status/fb9i157knoixe3iq/branch/master?svg=true)](https://ci.appveyor.com/project/jamestalmage/stack-utils-oiw96/branch/master) [![Coverage](https://coveralls.io/repos/tapjs/stack-utils/badge.svg?branch=master&service=github)](https://coveralls.io/github/tapjs/stack-utils?branch=master)
Extracted from `lib/stack.js` in the [`node-tap` project](https://github.com/tapjs/node-tap)
## Install
```
$ npm install --save stack-utils
```
## Usage
```js
const StackUtils = require('stack-utils');
const stack = new StackUtils({cwd: process.cwd(), internals: StackUtils.nodeInternals()});
console.log(stack.clean(new Error().stack));
// outputs a beautified stack trace
```
## API
### new StackUtils([options])
Creates a new `stackUtils` instance.
#### options
##### internals
Type: `array` of `RegularExpression`s
A set of regular expressions that match internal stack stack trace lines which should be culled from the stack trace.
The default is `StackUtils.nodeInternals()`, this can be disabled by setting `[]` or appended using
`StackUtils.nodeInternals().concat(additionalRegExp)`. See also `ignoredPackages`.
##### ignoredPackages
Type: `array` of `string`s
An array of npm modules to be culled from the stack trace. This list will mapped to regular
expressions and merged with the `internals`.
Default `''`.
##### cwd
Type: `string`
The path to the current working directory. File names in the stack trace will be shown relative to this directory.
##### wrapCallSite
Type: `function(CallSite)`
A mapping function for manipulating CallSites before processing. The first argument is a CallSite instance, and the function should return a modified CallSite. This is useful for providing source map support.
### StackUtils.nodeInternals()
Returns an array of regular expressions that be used to cull lines from the stack trace that reference common Node.js internal files.
### stackUtils.clean(stack, indent = 0)
Cleans up a stack trace by deleting any lines that match the `internals` passed to the constructor, and shortening file names relative to `cwd`.
Returns a `string` with the cleaned up stack (always terminated with a `\n` newline character).
Spaces at the start of each line are trimmed, indentation can be added by setting `indent` to the desired number of spaces.
#### stack
*Required*
Type: `string` or an `array` of `string`s
### stackUtils.capture([limit], [startStackFunction])
Captures the current stack trace, returning an array of `CallSite`s. There are good overviews of the available CallSite methods [here](https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces), and [here](https://github.com/sindresorhus/callsites#api).
#### limit
Type: `number`
Default: `Infinity`
Limits the number of lines returned by dropping all lines in excess of the limit. This removes lines from the stack trace.
#### startStackFunction
Type: `function`
The function where the stack trace should start. The first line of the stack trace will be the function that called `startStackFunction`. This removes lines from the end of the stack trace.
### stackUtils.captureString([limit], [startStackFunction])
Captures the current stack trace, cleans it using `stackUtils.clean(stack)`, and returns a string with the cleaned stack trace. It takes the same arguments as `stackUtils.capture`.
### stackUtils.at([startStackFunction])
Captures the first line of the stack trace (or the first line after `startStackFunction` if supplied), and returns a `CallSite` like object that is serialization friendly (properties are actual values instead of getter functions).
The available properties are:
- `line`: `number`
- `column`: `number`
- `file`: `string`
- `constructor`: `boolean`
- `evalOrigin`: `string`
- `native`: `boolean`
- `type`: `string`
- `function`: `string`
- `method`: `string`
### stackUtils.parseLine(line)
Parses a `string` (which should be a single line from a stack trace), and generates an object with the following properties:
- `line`: `number`
- `column`: `number`
- `file`: `string`
- `constructor`: `boolean`
- `evalOrigin`: `string`
- `evalLine`: `number`
- `evalColumn`: `number`
- `evalFile`: `string`
- `native`: `boolean`
- `function`: `string`
- `method`: `string`
## License
MIT © [Isaac Z. Schlueter](http://github.com/isaacs), [James Talmage](http://github.com/jamestalmage)

View file

@ -0,0 +1,5 @@
'use strict';
module.exports = {
stdout: false,
stderr: false
};

139
node_modules/ava/node_modules/supports-color/index.js generated vendored Normal file
View file

@ -0,0 +1,139 @@
'use strict';
const os = require('os');
const tty = require('tty');
const hasFlag = require('has-flag');
const {env} = process;
let forceColor;
if (hasFlag('no-color') ||
hasFlag('no-colors') ||
hasFlag('color=false') ||
hasFlag('color=never')) {
forceColor = 0;
} else if (hasFlag('color') ||
hasFlag('colors') ||
hasFlag('color=true') ||
hasFlag('color=always')) {
forceColor = 1;
}
if ('FORCE_COLOR' in env) {
if (env.FORCE_COLOR === 'true') {
forceColor = 1;
} else if (env.FORCE_COLOR === 'false') {
forceColor = 0;
} else {
forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
}
}
function translateLevel(level) {
if (level === 0) {
return false;
}
return {
level,
hasBasic: true,
has256: level >= 2,
has16m: level >= 3
};
}
function supportsColor(haveStream, streamIsTTY) {
if (forceColor === 0) {
return 0;
}
if (hasFlag('color=16m') ||
hasFlag('color=full') ||
hasFlag('color=truecolor')) {
return 3;
}
if (hasFlag('color=256')) {
return 2;
}
if (haveStream && !streamIsTTY && forceColor === undefined) {
return 0;
}
const min = forceColor || 0;
if (env.TERM === 'dumb') {
return min;
}
if (process.platform === 'win32') {
// Windows 10 build 10586 is the first Windows release that supports 256 colors.
// Windows 10 build 14931 is the first release that supports 16m/TrueColor.
const osRelease = os.release().split('.');
if (
Number(osRelease[0]) >= 10 &&
Number(osRelease[2]) >= 10586
) {
return Number(osRelease[2]) >= 14931 ? 3 : 2;
}
return 1;
}
if ('CI' in env) {
if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') {
return 1;
}
return min;
}
if ('TEAMCITY_VERSION' in env) {
return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
}
if ('GITHUB_ACTIONS' in env) {
return 1;
}
if (env.COLORTERM === 'truecolor') {
return 3;
}
if ('TERM_PROGRAM' in env) {
const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
switch (env.TERM_PROGRAM) {
case 'iTerm.app':
return version >= 3 ? 3 : 2;
case 'Apple_Terminal':
return 2;
// No default
}
}
if (/-256(color)?$/i.test(env.TERM)) {
return 2;
}
if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
return 1;
}
if ('COLORTERM' in env) {
return 1;
}
return min;
}
function getSupportLevel(stream) {
const level = supportsColor(stream, stream && stream.isTTY);
return translateLevel(level);
}
module.exports = {
supportsColor: getSupportLevel,
stdout: translateLevel(supportsColor(true, tty.isatty(1))),
stderr: translateLevel(supportsColor(true, tty.isatty(2)))
};

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