This commit is contained in:
Iliyan Angelov
2025-09-14 23:24:25 +03:00
commit c67067a2a4
71311 changed files with 6800714 additions and 0 deletions

21
frontend/node_modules/jest-jasmine2/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Facebook, Inc. and its affiliates.
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,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export default class ExpectationFailed extends Error {
}

View File

@@ -0,0 +1,16 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class ExpectationFailed extends Error {}
exports.default = ExpectationFailed;

View File

@@ -0,0 +1,17 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export default class PCancelable<T> implements PromiseLike<T> {
private _pending;
private _canceled;
private _promise;
private _cancel?;
private _reject;
constructor(executor: (onCancel: (cancelHandler: () => void) => void, resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: unknown) => void) => void);
then<TResult1 = T, TResult2 = never>(onFulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult>(onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | undefined | null): Promise<T | TResult>;
cancel(): void;
}

View File

@@ -0,0 +1,139 @@
'use strict';
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class CancelError extends Error {
constructor() {
super('Promise was canceled');
this.name = 'CancelError';
}
}
class PCancelable {
constructor(executor) {
_defineProperty(this, '_pending', true);
_defineProperty(this, '_canceled', false);
_defineProperty(this, '_promise', void 0);
_defineProperty(this, '_cancel', void 0);
_defineProperty(this, '_reject', () => {});
this._promise = new Promise((resolve, reject) => {
this._reject = reject;
return executor(
fn => {
this._cancel = fn;
},
val => {
this._pending = false;
resolve(val);
},
err => {
this._pending = false;
reject(err);
}
);
});
}
then(onFulfilled, onRejected) {
return this._promise.then(onFulfilled, onRejected);
}
catch(onRejected) {
return this._promise.catch(onRejected);
}
cancel() {
if (!this._pending || this._canceled) {
return;
}
if (typeof this._cancel === 'function') {
try {
this._cancel();
} catch (err) {
this._reject(err);
}
}
this._canceled = true;
this._reject(new CancelError());
}
}
exports.default = PCancelable;

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { DiffOptions } from 'jest-matcher-utils';
import type { AssertionErrorWithStack } from './types';
declare function assertionErrorMessage(error: AssertionErrorWithStack, options: DiffOptions): string;
export default assertionErrorMessage;

View File

@@ -0,0 +1,156 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var _chalk = _interopRequireDefault(require('chalk'));
var _jestMatcherUtils = require('jest-matcher-utils');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const assertOperatorsMap = {
'!=': 'notEqual',
'!==': 'notStrictEqual',
'==': 'equal',
'===': 'strictEqual'
};
const humanReadableOperators = {
deepEqual: 'to deeply equal',
deepStrictEqual: 'to deeply and strictly equal',
equal: 'to be equal',
notDeepEqual: 'not to deeply equal',
notDeepStrictEqual: 'not to deeply and strictly equal',
notEqual: 'to not be equal',
notStrictEqual: 'not be strictly equal',
strictEqual: 'to strictly be equal'
};
const getOperatorName = (operator, stack) => {
if (typeof operator === 'string') {
return assertOperatorsMap[operator] || operator;
}
if (stack.match('.doesNotThrow')) {
return 'doesNotThrow';
}
if (stack.match('.throws')) {
return 'throws';
} // this fallback is only needed for versions older than node 10
if (stack.match('.fail')) {
return 'fail';
}
return '';
};
const operatorMessage = operator => {
const niceOperatorName = getOperatorName(operator, '');
const humanReadableOperator = humanReadableOperators[niceOperatorName];
return typeof operator === 'string'
? `${humanReadableOperator || niceOperatorName} to:\n`
: '';
};
const assertThrowingMatcherHint = operatorName =>
operatorName
? _chalk.default.dim('assert') +
_chalk.default.dim('.' + operatorName + '(') +
_chalk.default.red('function') +
_chalk.default.dim(')')
: '';
const assertMatcherHint = (operator, operatorName, expected) => {
let message = '';
if (operator === '==' && expected === true) {
message =
_chalk.default.dim('assert') +
_chalk.default.dim('(') +
_chalk.default.red('received') +
_chalk.default.dim(')');
} else if (operatorName) {
message =
_chalk.default.dim('assert') +
_chalk.default.dim('.' + operatorName + '(') +
_chalk.default.red('received') +
_chalk.default.dim(', ') +
_chalk.default.green('expected') +
_chalk.default.dim(')');
}
return message;
};
function assertionErrorMessage(error, options) {
const {expected, actual, generatedMessage, message, operator, stack} = error;
const diffString = (0, _jestMatcherUtils.diff)(expected, actual, options);
const hasCustomMessage = !generatedMessage;
const operatorName = getOperatorName(operator, stack);
const trimmedStack = stack
.replace(message, '')
.replace(/AssertionError(.*)/g, '');
if (operatorName === 'doesNotThrow') {
return (
buildHintString(assertThrowingMatcherHint(operatorName)) +
_chalk.default.reset('Expected the function not to throw an error.\n') +
_chalk.default.reset('Instead, it threw:\n') +
` ${(0, _jestMatcherUtils.printReceived)(actual)}` +
_chalk.default.reset(
hasCustomMessage ? '\n\nMessage:\n ' + message : ''
) +
trimmedStack
);
}
if (operatorName === 'throws') {
return (
buildHintString(assertThrowingMatcherHint(operatorName)) +
_chalk.default.reset('Expected the function to throw an error.\n') +
_chalk.default.reset("But it didn't throw anything.") +
_chalk.default.reset(
hasCustomMessage ? '\n\nMessage:\n ' + message : ''
) +
trimmedStack
);
}
if (operatorName === 'fail') {
return (
buildHintString(assertMatcherHint(operator, operatorName, expected)) +
_chalk.default.reset(hasCustomMessage ? 'Message:\n ' + message : '') +
trimmedStack
);
}
return (
buildHintString(assertMatcherHint(operator, operatorName, expected)) +
_chalk.default.reset(`Expected value ${operatorMessage(operator)}`) +
` ${(0, _jestMatcherUtils.printExpected)(expected)}\n` +
_chalk.default.reset('Received:\n') +
` ${(0, _jestMatcherUtils.printReceived)(actual)}` +
_chalk.default.reset(hasCustomMessage ? '\n\nMessage:\n ' + message : '') +
(diffString ? `\n\nDifference:\n\n${diffString}` : '') +
trimmedStack
);
}
function buildHintString(hint) {
return hint ? hint + '\n\n' : '';
}
var _default = assertionErrorMessage;
exports.default = _default;

8
frontend/node_modules/jest-jasmine2/build/each.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { JestEnvironment } from '@jest/environment';
export default function each(environment: JestEnvironment): void;

44
frontend/node_modules/jest-jasmine2/build/each.js generated vendored Normal file
View File

@@ -0,0 +1,44 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = each;
var _jestEach = require('jest-each');
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function each(environment) {
environment.global.it.each = (0, _jestEach.bind)(environment.global.it);
environment.global.fit.each = (0, _jestEach.bind)(environment.global.fit);
environment.global.xit.each = (0, _jestEach.bind)(environment.global.xit);
environment.global.describe.each = (0, _jestEach.bind)(
environment.global.describe,
false
);
environment.global.xdescribe.each = (0, _jestEach.bind)(
environment.global.xdescribe,
false
);
environment.global.fdescribe.each = (0, _jestEach.bind)(
environment.global.fdescribe,
false
);
environment.global.it.concurrent.each = (0, _jestEach.bind)(
environment.global.it.concurrent,
false
);
environment.global.it.concurrent.only.each = (0, _jestEach.bind)(
environment.global.it.concurrent.only,
false
);
environment.global.it.concurrent.skip.each = (0, _jestEach.bind)(
environment.global.it.concurrent.skip,
false
);
}

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Global } from '@jest/types';
export declare function installErrorOnPrivate(global: Global.Global): void;

View File

@@ -0,0 +1,66 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.installErrorOnPrivate = installErrorOnPrivate;
var _jestUtil = require('jest-util');
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// prettier-ignore
const disabledGlobals = {
fail: 'Illegal usage of global `fail`, prefer throwing an error, or the `done.fail` callback.',
pending: 'Illegal usage of global `pending`, prefer explicitly skipping a test using `test.skip`',
spyOn: 'Illegal usage of global `spyOn`, prefer `jest.spyOn`.',
spyOnProperty: 'Illegal usage of global `spyOnProperty`, prefer `jest.spyOn`.'
};
// prettier-ignore
const disabledJasmineMethods = {
addMatchers: 'Illegal usage of `jasmine.addMatchers`, prefer `expect.extends`.',
any: 'Illegal usage of `jasmine.any`, prefer `expect.any`.',
anything: 'Illegal usage of `jasmine.anything`, prefer `expect.anything`.',
arrayContaining: 'Illegal usage of `jasmine.arrayContaining`, prefer `expect.arrayContaining`.',
createSpy: 'Illegal usage of `jasmine.createSpy`, prefer `jest.fn`.',
objectContaining: 'Illegal usage of `jasmine.objectContaining`, prefer `expect.objectContaining`.',
stringMatching: 'Illegal usage of `jasmine.stringMatching`, prefer `expect.stringMatching`.'
};
function installErrorOnPrivate(global) {
const jasmine = global.jasmine;
Object.keys(disabledGlobals).forEach(functionName => {
global[functionName] = () => {
throwAtFunction(disabledGlobals[functionName], global[functionName]);
};
});
Object.keys(disabledJasmineMethods).forEach(methodName => {
// @ts-expect-error
jasmine[methodName] = () => {
throwAtFunction(disabledJasmineMethods[methodName], jasmine[methodName]);
};
});
function set() {
throwAtFunction(
'Illegal usage of `jasmine.DEFAULT_TIMEOUT_INTERVAL`, prefer `jest.setTimeout`.',
set
);
}
const original = jasmine.DEFAULT_TIMEOUT_INTERVAL;
Object.defineProperty(jasmine, 'DEFAULT_TIMEOUT_INTERVAL', {
configurable: true,
enumerable: true,
get: () => original,
set
});
}
function throwAtFunction(message, fn) {
throw new _jestUtil.ErrorWithStack(message, fn);
}

View File

@@ -0,0 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { FailedAssertion } from '@jest/test-result';
export declare type Options = {
matcherName: string;
passed: boolean;
actual?: any;
error?: any;
expected?: any;
message?: string | null;
};
export default function expectationResultFactory(options: Options, initError?: Error): FailedAssertion;

View File

@@ -0,0 +1,93 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = expectationResultFactory;
var _prettyFormat = require('pretty-format');
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function messageFormatter({error, message, passed}) {
if (passed) {
return 'Passed.';
}
if (message) {
return message;
}
if (typeof error === 'string') {
return error;
}
if (
// duck-type Error, see #2549
error &&
typeof error === 'object' &&
typeof error.message === 'string' &&
typeof error.name === 'string'
) {
if (error.message === '') {
return error.name;
}
return `${error.name}: ${error.message}`;
}
return `thrown: ${(0, _prettyFormat.format)(error, {
maxDepth: 3
})}`;
}
function stackFormatter(options, initError, errorMessage) {
if (options.passed) {
return '';
}
if (options.error) {
if (typeof options.error.stack === 'string') {
return options.error.stack;
}
if (options.error === errorMessage) {
return errorMessage;
}
}
if (initError) {
return errorMessage.trimRight() + '\n\n' + initError.stack;
}
return new Error(errorMessage).stack;
}
function expectationResultFactory(options, initError) {
const message = messageFormatter(options);
const stack = stackFormatter(options, initError, message);
if (options.passed) {
return {
error: options.error,
matcherName: options.matcherName,
message,
passed: options.passed,
stack
};
}
return {
actual: options.actual,
error: options.error,
expected: options.expected,
matcherName: options.matcherName,
message,
passed: options.passed,
stack
};
}

12
frontend/node_modules/jest-jasmine2/build/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { JestEnvironment } from '@jest/environment';
import type { TestResult } from '@jest/test-result';
import type { Config } from '@jest/types';
import type Runtime from 'jest-runtime';
export type { Jasmine } from './types';
export default function jasmine2(globalConfig: Config.GlobalConfig, config: Config.ProjectConfig, environment: JestEnvironment, runtime: Runtime, testPath: string): Promise<TestResult>;

247
frontend/node_modules/jest-jasmine2/build/index.js generated vendored Normal file
View File

@@ -0,0 +1,247 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = jasmine2;
var path = _interopRequireWildcard(require('path'));
var _sourceMap = require('@jest/source-map');
var _each = _interopRequireDefault(require('./each'));
var _errorOnPrivate = require('./errorOnPrivate');
var _jasmineAsyncInstall = _interopRequireDefault(
require('./jasmineAsyncInstall')
);
var _reporter = _interopRequireDefault(require('./reporter'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const JASMINE = require.resolve('./jasmine/jasmineLight');
const jestEachBuildDir = path.dirname(require.resolve('jest-each'));
async function jasmine2(globalConfig, config, environment, runtime, testPath) {
const reporter = new _reporter.default(globalConfig, config, testPath);
const jasmineFactory = runtime.requireInternalModule(JASMINE);
const jasmine = jasmineFactory.create({
process,
testPath,
testTimeout: globalConfig.testTimeout
});
const env = jasmine.getEnv();
const jasmineInterface = jasmineFactory._interface(jasmine, env);
Object.assign(environment.global, jasmineInterface);
env.addReporter(jasmineInterface.jsApiReporter); // TODO: Remove config option if V8 exposes some way of getting location of caller
// in a future version
if (config.testLocationInResults === true) {
function wrapIt(original) {
const wrapped = (testName, fn, timeout) => {
var _stack$getFileName;
const sourcemaps = runtime.getSourceMaps();
let stack = (0, _sourceMap.getCallsite)(1, sourcemaps);
const it = original(testName, fn, timeout);
if (
(_stack$getFileName = stack.getFileName()) !== null &&
_stack$getFileName !== void 0 &&
_stack$getFileName.startsWith(jestEachBuildDir)
) {
stack = (0, _sourceMap.getCallsite)(4, sourcemaps);
} // @ts-expect-error
it.result.__callsite = stack;
return it;
};
return wrapped;
}
environment.global.it = wrapIt(environment.global.it);
environment.global.xit = wrapIt(environment.global.xit);
environment.global.fit = wrapIt(environment.global.fit);
}
(0, _jasmineAsyncInstall.default)(globalConfig, environment.global);
(0, _each.default)(environment);
environment.global.test = environment.global.it;
environment.global.it.only = environment.global.fit;
environment.global.it.todo = env.todo;
environment.global.it.skip = environment.global.xit;
environment.global.xtest = environment.global.xit;
environment.global.describe.skip = environment.global.xdescribe;
environment.global.describe.only = environment.global.fdescribe;
if (config.timers === 'fake' || config.timers === 'modern') {
environment.fakeTimersModern.useFakeTimers();
} else if (config.timers === 'legacy') {
environment.fakeTimers.useFakeTimers();
}
env.beforeEach(() => {
if (config.resetModules) {
runtime.resetModules();
}
if (config.clearMocks) {
runtime.clearAllMocks();
}
if (config.resetMocks) {
runtime.resetAllMocks();
if (config.timers === 'legacy') {
environment.fakeTimers.useFakeTimers();
}
}
if (config.restoreMocks) {
runtime.restoreAllMocks();
}
});
env.addReporter(reporter);
runtime
.requireInternalModule(path.resolve(__dirname, './jestExpect.js'))
.default({
expand: globalConfig.expand
});
if (globalConfig.errorOnDeprecated) {
(0, _errorOnPrivate.installErrorOnPrivate)(environment.global);
} else {
Object.defineProperty(jasmine, 'DEFAULT_TIMEOUT_INTERVAL', {
configurable: true,
enumerable: true,
get() {
return this._DEFAULT_TIMEOUT_INTERVAL;
},
set(value) {
this._DEFAULT_TIMEOUT_INTERVAL = value;
}
});
}
const snapshotState = await runtime
.requireInternalModule(path.resolve(__dirname, './setup_jest_globals.js'))
.default({
config,
globalConfig,
localRequire: runtime.requireModule.bind(runtime),
testPath
});
for (const path of config.setupFilesAfterEnv) {
const esm = runtime.unstable_shouldLoadAsEsm(path);
if (esm) {
await runtime.unstable_importModule(path);
} else {
runtime.requireModule(path);
}
}
if (globalConfig.testNamePattern) {
const testNameRegex = new RegExp(globalConfig.testNamePattern, 'i');
env.specFilter = spec => testNameRegex.test(spec.getFullName());
}
const esm = runtime.unstable_shouldLoadAsEsm(testPath);
if (esm) {
await runtime.unstable_importModule(testPath);
} else {
runtime.requireModule(testPath);
}
await env.execute();
const results = await reporter.getResults();
return addSnapshotData(results, snapshotState);
}
const addSnapshotData = (results, snapshotState) => {
results.testResults.forEach(({fullName, status}) => {
if (status === 'pending' || status === 'failed') {
// if test is skipped or failed, we don't want to mark
// its snapshots as obsolete.
snapshotState.markSnapshotsAsCheckedForTest(fullName);
}
});
const uncheckedCount = snapshotState.getUncheckedCount();
const uncheckedKeys = snapshotState.getUncheckedKeys();
if (uncheckedCount) {
snapshotState.removeUncheckedKeys();
}
const status = snapshotState.save();
results.snapshot.fileDeleted = status.deleted;
results.snapshot.added = snapshotState.added;
results.snapshot.matched = snapshotState.matched;
results.snapshot.unmatched = snapshotState.unmatched;
results.snapshot.updated = snapshotState.updated;
results.snapshot.unchecked = !status.deleted ? uncheckedCount : 0; // Copy the array to prevent memory leaks
results.snapshot.uncheckedKeys = Array.from(uncheckedKeys);
return results;
};

10
frontend/node_modules/jest-jasmine2/build/isError.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export default function isError(potentialError: any): {
isError: boolean;
message: string | null;
};

32
frontend/node_modules/jest-jasmine2/build/isError.js generated vendored Normal file
View File

@@ -0,0 +1,32 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = isError;
var _prettyFormat = require('pretty-format');
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function isError(potentialError) { // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
// duck-type Error, see #2549
const isError =
potentialError !== null &&
typeof potentialError === 'object' &&
typeof potentialError.message === 'string' &&
typeof potentialError.name === 'string';
const message = isError
? null
: `Failed: ${(0, _prettyFormat.format)(potentialError, {
maxDepth: 3
})}`;
return {
isError,
message
};
}

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
export declare type Context = {
object: unknown;
args: Array<unknown>;
returnValue?: unknown;
};
declare class CallTracker {
track: (context: Context) => void;
any: () => boolean;
count: () => number;
argsFor: (index: number) => Array<unknown>;
all: () => Array<Context>;
allArgs: () => Array<unknown>;
first: () => Context;
mostRecent: () => Context;
reset: () => void;
constructor();
}
export default CallTracker;

View File

@@ -0,0 +1,121 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// This file is a heavily modified fork of Jasmine. Original license:
/*
Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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.
*/
class CallTracker {
constructor() {
_defineProperty(this, 'track', void 0);
_defineProperty(this, 'any', void 0);
_defineProperty(this, 'count', void 0);
_defineProperty(this, 'argsFor', void 0);
_defineProperty(this, 'all', void 0);
_defineProperty(this, 'allArgs', void 0);
_defineProperty(this, 'first', void 0);
_defineProperty(this, 'mostRecent', void 0);
_defineProperty(this, 'reset', void 0);
let calls = [];
this.track = function (context) {
calls.push(context);
};
this.any = function () {
return !!calls.length;
};
this.count = function () {
return calls.length;
};
this.argsFor = function (index) {
const call = calls[index];
return call ? call.args : [];
};
this.all = function () {
return calls;
};
this.allArgs = function () {
const callArgs = [];
for (let i = 0; i < calls.length; i++) {
callArgs.push(calls[i].args);
}
return callArgs;
};
this.first = function () {
return calls[0];
};
this.mostRecent = function () {
return calls[calls.length - 1];
};
this.reset = function () {
calls = [];
};
}
}
var _default = CallTracker;
exports.default = _default;

View File

@@ -0,0 +1,43 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import { QueueableFn } from '../queueRunner';
import type { AssertionErrorWithStack, Jasmine, Reporter, SpecDefinitionsFn, Spy } from '../types';
import type { default as Spec } from './Spec';
import type Suite from './Suite';
export default function jasmineEnv(j$: Jasmine): {
new (): {
specFilter: (spec: Spec) => boolean;
catchExceptions: (value: unknown) => boolean;
throwOnExpectationFailure: (value: unknown) => void;
catchingExceptions: () => boolean;
topSuite: () => Suite;
fail: (error: Error | AssertionErrorWithStack) => void;
pending: (message: string) => void;
afterAll: (afterAllFunction: QueueableFn['fn'], timeout?: number | undefined) => void;
fit: (description: string, fn: QueueableFn['fn'], timeout?: number | undefined) => Spec;
throwingExpectationFailures: () => boolean;
randomizeTests: (value: unknown) => void;
randomTests: () => boolean;
seed: (value: unknown) => unknown;
execute: (runnablesToRun?: string[] | undefined, suiteTree?: Suite | undefined) => Promise<void>;
fdescribe: (description: string, specDefinitions: SpecDefinitionsFn) => Suite;
spyOn: (obj: Record<string, Spy>, methodName: string, accessType?: "configurable" | "enumerable" | "value" | "writable" | "get" | "set" | undefined) => Spy;
beforeEach: (beforeEachFunction: QueueableFn['fn'], timeout?: number | undefined) => void;
afterEach: (afterEachFunction: QueueableFn['fn'], timeout?: number | undefined) => void;
clearReporters: () => void;
addReporter: (reporterToAdd: Reporter) => void;
it: (description: string, fn: QueueableFn['fn'], timeout?: number | undefined) => Spec;
xdescribe: (description: string, specDefinitions: SpecDefinitionsFn) => Suite;
xit: (description: string, fn: QueueableFn['fn'], timeout?: number | undefined) => Spec;
beforeAll: (beforeAllFunction: QueueableFn['fn'], timeout?: number | undefined) => void;
todo: () => Spec;
provideFallbackReporter: (reporterToAdd: Reporter) => void;
allowRespy: (allow: boolean) => void;
describe: (description: string, specDefinitions: SpecDefinitionsFn) => Suite;
};
};

View File

@@ -0,0 +1,716 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = jasmineEnv;
var _assert = require('assert');
var _jestUtil = require('jest-util');
var _assertionErrorMessage = _interopRequireDefault(
require('../assertionErrorMessage')
);
var _isError = _interopRequireDefault(require('../isError'));
var _queueRunner = _interopRequireDefault(require('../queueRunner'));
var _treeProcessor = _interopRequireDefault(require('../treeProcessor'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function jasmineEnv(j$) {
return class Env {
constructor() {
_defineProperty(this, 'specFilter', void 0);
_defineProperty(this, 'catchExceptions', void 0);
_defineProperty(this, 'throwOnExpectationFailure', void 0);
_defineProperty(this, 'catchingExceptions', void 0);
_defineProperty(this, 'topSuite', void 0);
_defineProperty(this, 'fail', void 0);
_defineProperty(this, 'pending', void 0);
_defineProperty(this, 'afterAll', void 0);
_defineProperty(this, 'fit', void 0);
_defineProperty(this, 'throwingExpectationFailures', void 0);
_defineProperty(this, 'randomizeTests', void 0);
_defineProperty(this, 'randomTests', void 0);
_defineProperty(this, 'seed', void 0);
_defineProperty(this, 'execute', void 0);
_defineProperty(this, 'fdescribe', void 0);
_defineProperty(this, 'spyOn', void 0);
_defineProperty(this, 'beforeEach', void 0);
_defineProperty(this, 'afterEach', void 0);
_defineProperty(this, 'clearReporters', void 0);
_defineProperty(this, 'addReporter', void 0);
_defineProperty(this, 'it', void 0);
_defineProperty(this, 'xdescribe', void 0);
_defineProperty(this, 'xit', void 0);
_defineProperty(this, 'beforeAll', void 0);
_defineProperty(this, 'todo', void 0);
_defineProperty(this, 'provideFallbackReporter', void 0);
_defineProperty(this, 'allowRespy', void 0);
_defineProperty(this, 'describe', void 0);
let totalSpecsDefined = 0;
let catchExceptions = true;
const realSetTimeout = global.setTimeout;
const realClearTimeout = global.clearTimeout;
const runnableResources = {};
const currentlyExecutingSuites = [];
let currentSpec = null;
let throwOnExpectationFailure = false;
let random = false;
let seed = null;
let nextSpecId = 0;
let nextSuiteId = 0;
const getNextSpecId = function () {
return 'spec' + nextSpecId++;
};
const getNextSuiteId = function () {
return 'suite' + nextSuiteId++;
};
const topSuite = new j$.Suite({
id: getNextSuiteId(),
description: '',
getTestPath() {
return j$.testPath;
}
});
let currentDeclarationSuite = topSuite;
const currentSuite = function () {
return currentlyExecutingSuites[currentlyExecutingSuites.length - 1];
};
const currentRunnable = function () {
return currentSpec || currentSuite();
};
const reporter = new j$.ReportDispatcher([
'jasmineStarted',
'jasmineDone',
'suiteStarted',
'suiteDone',
'specStarted',
'specDone'
]);
this.specFilter = function () {
return true;
};
const defaultResourcesForRunnable = function (id, _parentRunnableId) {
const resources = {
spies: []
};
runnableResources[id] = resources;
};
const clearResourcesForRunnable = function (id) {
spyRegistry.clearSpies();
delete runnableResources[id];
};
const beforeAndAfterFns = function (suite) {
return function () {
let afters = [];
let befores = [];
while (suite) {
befores = befores.concat(suite.beforeFns);
afters = afters.concat(suite.afterFns);
suite = suite.parentSuite;
}
return {
befores: befores.reverse(),
afters
};
};
};
const getSpecName = function (spec, suite) {
const fullName = [spec.description];
const suiteFullName = suite.getFullName();
if (suiteFullName !== '') {
fullName.unshift(suiteFullName);
}
return fullName.join(' ');
};
this.catchExceptions = function (value) {
catchExceptions = !!value;
return catchExceptions;
};
this.catchingExceptions = function () {
return catchExceptions;
};
this.throwOnExpectationFailure = function (value) {
throwOnExpectationFailure = !!value;
};
this.throwingExpectationFailures = function () {
return throwOnExpectationFailure;
};
this.randomizeTests = function (value) {
random = !!value;
};
this.randomTests = function () {
return random;
};
this.seed = function (value) {
if (value) {
seed = value;
}
return seed;
};
const queueRunnerFactory = options => {
options.clearTimeout = realClearTimeout;
options.fail = this.fail;
options.setTimeout = realSetTimeout;
return (0, _queueRunner.default)(options);
};
this.topSuite = function () {
return topSuite;
};
const uncaught = err => {
if (currentSpec) {
currentSpec.onException(err);
currentSpec.cancel();
} else {
console.error('Unhandled error');
console.error(err.stack);
}
};
let oldListenersException;
let oldListenersRejection;
const executionSetup = function () {
// Need to ensure we are the only ones handling these exceptions.
oldListenersException = process.listeners('uncaughtException').slice();
oldListenersRejection = process.listeners('unhandledRejection').slice();
j$.process.removeAllListeners('uncaughtException');
j$.process.removeAllListeners('unhandledRejection');
j$.process.on('uncaughtException', uncaught);
j$.process.on('unhandledRejection', uncaught);
};
const executionTeardown = function () {
j$.process.removeListener('uncaughtException', uncaught);
j$.process.removeListener('unhandledRejection', uncaught); // restore previous exception handlers
oldListenersException.forEach(listener => {
j$.process.on('uncaughtException', listener);
});
oldListenersRejection.forEach(listener => {
j$.process.on('unhandledRejection', listener);
});
};
this.execute = async function (runnablesToRun, suiteTree = topSuite) {
if (!runnablesToRun) {
if (focusedRunnables.length) {
runnablesToRun = focusedRunnables;
} else {
runnablesToRun = [suiteTree.id];
}
}
if (currentlyExecutingSuites.length === 0) {
executionSetup();
}
const lastDeclarationSuite = currentDeclarationSuite;
await (0, _treeProcessor.default)({
nodeComplete(suite) {
if (!suite.disabled) {
clearResourcesForRunnable(suite.id);
}
currentlyExecutingSuites.pop();
if (suite === topSuite) {
reporter.jasmineDone({
failedExpectations: topSuite.result.failedExpectations
});
} else {
reporter.suiteDone(suite.getResult());
}
},
nodeStart(suite) {
currentlyExecutingSuites.push(suite);
defaultResourcesForRunnable(
suite.id,
suite.parentSuite && suite.parentSuite.id
);
if (suite === topSuite) {
reporter.jasmineStarted({
totalSpecsDefined
});
} else {
reporter.suiteStarted(suite.result);
}
},
queueRunnerFactory,
runnableIds: runnablesToRun,
tree: suiteTree
});
currentDeclarationSuite = lastDeclarationSuite;
if (currentlyExecutingSuites.length === 0) {
executionTeardown();
}
};
this.addReporter = function (reporterToAdd) {
reporter.addReporter(reporterToAdd);
};
this.provideFallbackReporter = function (reporterToAdd) {
reporter.provideFallbackReporter(reporterToAdd);
};
this.clearReporters = function () {
reporter.clearReporters();
};
const spyRegistry = new j$.SpyRegistry({
currentSpies() {
if (!currentRunnable()) {
throw new Error(
'Spies must be created in a before function or a spec'
);
}
return runnableResources[currentRunnable().id].spies;
}
});
this.allowRespy = function (allow) {
spyRegistry.allowRespy(allow);
};
this.spyOn = function (...args) {
return spyRegistry.spyOn.apply(spyRegistry, args);
};
const suiteFactory = function (description) {
const suite = new j$.Suite({
id: getNextSuiteId(),
description,
parentSuite: currentDeclarationSuite,
throwOnExpectationFailure,
getTestPath() {
return j$.testPath;
}
});
return suite;
};
this.describe = function (description, specDefinitions) {
const suite = suiteFactory(description);
if (specDefinitions === undefined) {
throw new Error(
'Missing second argument. It must be a callback function.'
);
}
if (typeof specDefinitions !== 'function') {
throw new Error(
`Invalid second argument, ${specDefinitions}. It must be a callback function.`
);
}
if (specDefinitions.length > 0) {
throw new Error('describe does not expect any arguments');
}
if (currentDeclarationSuite.markedPending) {
suite.pend();
}
if (currentDeclarationSuite.markedTodo) {
// @ts-expect-error TODO Possible error: Suite does not have todo method
suite.todo();
}
addSpecsToSuite(suite, specDefinitions);
return suite;
};
this.xdescribe = function (description, specDefinitions) {
const suite = suiteFactory(description);
suite.pend();
addSpecsToSuite(suite, specDefinitions);
return suite;
};
const focusedRunnables = [];
this.fdescribe = function (description, specDefinitions) {
const suite = suiteFactory(description);
suite.isFocused = true;
focusedRunnables.push(suite.id);
unfocusAncestor();
addSpecsToSuite(suite, specDefinitions);
return suite;
};
const addSpecsToSuite = (suite, specDefinitions) => {
const parentSuite = currentDeclarationSuite;
parentSuite.addChild(suite);
currentDeclarationSuite = suite;
let declarationError = undefined;
let describeReturnValue;
try {
describeReturnValue = specDefinitions.call(suite);
} catch (e) {
declarationError = e;
}
if ((0, _jestUtil.isPromise)(describeReturnValue)) {
declarationError = new Error(
'Returning a Promise from "describe" is not supported. Tests must be defined synchronously.'
);
} else if (describeReturnValue !== undefined) {
declarationError = new Error(
'A "describe" callback must not return a value.'
);
}
if (declarationError) {
this.it('encountered a declaration exception', () => {
throw declarationError;
});
}
currentDeclarationSuite = parentSuite;
};
function findFocusedAncestor(suite) {
while (suite) {
if (suite.isFocused) {
return suite.id;
}
suite = suite.parentSuite;
}
return null;
}
function unfocusAncestor() {
const focusedAncestor = findFocusedAncestor(currentDeclarationSuite);
if (focusedAncestor) {
for (let i = 0; i < focusedRunnables.length; i++) {
if (focusedRunnables[i] === focusedAncestor) {
focusedRunnables.splice(i, 1);
break;
}
}
}
}
const specFactory = (description, fn, suite, timeout) => {
totalSpecsDefined++;
const spec = new j$.Spec({
id: getNextSpecId(),
beforeAndAfterFns: beforeAndAfterFns(suite),
resultCallback: specResultCallback,
getSpecName(spec) {
return getSpecName(spec, suite);
},
getTestPath() {
return j$.testPath;
},
onStart: specStarted,
description,
queueRunnerFactory,
userContext() {
return suite.clonedSharedUserContext();
},
queueableFn: {
fn,
timeout() {
return timeout || j$._DEFAULT_TIMEOUT_INTERVAL;
}
},
throwOnExpectationFailure
});
if (!this.specFilter(spec)) {
spec.disable();
}
return spec;
function specResultCallback(result) {
clearResourcesForRunnable(spec.id);
currentSpec = null;
reporter.specDone(result);
}
function specStarted(spec) {
currentSpec = spec;
defaultResourcesForRunnable(spec.id, suite.id);
reporter.specStarted(spec.result);
}
};
this.it = function (description, fn, timeout) {
if (typeof description !== 'string') {
throw new Error(
`Invalid first argument, ${description}. It must be a string.`
);
}
if (fn === undefined) {
throw new Error(
'Missing second argument. It must be a callback function. Perhaps you want to use `test.todo` for a test placeholder.'
);
}
if (typeof fn !== 'function') {
throw new Error(
`Invalid second argument, ${fn}. It must be a callback function.`
);
}
const spec = specFactory(
description,
fn,
currentDeclarationSuite,
timeout
);
if (currentDeclarationSuite.markedPending) {
spec.pend();
} // When a test is defined inside another, jasmine will not run it.
// This check throws an error to warn the user about the edge-case.
if (currentSpec !== null) {
throw new Error(
`Tests cannot be nested. Test "${spec.description}" cannot run because it is nested within "${currentSpec.description}".`
);
}
currentDeclarationSuite.addChild(spec);
return spec;
};
this.xit = function (...args) {
const spec = this.it.apply(this, args);
spec.pend('Temporarily disabled with xit');
return spec;
};
this.todo = function () {
const description = arguments[0];
if (arguments.length !== 1 || typeof description !== 'string') {
throw new _jestUtil.ErrorWithStack(
'Todo must be called with only a description.',
this.todo
);
}
const spec = specFactory(
description,
() => {},
currentDeclarationSuite
);
if (currentDeclarationSuite.markedPending) {
spec.pend();
} else {
spec.todo();
}
currentDeclarationSuite.addChild(spec);
return spec;
};
this.fit = function (description, fn, timeout) {
const spec = specFactory(
description,
fn,
currentDeclarationSuite,
timeout
);
currentDeclarationSuite.addChild(spec);
if (currentDeclarationSuite.markedPending) {
spec.pend();
} else {
focusedRunnables.push(spec.id);
}
unfocusAncestor();
return spec;
};
this.beforeEach = function (beforeEachFunction, timeout) {
currentDeclarationSuite.beforeEach({
fn: beforeEachFunction,
timeout() {
return timeout || j$._DEFAULT_TIMEOUT_INTERVAL;
}
});
};
this.beforeAll = function (beforeAllFunction, timeout) {
currentDeclarationSuite.beforeAll({
fn: beforeAllFunction,
timeout() {
return timeout || j$._DEFAULT_TIMEOUT_INTERVAL;
}
});
};
this.afterEach = function (afterEachFunction, timeout) {
currentDeclarationSuite.afterEach({
fn: afterEachFunction,
timeout() {
return timeout || j$._DEFAULT_TIMEOUT_INTERVAL;
}
});
};
this.afterAll = function (afterAllFunction, timeout) {
currentDeclarationSuite.afterAll({
fn: afterAllFunction,
timeout() {
return timeout || j$._DEFAULT_TIMEOUT_INTERVAL;
}
});
};
this.pending = function (message) {
let fullMessage = j$.Spec.pendingSpecExceptionMessage;
if (message) {
fullMessage += message;
}
throw fullMessage;
};
this.fail = function (error) {
let checkIsError;
let message;
if (
error instanceof _assert.AssertionError ||
(error && error.name === _assert.AssertionError.name)
) {
checkIsError = false; // @ts-expect-error TODO Possible error: j$.Spec does not have expand property
message = (0, _assertionErrorMessage.default)(error, {
expand: j$.Spec.expand
});
} else {
const check = (0, _isError.default)(error);
checkIsError = check.isError;
message = check.message;
}
const errorAsErrorObject = checkIsError ? error : new Error(message);
const runnable = currentRunnable();
if (!runnable) {
errorAsErrorObject.message =
'Caught error after test environment was torn down\n\n' +
errorAsErrorObject.message;
throw errorAsErrorObject;
}
runnable.addExpectationResult(false, {
matcherName: '',
passed: false,
expected: '',
actual: '',
message,
error: errorAsErrorObject
});
};
}
};
}

View File

@@ -0,0 +1,31 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { Reporter, RunDetails } from '../types';
import type { SpecResult } from './Spec';
import type { SuiteResult } from './Suite';
import type Timer from './Timer';
export default class JsApiReporter implements Reporter {
started: boolean;
finished: boolean;
runDetails: RunDetails;
jasmineStarted: (runDetails: RunDetails) => void;
jasmineDone: (runDetails: RunDetails) => void;
status: () => unknown;
executionTime: () => unknown;
suiteStarted: (result: SuiteResult) => void;
suiteDone: (result: SuiteResult) => void;
suiteResults: (index: number, length: number) => Array<SuiteResult>;
suites: () => Record<string, SuiteResult>;
specResults: (index: number, length: number) => Array<SpecResult>;
specDone: (result: SpecResult) => void;
specs: () => Array<SpecResult>;
specStarted: (spec: SpecResult) => void;
constructor(options: {
timer?: Timer;
});
}

View File

@@ -0,0 +1,173 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// This file is a heavily modified fork of Jasmine. Original license:
/*
Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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.
*/
/* eslint-disable sort-keys */
const noopTimer = {
start() {},
elapsed() {
return 0;
}
};
class JsApiReporter {
constructor(options) {
_defineProperty(this, 'started', void 0);
_defineProperty(this, 'finished', void 0);
_defineProperty(this, 'runDetails', void 0);
_defineProperty(this, 'jasmineStarted', void 0);
_defineProperty(this, 'jasmineDone', void 0);
_defineProperty(this, 'status', void 0);
_defineProperty(this, 'executionTime', void 0);
_defineProperty(this, 'suiteStarted', void 0);
_defineProperty(this, 'suiteDone', void 0);
_defineProperty(this, 'suiteResults', void 0);
_defineProperty(this, 'suites', void 0);
_defineProperty(this, 'specResults', void 0);
_defineProperty(this, 'specDone', void 0);
_defineProperty(this, 'specs', void 0);
_defineProperty(this, 'specStarted', void 0);
const timer = options.timer || noopTimer;
let status = 'loaded';
this.started = false;
this.finished = false;
this.runDetails = {};
this.jasmineStarted = () => {
this.started = true;
status = 'started';
timer.start();
};
let executionTime;
function validateAfterAllExceptions({failedExpectations}) {
if (failedExpectations && failedExpectations.length > 0) {
throw failedExpectations[0];
}
}
this.jasmineDone = function (runDetails) {
validateAfterAllExceptions(runDetails);
this.finished = true;
this.runDetails = runDetails;
executionTime = timer.elapsed();
status = 'done';
};
this.status = function () {
return status;
};
const suites = [];
const suites_hash = {};
this.specStarted = function () {};
this.suiteStarted = function (result) {
suites_hash[result.id] = result;
};
this.suiteDone = function (result) {
storeSuite(result);
};
this.suiteResults = function (index, length) {
return suites.slice(index, index + length);
};
function storeSuite(result) {
suites.push(result);
suites_hash[result.id] = result;
}
this.suites = function () {
return suites_hash;
};
const specs = [];
this.specDone = function (result) {
specs.push(result);
};
this.specResults = function (index, length) {
return specs.slice(index, index + length);
};
this.specs = function () {
return specs;
};
this.executionTime = function () {
return executionTime;
};
}
}
exports.default = JsApiReporter;

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { Reporter, RunDetails } from '../types';
import type { SpecResult } from './Spec';
import type { SuiteResult } from './Suite';
export default class ReportDispatcher implements Reporter {
addReporter: (reporter: Reporter) => void;
provideFallbackReporter: (reporter: Reporter) => void;
clearReporters: () => void;
jasmineDone: (runDetails: RunDetails) => void;
jasmineStarted: (runDetails: RunDetails) => void;
specDone: (result: SpecResult) => void;
specStarted: (spec: SpecResult) => void;
suiteDone: (result: SuiteResult) => void;
suiteStarted: (result: SuiteResult) => void;
constructor(methods: Array<keyof Reporter>);
}

View File

@@ -0,0 +1,127 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// This file is a heavily modified fork of Jasmine. Original license:
/*
Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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.
*/
/* eslint-disable local/prefer-spread-eventually, local/prefer-rest-params-eventually */
class ReportDispatcher {
// @ts-expect-error
// @ts-expect-error
// @ts-expect-error
// @ts-expect-error
// @ts-expect-error
// @ts-expect-error
constructor(methods) {
_defineProperty(this, 'addReporter', void 0);
_defineProperty(this, 'provideFallbackReporter', void 0);
_defineProperty(this, 'clearReporters', void 0);
_defineProperty(this, 'jasmineDone', void 0);
_defineProperty(this, 'jasmineStarted', void 0);
_defineProperty(this, 'specDone', void 0);
_defineProperty(this, 'specStarted', void 0);
_defineProperty(this, 'suiteDone', void 0);
_defineProperty(this, 'suiteStarted', void 0);
const dispatchedMethods = methods || [];
for (let i = 0; i < dispatchedMethods.length; i++) {
const method = dispatchedMethods[i];
this[method] = (function (m) {
return function () {
dispatch(m, arguments);
};
})(method);
}
let reporters = [];
let fallbackReporter = null;
this.addReporter = function (reporter) {
reporters.push(reporter);
};
this.provideFallbackReporter = function (reporter) {
fallbackReporter = reporter;
};
this.clearReporters = function () {
reporters = [];
};
return this;
function dispatch(method, args) {
if (reporters.length === 0 && fallbackReporter !== null) {
reporters.push(fallbackReporter);
}
for (let i = 0; i < reporters.length; i++) {
const reporter = reporters[i];
if (reporter[method]) {
// @ts-expect-error
reporter[method].apply(reporter, args);
}
}
}
}
}
exports.default = ReportDispatcher;

View File

@@ -0,0 +1,81 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { FailedAssertion, Milliseconds, Status } from '@jest/test-result';
import type { Config } from '@jest/types';
import ExpectationFailed from '../ExpectationFailed';
import expectationResultFactory, { Options as ExpectationResultFactoryOptions } from '../expectationResultFactory';
import type { QueueableFn, default as queueRunner } from '../queueRunner';
import type { AssertionErrorWithStack } from '../types';
export declare type Attributes = {
id: string;
resultCallback: (result: Spec['result']) => void;
description: string;
throwOnExpectationFailure: unknown;
getTestPath: () => Config.Path;
queueableFn: QueueableFn;
beforeAndAfterFns: () => {
befores: Array<QueueableFn>;
afters: Array<QueueableFn>;
};
userContext: () => unknown;
onStart: (context: Spec) => void;
getSpecName: (spec: Spec) => string;
queueRunnerFactory: typeof queueRunner;
};
export declare type SpecResult = {
id: string;
description: string;
fullName: string;
duration?: Milliseconds;
failedExpectations: Array<FailedAssertion>;
testPath: Config.Path;
passedExpectations: Array<ReturnType<typeof expectationResultFactory>>;
pendingReason: string;
status: Status;
__callsite?: {
getColumnNumber: () => number;
getLineNumber: () => number;
};
};
export default class Spec {
id: string;
description: string;
resultCallback: (result: SpecResult) => void;
queueableFn: QueueableFn;
beforeAndAfterFns: () => {
befores: Array<QueueableFn>;
afters: Array<QueueableFn>;
};
userContext: () => unknown;
onStart: (spec: Spec) => void;
getSpecName: (spec: Spec) => string;
queueRunnerFactory: typeof queueRunner;
throwOnExpectationFailure: boolean;
initError: Error;
result: SpecResult;
disabled?: boolean;
currentRun?: ReturnType<typeof queueRunner>;
markedTodo?: boolean;
markedPending?: boolean;
expand?: boolean;
static pendingSpecExceptionMessage: string;
static isPendingSpecException(e: Error): boolean;
constructor(attrs: Attributes);
addExpectationResult(passed: boolean, data: ExpectationResultFactoryOptions, isError?: boolean): void;
execute(onComplete?: () => void, enabled?: boolean): void;
cancel(): void;
onException(error: ExpectationFailed | AssertionErrorWithStack): void;
disable(): void;
pend(message?: string): void;
todo(): void;
getResult(): SpecResult;
status(enabled?: boolean): "todo" | "passed" | "failed" | "pending" | "disabled";
isExecutable(): boolean;
getFullName(): string;
isAssertionError(error: Error): boolean;
}

View File

@@ -0,0 +1,298 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var _assert = require('assert');
var _ExpectationFailed = _interopRequireDefault(
require('../ExpectationFailed')
);
var _assertionErrorMessage = _interopRequireDefault(
require('../assertionErrorMessage')
);
var _expectationResultFactory = _interopRequireDefault(
require('../expectationResultFactory')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class Spec {
static isPendingSpecException(e) {
return !!(
e &&
e.toString &&
e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1
);
}
constructor(attrs) {
_defineProperty(this, 'id', void 0);
_defineProperty(this, 'description', void 0);
_defineProperty(this, 'resultCallback', void 0);
_defineProperty(this, 'queueableFn', void 0);
_defineProperty(this, 'beforeAndAfterFns', void 0);
_defineProperty(this, 'userContext', void 0);
_defineProperty(this, 'onStart', void 0);
_defineProperty(this, 'getSpecName', void 0);
_defineProperty(this, 'queueRunnerFactory', void 0);
_defineProperty(this, 'throwOnExpectationFailure', void 0);
_defineProperty(this, 'initError', void 0);
_defineProperty(this, 'result', void 0);
_defineProperty(this, 'disabled', void 0);
_defineProperty(this, 'currentRun', void 0);
_defineProperty(this, 'markedTodo', void 0);
_defineProperty(this, 'markedPending', void 0);
_defineProperty(this, 'expand', void 0);
this.resultCallback = attrs.resultCallback || function () {};
this.id = attrs.id;
this.description = attrs.description || '';
this.queueableFn = attrs.queueableFn;
this.beforeAndAfterFns =
attrs.beforeAndAfterFns ||
function () {
return {
befores: [],
afters: []
};
};
this.userContext =
attrs.userContext ||
function () {
return {};
};
this.onStart = attrs.onStart || function () {};
this.getSpecName =
attrs.getSpecName ||
function () {
return '';
};
this.queueRunnerFactory = attrs.queueRunnerFactory || function () {};
this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure;
this.initError = new Error();
this.initError.name = ''; // Without this line v8 stores references to all closures
// in the stack in the Error object. This line stringifies the stack
// property to allow garbage-collecting objects on the stack
// https://crbug.com/v8/7142
this.initError.stack = this.initError.stack;
this.queueableFn.initError = this.initError; // @ts-expect-error
this.result = {
id: this.id,
description: this.description,
fullName: this.getFullName(),
failedExpectations: [],
passedExpectations: [],
pendingReason: '',
testPath: attrs.getTestPath()
};
}
addExpectationResult(passed, data, isError) {
const expectationResult = (0, _expectationResultFactory.default)(
data,
this.initError
);
if (passed) {
this.result.passedExpectations.push(expectationResult);
} else {
this.result.failedExpectations.push(expectationResult);
if (this.throwOnExpectationFailure && !isError) {
throw new _ExpectationFailed.default();
}
}
}
execute(onComplete, enabled) {
const self = this;
this.onStart(this);
if (
!this.isExecutable() ||
this.markedPending ||
this.markedTodo ||
enabled === false
) {
complete(enabled);
return;
}
const fns = this.beforeAndAfterFns();
const allFns = fns.befores.concat(this.queueableFn).concat(fns.afters);
this.currentRun = this.queueRunnerFactory({
queueableFns: allFns,
onException() {
// @ts-expect-error
self.onException.apply(self, arguments);
},
userContext: this.userContext(),
setTimeout,
clearTimeout,
fail: () => {}
});
this.currentRun.then(() => complete(true));
function complete(enabledAgain) {
self.result.status = self.status(enabledAgain);
self.resultCallback(self.result);
if (onComplete) {
onComplete();
}
}
}
cancel() {
if (this.currentRun) {
this.currentRun.cancel();
}
}
onException(error) {
if (Spec.isPendingSpecException(error)) {
this.pend(extractCustomPendingMessage(error));
return;
}
if (error instanceof _ExpectationFailed.default) {
return;
}
this.addExpectationResult(
false,
{
matcherName: '',
passed: false,
expected: '',
actual: '',
error: this.isAssertionError(error)
? (0, _assertionErrorMessage.default)(error, {
expand: this.expand
})
: error
},
true
);
}
disable() {
this.disabled = true;
}
pend(message) {
this.markedPending = true;
if (message) {
this.result.pendingReason = message;
}
}
todo() {
this.markedTodo = true;
}
getResult() {
this.result.status = this.status();
return this.result;
}
status(enabled) {
if (this.disabled || enabled === false) {
return 'disabled';
}
if (this.markedTodo) {
return 'todo';
}
if (this.markedPending) {
return 'pending';
}
if (this.result.failedExpectations.length > 0) {
return 'failed';
} else {
return 'passed';
}
}
isExecutable() {
return !this.disabled;
}
getFullName() {
return this.getSpecName(this);
}
isAssertionError(error) {
return (
error instanceof _assert.AssertionError ||
(error && error.name === _assert.AssertionError.name)
);
}
}
exports.default = Spec;
_defineProperty(Spec, 'pendingSpecExceptionMessage', void 0);
Spec.pendingSpecExceptionMessage = '=> marked Pending';
const extractCustomPendingMessage = function (e) {
const fullMessage = e.toString();
const boilerplateStart = fullMessage.indexOf(
Spec.pendingSpecExceptionMessage
);
const boilerplateEnd =
boilerplateStart + Spec.pendingSpecExceptionMessage.length;
return fullMessage.substr(boilerplateEnd);
};

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
export default class SpyStrategy {
identity: () => string;
exec: (...args: Array<any>) => unknown;
callThrough: () => unknown;
returnValue: (value: unknown) => unknown;
returnValues: () => unknown;
throwError: (something: string | Error) => unknown;
callFake: (fn: Function) => unknown;
stub: (fn: Function) => unknown;
constructor({ name, fn, getSpy, }?: {
name?: string;
fn?: Function;
getSpy?: () => unknown;
});
}

View File

@@ -0,0 +1,143 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// This file is a heavily modified fork of Jasmine. Original license:
/*
Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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.
*/
/* eslint-disable local/ban-types-eventually, local/prefer-rest-params-eventually */
class SpyStrategy {
constructor({
name = 'unknown',
fn = function () {},
getSpy = function () {}
} = {}) {
_defineProperty(this, 'identity', void 0);
_defineProperty(this, 'exec', void 0);
_defineProperty(this, 'callThrough', void 0);
_defineProperty(this, 'returnValue', void 0);
_defineProperty(this, 'returnValues', void 0);
_defineProperty(this, 'throwError', void 0);
_defineProperty(this, 'callFake', void 0);
_defineProperty(this, 'stub', void 0);
const identity = name;
const originalFn = fn;
let plan = function () {};
this.identity = function () {
return identity;
};
this.exec = function () {
return plan.apply(this, arguments);
};
this.callThrough = function () {
plan = originalFn;
return getSpy();
};
this.returnValue = function (value) {
plan = function () {
return value;
};
return getSpy();
};
this.returnValues = function () {
const values = Array.prototype.slice.call(arguments);
plan = function () {
return values.shift();
};
return getSpy();
};
this.throwError = function (something) {
const error =
something instanceof Error ? something : new Error(something);
plan = function () {
throw error;
};
return getSpy();
};
this.callFake = function (fn) {
if (typeof fn !== 'function') {
throw new Error(
'Argument passed to callFake should be a function, got ' + fn
);
}
plan = fn;
return getSpy();
};
this.stub = function (_fn) {
plan = function () {};
return getSpy();
};
}
}
exports.default = SpyStrategy;

View File

@@ -0,0 +1,61 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { Config } from '@jest/types';
import expectationResultFactory from '../expectationResultFactory';
import type { QueueableFn } from '../queueRunner';
import type Spec from './Spec';
export declare type SuiteResult = {
id: string;
description: string;
fullName: string;
failedExpectations: Array<ReturnType<typeof expectationResultFactory>>;
testPath: Config.Path;
status?: string;
};
export declare type Attributes = {
id: string;
parentSuite?: Suite;
description: string;
throwOnExpectationFailure?: boolean;
getTestPath: () => Config.Path;
};
export default class Suite {
id: string;
parentSuite?: Suite;
description: string;
throwOnExpectationFailure: boolean;
beforeFns: Array<QueueableFn>;
afterFns: Array<QueueableFn>;
beforeAllFns: Array<QueueableFn>;
afterAllFns: Array<QueueableFn>;
disabled: boolean;
children: Array<Suite | Spec>;
result: SuiteResult;
sharedContext?: object;
markedPending: boolean;
markedTodo: boolean;
isFocused: boolean;
constructor(attrs: Attributes);
getFullName(): string;
disable(): void;
pend(_message?: string): void;
beforeEach(fn: QueueableFn): void;
beforeAll(fn: QueueableFn): void;
afterEach(fn: QueueableFn): void;
afterAll(fn: QueueableFn): void;
addChild(child: Suite | Spec): void;
status(): "failed" | "pending" | "disabled" | "finished";
isExecutable(): boolean;
canBeReentered(): boolean;
getResult(): SuiteResult;
sharedUserContext(): object;
clonedSharedUserContext(): object;
onException(...args: Parameters<Spec['onException']>): void;
addExpectationResult(...args: Parameters<Spec['addExpectationResult']>): void;
execute(..._args: Array<any>): void;
}

View File

@@ -0,0 +1,235 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var _jestUtil = require('jest-util');
var _ExpectationFailed = _interopRequireDefault(
require('../ExpectationFailed')
);
var _expectationResultFactory = _interopRequireDefault(
require('../expectationResultFactory')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class Suite {
constructor(attrs) {
_defineProperty(this, 'id', void 0);
_defineProperty(this, 'parentSuite', void 0);
_defineProperty(this, 'description', void 0);
_defineProperty(this, 'throwOnExpectationFailure', void 0);
_defineProperty(this, 'beforeFns', void 0);
_defineProperty(this, 'afterFns', void 0);
_defineProperty(this, 'beforeAllFns', void 0);
_defineProperty(this, 'afterAllFns', void 0);
_defineProperty(this, 'disabled', void 0);
_defineProperty(this, 'children', void 0);
_defineProperty(this, 'result', void 0);
_defineProperty(this, 'sharedContext', void 0);
_defineProperty(this, 'markedPending', void 0);
_defineProperty(this, 'markedTodo', void 0);
_defineProperty(this, 'isFocused', void 0);
this.markedPending = false;
this.markedTodo = false;
this.isFocused = false;
this.id = attrs.id;
this.parentSuite = attrs.parentSuite;
this.description = (0, _jestUtil.convertDescriptorToString)(
attrs.description
);
this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure;
this.beforeFns = [];
this.afterFns = [];
this.beforeAllFns = [];
this.afterAllFns = [];
this.disabled = false;
this.children = [];
this.result = {
id: this.id,
description: this.description,
fullName: this.getFullName(),
failedExpectations: [],
testPath: attrs.getTestPath()
};
}
getFullName() {
const fullName = [];
for (
let parentSuite = this;
parentSuite;
parentSuite = parentSuite.parentSuite
) {
if (parentSuite.parentSuite) {
fullName.unshift(parentSuite.description);
}
}
return fullName.join(' ');
}
disable() {
this.disabled = true;
}
pend(_message) {
this.markedPending = true;
}
beforeEach(fn) {
this.beforeFns.unshift(fn);
}
beforeAll(fn) {
this.beforeAllFns.push(fn);
}
afterEach(fn) {
this.afterFns.unshift(fn);
}
afterAll(fn) {
this.afterAllFns.unshift(fn);
}
addChild(child) {
this.children.push(child);
}
status() {
if (this.disabled) {
return 'disabled';
}
if (this.markedPending) {
return 'pending';
}
if (this.result.failedExpectations.length > 0) {
return 'failed';
} else {
return 'finished';
}
}
isExecutable() {
return !this.disabled;
}
canBeReentered() {
return this.beforeAllFns.length === 0 && this.afterAllFns.length === 0;
}
getResult() {
this.result.status = this.status();
return this.result;
}
sharedUserContext() {
if (!this.sharedContext) {
this.sharedContext = {};
}
return this.sharedContext;
}
clonedSharedUserContext() {
return this.sharedUserContext();
}
onException(...args) {
if (args[0] instanceof _ExpectationFailed.default) {
return;
}
if (isAfterAll(this.children)) {
const data = {
matcherName: '',
passed: false,
expected: '',
actual: '',
error: arguments[0]
};
this.result.failedExpectations.push(
(0, _expectationResultFactory.default)(data)
);
} else {
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
child.onException.apply(child, args);
}
}
}
addExpectationResult(...args) {
if (isAfterAll(this.children) && isFailure(args)) {
const data = args[1];
this.result.failedExpectations.push(
(0, _expectationResultFactory.default)(data)
);
if (this.throwOnExpectationFailure) {
throw new _ExpectationFailed.default();
}
} else {
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
try {
child.addExpectationResult.apply(child, args);
} catch {
// keep going
}
}
}
}
execute(..._args) {}
}
exports.default = Suite;
function isAfterAll(children) {
return children && children[0] && children[0].result.status;
}
function isFailure(args) {
return !args[0];
}

View File

@@ -0,0 +1,14 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
export default class Timer {
start: () => void;
elapsed: () => number;
constructor(options?: {
now?: () => number;
});
}

View File

@@ -0,0 +1,79 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// This file is a heavily modified fork of Jasmine. Original license:
/*
Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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.
*/
const defaultNow = (function (Date) {
return function () {
return new Date().getTime();
};
})(Date);
class Timer {
constructor(options) {
_defineProperty(this, 'start', void 0);
_defineProperty(this, 'elapsed', void 0);
options = options || {};
const now = options.now || defaultNow;
let startTime;
this.start = function () {
startTime = now();
};
this.elapsed = function () {
return now() - startTime;
};
}
}
exports.default = Timer;

View File

@@ -0,0 +1,13 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { Spy } from '../types';
interface Fn extends Record<string, unknown> {
(): unknown;
}
declare function createSpy(name: string, originalFn: Fn): Spy;
export default createSpy;

View File

@@ -0,0 +1,88 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var _CallTracker = _interopRequireDefault(require('./CallTracker'));
var _SpyStrategy = _interopRequireDefault(require('./SpyStrategy'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// This file is a heavily modified fork of Jasmine. Original license:
/*
Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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.
*/
/* eslint-disable sort-keys, local/prefer-rest-params-eventually */
function createSpy(name, originalFn) {
const spyStrategy = new _SpyStrategy.default({
name,
fn: originalFn,
getSpy() {
return spy;
}
});
const callTracker = new _CallTracker.default();
const spy = function (...args) {
const callData = {
object: this,
args: Array.prototype.slice.apply(arguments)
};
callTracker.track(callData);
const returnValue = spyStrategy.exec.apply(this, args);
callData.returnValue = returnValue;
return returnValue;
};
for (const prop in originalFn) {
if (prop === 'and' || prop === 'calls') {
throw new Error(
"Jasmine spies would overwrite the 'and' and 'calls' properties " +
'on the object being spied upon'
);
}
spy[prop] = originalFn[prop];
}
spy.and = spyStrategy;
spy.calls = callTracker;
return spy;
}
var _default = createSpy;
exports.default = _default;

View File

@@ -0,0 +1,27 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { Jasmine, SpecDefinitionsFn } from '../types';
import JsApiReporter from './JsApiReporter';
export declare const create: (createOptions: Record<string, any>) => Jasmine;
export declare const _interface: (jasmine: Jasmine, env: any) => {
describe(description: string, specDefinitions: SpecDefinitionsFn): any;
xdescribe(description: string, specDefinitions: SpecDefinitionsFn): any;
fdescribe(description: string, specDefinitions: SpecDefinitionsFn): any;
it(): any;
xit(): any;
fit(): any;
beforeEach(): any;
afterEach(): any;
beforeAll(): any;
afterAll(): any;
pending(): any;
fail(): any;
spyOn(obj: Record<string, any>, methodName: string, accessType?: string | undefined): any;
jsApiReporter: JsApiReporter;
jasmine: Jasmine;
};

View File

@@ -0,0 +1,171 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.create = exports._interface = void 0;
var _Env = _interopRequireDefault(require('./Env'));
var _JsApiReporter = _interopRequireDefault(require('./JsApiReporter'));
var _ReportDispatcher = _interopRequireDefault(require('./ReportDispatcher'));
var _Spec = _interopRequireDefault(require('./Spec'));
var _Suite = _interopRequireDefault(require('./Suite'));
var _Timer = _interopRequireDefault(require('./Timer'));
var _createSpy = _interopRequireDefault(require('./createSpy'));
var _spyRegistry = _interopRequireDefault(require('./spyRegistry'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// This file is a heavily modified fork of Jasmine. Original license:
/*
Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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.
*/
/* eslint-disable sort-keys, local/prefer-spread-eventually, local/prefer-rest-params-eventually */
const create = function (createOptions) {
const j$ = {...createOptions};
j$._DEFAULT_TIMEOUT_INTERVAL = createOptions.testTimeout || 5000;
j$.getEnv = function () {
const env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env()); //jasmine. singletons in here (setTimeout blah blah).
return env;
};
j$.createSpy = _createSpy.default;
j$.Env = (0, _Env.default)(j$);
j$.JsApiReporter = _JsApiReporter.default;
j$.ReportDispatcher = _ReportDispatcher.default;
j$.Spec = _Spec.default;
j$.SpyRegistry = _spyRegistry.default;
j$.Suite = _Suite.default;
j$.Timer = _Timer.default;
j$.version = '2.5.2-light';
return j$;
}; // Interface is a reserved word in strict mode, so can't export it as ESM
exports.create = create;
const _interface = function (jasmine, env) {
const jasmineInterface = {
describe(description, specDefinitions) {
return env.describe(description, specDefinitions);
},
xdescribe(description, specDefinitions) {
return env.xdescribe(description, specDefinitions);
},
fdescribe(description, specDefinitions) {
return env.fdescribe(description, specDefinitions);
},
it() {
return env.it.apply(env, arguments);
},
xit() {
return env.xit.apply(env, arguments);
},
fit() {
return env.fit.apply(env, arguments);
},
beforeEach() {
if (typeof arguments[0] !== 'function') {
throw new Error(
'Invalid first argument. It must be a callback function.'
);
}
return env.beforeEach.apply(env, arguments);
},
afterEach() {
if (typeof arguments[0] !== 'function') {
throw new Error(
'Invalid first argument. It must be a callback function.'
);
}
return env.afterEach.apply(env, arguments);
},
beforeAll() {
if (typeof arguments[0] !== 'function') {
throw new Error(
'Invalid first argument. It must be a callback function.'
);
}
return env.beforeAll.apply(env, arguments);
},
afterAll() {
if (typeof arguments[0] !== 'function') {
throw new Error(
'Invalid first argument. It must be a callback function.'
);
}
return env.afterAll.apply(env, arguments);
},
pending() {
return env.pending.apply(env, arguments);
},
fail() {
return env.fail.apply(env, arguments);
},
spyOn(obj, methodName, accessType) {
return env.spyOn(obj, methodName, accessType);
},
jsApiReporter: new jasmine.JsApiReporter({
timer: new jasmine.Timer()
}),
jasmine
};
return jasmineInterface;
};
exports._interface = _interface;

View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { Spy } from '../types';
export default class SpyRegistry {
allowRespy: (allow: unknown) => void;
spyOn: (obj: Record<string, Spy>, methodName: string, accessType?: keyof PropertyDescriptor) => Spy;
clearSpies: () => void;
respy: unknown;
private _spyOnProperty;
constructor({ currentSpies, }?: {
currentSpies?: () => Array<Spy>;
});
}

View File

@@ -0,0 +1,222 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var _CallTracker = _interopRequireDefault(require('./CallTracker'));
var _SpyStrategy = _interopRequireDefault(require('./SpyStrategy'));
var _createSpy = _interopRequireDefault(require('./createSpy'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const formatErrorMsg = (domain, usage) => {
const usageDefinition = usage ? '\nUsage: ' + usage : '';
return msg => domain + ' : ' + msg + usageDefinition;
};
function isSpy(putativeSpy) {
if (!putativeSpy) {
return false;
}
return (
putativeSpy.and instanceof _SpyStrategy.default &&
putativeSpy.calls instanceof _CallTracker.default
);
}
const getErrorMsg = formatErrorMsg('<spyOn>', 'spyOn(<object>, <methodName>)');
class SpyRegistry {
constructor({currentSpies = () => []} = {}) {
_defineProperty(this, 'allowRespy', void 0);
_defineProperty(this, 'spyOn', void 0);
_defineProperty(this, 'clearSpies', void 0);
_defineProperty(this, 'respy', void 0);
_defineProperty(this, '_spyOnProperty', void 0);
this.allowRespy = function (allow) {
this.respy = allow;
};
this.spyOn = (obj, methodName, accessType) => {
if (accessType) {
return this._spyOnProperty(obj, methodName, accessType);
}
if (obj === void 0) {
throw new Error(
getErrorMsg(
'could not find an object to spy upon for ' + methodName + '()'
)
);
}
if (methodName === void 0) {
throw new Error(getErrorMsg('No method name supplied'));
}
if (obj[methodName] === void 0) {
throw new Error(getErrorMsg(methodName + '() method does not exist'));
}
if (obj[methodName] && isSpy(obj[methodName])) {
if (this.respy) {
return obj[methodName];
} else {
throw new Error(
getErrorMsg(methodName + ' has already been spied upon')
);
}
}
let descriptor;
try {
descriptor = Object.getOwnPropertyDescriptor(obj, methodName);
} catch {
// IE 8 doesn't support `definePropery` on non-DOM nodes
}
if (descriptor && !(descriptor.writable || descriptor.set)) {
throw new Error(
getErrorMsg(methodName + ' is not declared writable or has no setter')
);
}
const originalMethod = obj[methodName];
const spiedMethod = (0, _createSpy.default)(methodName, originalMethod);
let restoreStrategy;
if (Object.prototype.hasOwnProperty.call(obj, methodName)) {
restoreStrategy = function () {
obj[methodName] = originalMethod;
};
} else {
restoreStrategy = function () {
if (!delete obj[methodName]) {
obj[methodName] = originalMethod;
}
};
}
currentSpies().push({
restoreObjectToOriginalState: restoreStrategy
});
obj[methodName] = spiedMethod;
return spiedMethod;
};
this._spyOnProperty = function (obj, propertyName, accessType = 'get') {
if (!obj) {
throw new Error(
getErrorMsg(
'could not find an object to spy upon for ' + propertyName
)
);
}
if (!propertyName) {
throw new Error(getErrorMsg('No property name supplied'));
}
let descriptor;
try {
descriptor = Object.getOwnPropertyDescriptor(obj, propertyName);
} catch {
// IE 8 doesn't support `definePropery` on non-DOM nodes
}
if (!descriptor) {
throw new Error(getErrorMsg(propertyName + ' property does not exist'));
}
if (!descriptor.configurable) {
throw new Error(
getErrorMsg(propertyName + ' is not declared configurable')
);
}
if (!descriptor[accessType]) {
throw new Error(
getErrorMsg(
'Property ' +
propertyName +
' does not have access type ' +
accessType
)
);
}
if (obj[propertyName] && isSpy(obj[propertyName])) {
if (this.respy) {
return obj[propertyName];
} else {
throw new Error(
getErrorMsg(propertyName + ' has already been spied upon')
);
}
}
const originalDescriptor = descriptor;
const spiedProperty = (0, _createSpy.default)(
propertyName,
descriptor[accessType]
);
let restoreStrategy;
if (Object.prototype.hasOwnProperty.call(obj, propertyName)) {
restoreStrategy = function () {
Object.defineProperty(obj, propertyName, originalDescriptor);
};
} else {
restoreStrategy = function () {
delete obj[propertyName];
};
}
currentSpies().push({
restoreObjectToOriginalState: restoreStrategy
});
const spiedDescriptor = {...descriptor, [accessType]: spiedProperty};
Object.defineProperty(obj, propertyName, spiedDescriptor);
return spiedProperty;
};
this.clearSpies = function () {
const spies = currentSpies();
for (let i = spies.length - 1; i >= 0; i--) {
const spyEntry = spies[i];
spyEntry.restoreObjectToOriginalState();
}
};
}
}
exports.default = SpyRegistry;

View File

@@ -0,0 +1,8 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config, Global } from '@jest/types';
export default function jasmineAsyncInstall(globalConfig: Config.GlobalConfig, global: Global.Global): void;

View File

@@ -0,0 +1,259 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = jasmineAsyncInstall;
var _co = _interopRequireDefault(require('co'));
var _isGeneratorFn = _interopRequireDefault(require('is-generator-fn'));
var _throat = _interopRequireDefault(require('throat'));
var _isError = _interopRequireDefault(require('./isError'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
function isPromise(obj) {
return obj && typeof obj.then === 'function';
}
const doneFnNoop = () => {};
doneFnNoop.fail = () => {};
function promisifyLifeCycleFunction(originalFn, env) {
return function (fn, timeout) {
if (!fn) {
// @ts-expect-error: missing fn arg is handled by originalFn
return originalFn.call(env);
}
if (typeof fn !== 'function') {
// Pass non-functions to Jest, which throws a nice error.
return originalFn.call(env, fn, timeout);
}
const hasDoneCallback = fn.length > 0;
if (hasDoneCallback) {
// Give the function a name so it can be detected in call stacks, but
// otherwise Jasmine will handle it.
const asyncJestLifecycleWithCallback = function (...args) {
// @ts-expect-error: Support possible extra args at runtime
return fn.apply(this, args);
};
return originalFn.call(env, asyncJestLifecycleWithCallback, timeout);
}
const extraError = new Error(); // Without this line v8 stores references to all closures
// in the stack in the Error object. This line stringifies the stack
// property to allow garbage-collecting objects on the stack
// https://crbug.com/v8/7142
extraError.stack = extraError.stack; // We make *all* functions async and run `done` right away if they
// didn't return a promise.
const asyncJestLifecycle = function (done) {
const wrappedFn = (0, _isGeneratorFn.default)(fn)
? _co.default.wrap(fn)
: fn;
const returnValue = wrappedFn.call({}, doneFnNoop);
if (isPromise(returnValue)) {
returnValue.then(done.bind(null, null), error => {
const {isError: checkIsError, message} = (0, _isError.default)(error);
if (message) {
extraError.message = message;
}
done.fail(checkIsError ? error : extraError);
});
} else {
done();
}
};
return originalFn.call(env, asyncJestLifecycle, timeout);
};
} // Similar to promisifyLifeCycleFunction but throws an error
// when the return value is neither a Promise nor `undefined`
function promisifyIt(originalFn, env, jasmine) {
return function (specName, fn, timeout) {
if (!fn) {
// @ts-expect-error: missing fn arg is handled by originalFn
const spec = originalFn.call(env, specName);
spec.pend('not implemented');
return spec;
}
if (typeof fn !== 'function') {
// Pass non-functions to Jest, which throws a nice error.
return originalFn.call(env, specName, fn, timeout);
}
const hasDoneCallback = fn.length > 0;
if (hasDoneCallback) {
// Give the function a name so it can be detected in call stacks, but
// otherwise Jasmine will handle it.
const asyncJestTestWithCallback = function (...args) {
// @ts-expect-error: Support possible extra args at runtime
return fn.apply(this, args);
};
return originalFn.call(env, specName, asyncJestTestWithCallback, timeout);
}
const extraError = new Error(); // Without this line v8 stores references to all closures
// in the stack in the Error object. This line stringifies the stack
// property to allow garbage-collecting objects on the stack
// https://crbug.com/v8/7142
extraError.stack = extraError.stack;
const asyncJestTest = function (done) {
const wrappedFn = (0, _isGeneratorFn.default)(fn)
? _co.default.wrap(fn)
: fn;
const returnValue = wrappedFn.call({}, doneFnNoop);
if (isPromise(returnValue)) {
returnValue.then(done.bind(null, null), error => {
const {isError: checkIsError, message} = (0, _isError.default)(error);
if (message) {
extraError.message = message;
}
if (jasmine.Spec.isPendingSpecException(error)) {
env.pending(message);
done();
} else {
done.fail(checkIsError ? error : extraError);
}
});
} else if (returnValue === undefined) {
done();
} else {
done.fail(
new Error(
'Jest: `it` and `test` must return either a Promise or undefined.'
)
);
}
};
return originalFn.call(env, specName, asyncJestTest, timeout);
};
}
function makeConcurrent(originalFn, env, mutex) {
const concurrentFn = function (specName, fn, timeout) {
let promise = Promise.resolve();
const spec = originalFn.call(env, specName, () => promise, timeout);
if (env != null && !env.specFilter(spec)) {
return spec;
}
try {
promise = mutex(() => {
const promise = fn();
if (isPromise(promise)) {
return promise;
}
throw new Error(
`Jest: concurrent test "${spec.getFullName()}" must return a Promise.`
);
});
} catch (error) {
promise = Promise.reject(error);
} // Avoid triggering the uncaught promise rejection handler in case the test errors before
// being awaited on.
promise.catch(() => {});
return spec;
}; // each is binded after the function is made concurrent, so for now it is made noop
concurrentFn.each = () => () => {};
return concurrentFn;
}
function jasmineAsyncInstall(globalConfig, global) {
const jasmine = global.jasmine;
const mutex = (0, _throat.default)(globalConfig.maxConcurrency);
const env = jasmine.getEnv();
env.it = promisifyIt(env.it, env, jasmine);
env.fit = promisifyIt(env.fit, env, jasmine);
global.it.concurrent = (env => {
const concurrent = makeConcurrent(env.it, env, mutex);
concurrent.only = makeConcurrent(env.fit, env, mutex);
concurrent.skip = makeConcurrent(env.xit, env, mutex);
return concurrent;
})(env);
global.fit.concurrent = makeConcurrent(env.fit, env, mutex);
env.afterAll = promisifyLifeCycleFunction(env.afterAll, env);
env.afterEach = promisifyLifeCycleFunction(env.afterEach, env);
env.beforeAll = promisifyLifeCycleFunction(env.beforeAll, env);
env.beforeEach = promisifyLifeCycleFunction(env.beforeEach, env);
}

View File

@@ -0,0 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export default function jestExpect(config: {
expand: boolean;
}): void;

View File

@@ -0,0 +1,69 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = jestExpect;
var _expect = _interopRequireDefault(require('expect'));
var _jestSnapshot = require('jest-snapshot');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable local/prefer-spread-eventually */
function jestExpect(config) {
global.expect = _expect.default;
_expect.default.setState({
expand: config.expand
});
_expect.default.extend({
toMatchInlineSnapshot: _jestSnapshot.toMatchInlineSnapshot,
toMatchSnapshot: _jestSnapshot.toMatchSnapshot,
toThrowErrorMatchingInlineSnapshot:
_jestSnapshot.toThrowErrorMatchingInlineSnapshot,
toThrowErrorMatchingSnapshot: _jestSnapshot.toThrowErrorMatchingSnapshot
});
_expect.default.addSnapshotSerializer = _jestSnapshot.addSerializer;
const jasmine = global.jasmine;
jasmine.anything = _expect.default.anything;
jasmine.any = _expect.default.any;
jasmine.objectContaining = _expect.default.objectContaining;
jasmine.arrayContaining = _expect.default.arrayContaining;
jasmine.stringMatching = _expect.default.stringMatching;
jasmine.addMatchers = jasmineMatchersObject => {
const jestMatchersObject = Object.create(null);
Object.keys(jasmineMatchersObject).forEach(name => {
jestMatchersObject[name] = function (...args) {
// use "expect.extend" if you need to use equality testers (via this.equal)
const result = jasmineMatchersObject[name](null, null); // if there is no 'negativeCompare', both should be handled by `compare`
const negativeCompare = result.negativeCompare || result.compare;
return this.isNot
? negativeCompare.apply(
null, // @ts-expect-error
args
)
: result.compare.apply(
null, // @ts-expect-error
args
);
};
});
_expect.default.extend(jestMatchersObject);
};
}

View File

@@ -0,0 +1,7 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export default function pTimeout(promise: Promise<void>, ms: number, clearTimeout: typeof globalThis['clearTimeout'], setTimeout: typeof globalThis['setTimeout'], onTimeout: () => void): Promise<void>;

78
frontend/node_modules/jest-jasmine2/build/pTimeout.js generated vendored Normal file
View File

@@ -0,0 +1,78 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = pTimeout;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// A specialized version of `p-timeout` that does not touch globals.
// It does not throw on timeout.
function pTimeout(promise, ms, clearTimeout, setTimeout, onTimeout) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve(onTimeout()), ms);
promise.then(
val => {
clearTimeout(timer);
resolve(val);
},
err => {
clearTimeout(timer);
reject(err);
}
);
});
}

View File

@@ -0,0 +1,29 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare type Options = {
clearTimeout: typeof globalThis['clearTimeout'];
fail: (error: Error) => void;
onException: (error: Error) => void;
queueableFns: Array<QueueableFn>;
setTimeout: typeof globalThis['setTimeout'];
userContext: unknown;
};
export interface DoneFn {
(error?: any): void;
fail: (error: Error) => void;
}
export declare type QueueableFn = {
fn: (done: DoneFn) => void;
timeout?: () => number;
initError?: Error;
};
declare type PromiseCallback = (() => void | PromiseLike<void>) | undefined | null;
export default function queueRunner(options: Options): PromiseLike<void> & {
cancel: () => void;
catch: (onRejected?: PromiseCallback) => Promise<void>;
};
export {};

View File

@@ -0,0 +1,127 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = queueRunner;
var _jestUtil = require('jest-util');
var _PCancelable = _interopRequireDefault(require('./PCancelable'));
var _pTimeout = _interopRequireDefault(require('./pTimeout'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
function queueRunner(options) {
const token = new _PCancelable.default((onCancel, resolve) => {
onCancel(resolve);
});
const mapper = ({fn, timeout, initError = new Error()}) => {
let promise = new Promise(resolve => {
const next = function (...args) {
const err = args[0];
if (err) {
options.fail.apply(null, args);
}
resolve();
};
next.fail = function (...args) {
options.fail.apply(null, args);
resolve();
};
try {
fn.call(options.userContext, next);
} catch (e) {
options.onException(e);
resolve();
}
});
promise = Promise.race([promise, token]);
if (!timeout) {
return promise;
}
const timeoutMs = timeout();
return (0, _pTimeout.default)(
promise,
timeoutMs,
options.clearTimeout,
options.setTimeout,
() => {
initError.message =
'Timeout - Async callback was not invoked within the ' +
(0, _jestUtil.formatTime)(timeoutMs) +
' timeout specified by jest.setTimeout.';
initError.stack = initError.message + initError.stack;
options.onException(initError);
}
);
};
const result = options.queueableFns.reduce(
(promise, fn) => promise.then(() => mapper(fn)),
Promise.resolve()
);
return {
cancel: token.cancel.bind(token),
catch: result.catch.bind(result),
then: result.then.bind(result)
};
}

View File

@@ -0,0 +1,31 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import { TestResult } from '@jest/test-result';
import type { Config } from '@jest/types';
import type { SpecResult } from './jasmine/Spec';
import type { SuiteResult } from './jasmine/Suite';
import type { Reporter, RunDetails } from './types';
export default class Jasmine2Reporter implements Reporter {
private _testResults;
private _globalConfig;
private _config;
private _currentSuites;
private _resolve;
private _resultsPromise;
private _startTimes;
private _testPath;
constructor(globalConfig: Config.GlobalConfig, config: Config.ProjectConfig, testPath: Config.Path);
jasmineStarted(_runDetails: RunDetails): void;
specStarted(spec: SpecResult): void;
specDone(result: SpecResult): void;
suiteStarted(suite: SuiteResult): void;
suiteDone(_result: SuiteResult): void;
jasmineDone(_runDetails: RunDetails): void;
getResults(): Promise<TestResult>;
private _addMissingMessageToStack;
private _extractSpecResults;
}

250
frontend/node_modules/jest-jasmine2/build/reporter.js generated vendored Normal file
View File

@@ -0,0 +1,250 @@
'use strict';
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var _testResult = require('@jest/test-result');
var _jestMessageUtil = require('jest-message-util');
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var jestNow = global[Symbol.for('jest-native-now')] || global.Date.now;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class Jasmine2Reporter {
constructor(globalConfig, config, testPath) {
_defineProperty(this, '_testResults', void 0);
_defineProperty(this, '_globalConfig', void 0);
_defineProperty(this, '_config', void 0);
_defineProperty(this, '_currentSuites', void 0);
_defineProperty(this, '_resolve', void 0);
_defineProperty(this, '_resultsPromise', void 0);
_defineProperty(this, '_startTimes', void 0);
_defineProperty(this, '_testPath', void 0);
this._globalConfig = globalConfig;
this._config = config;
this._testPath = testPath;
this._testResults = [];
this._currentSuites = [];
this._resolve = null;
this._resultsPromise = new Promise(resolve => (this._resolve = resolve));
this._startTimes = new Map();
}
jasmineStarted(_runDetails) {}
specStarted(spec) {
this._startTimes.set(spec.id, jestNow());
}
specDone(result) {
this._testResults.push(
this._extractSpecResults(result, this._currentSuites.slice(0))
);
}
suiteStarted(suite) {
this._currentSuites.push(suite.description);
}
suiteDone(_result) {
this._currentSuites.pop();
}
jasmineDone(_runDetails) {
let numFailingTests = 0;
let numPassingTests = 0;
let numPendingTests = 0;
let numTodoTests = 0;
const testResults = this._testResults;
testResults.forEach(testResult => {
if (testResult.status === 'failed') {
numFailingTests++;
} else if (testResult.status === 'pending') {
numPendingTests++;
} else if (testResult.status === 'todo') {
numTodoTests++;
} else {
numPassingTests++;
}
});
const testResult = {
...(0, _testResult.createEmptyTestResult)(),
console: null,
failureMessage: (0, _jestMessageUtil.formatResultsErrors)(
testResults,
this._config,
this._globalConfig,
this._testPath
),
numFailingTests,
numPassingTests,
numPendingTests,
numTodoTests,
snapshot: {
added: 0,
fileDeleted: false,
matched: 0,
unchecked: 0,
unmatched: 0,
updated: 0
},
testFilePath: this._testPath,
testResults
};
this._resolve(testResult);
}
getResults() {
return this._resultsPromise;
}
_addMissingMessageToStack(stack, message) {
// Some errors (e.g. Angular injection error) don't prepend error.message
// to stack, instead the first line of the stack is just plain 'Error'
const ERROR_REGEX = /^Error:?\s*\n/;
if (stack && message && !stack.includes(message)) {
return message + stack.replace(ERROR_REGEX, '\n');
}
return stack;
}
_extractSpecResults(specResult, ancestorTitles) {
const start = this._startTimes.get(specResult.id);
const duration = start ? jestNow() - start : undefined;
const status =
specResult.status === 'disabled' ? 'pending' : specResult.status;
const location = specResult.__callsite
? {
column: specResult.__callsite.getColumnNumber(),
line: specResult.__callsite.getLineNumber()
}
: null;
const results = {
ancestorTitles,
duration,
failureDetails: [],
failureMessages: [],
fullName: specResult.fullName,
location,
numPassingAsserts: 0,
// Jasmine2 only returns an array of failed asserts.
status,
title: specResult.description
};
specResult.failedExpectations.forEach(failed => {
const message =
!failed.matcherName && typeof failed.stack === 'string'
? this._addMissingMessageToStack(failed.stack, failed.message)
: failed.message || '';
results.failureMessages.push(message);
results.failureDetails.push(failed);
});
return results;
}
}
exports.default = Jasmine2Reporter;

View File

@@ -0,0 +1,16 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import { SnapshotStateType } from 'jest-snapshot';
import type { Plugin } from 'pretty-format';
export declare type SetupOptions = {
config: Config.ProjectConfig;
globalConfig: Config.GlobalConfig;
localRequire: (moduleName: string) => Plugin;
testPath: Config.Path;
};
export default function setupJestGlobals({ config, globalConfig, localRequire, testPath, }: SetupOptions): Promise<SnapshotStateType>;

View File

@@ -0,0 +1,121 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = setupJestGlobals;
var _expect = require('expect');
var _jestSnapshot = require('jest-snapshot');
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Get suppressed errors form jest-matchers that weren't throw during
// test execution and add them to the test result, potentially failing
// a passing test.
const addSuppressedErrors = result => {
const {suppressedErrors} = (0, _expect.getState)();
(0, _expect.setState)({
suppressedErrors: []
});
if (suppressedErrors.length) {
result.status = 'failed';
result.failedExpectations = suppressedErrors.map(error => ({
actual: '',
// passing error for custom test reporters
error,
expected: '',
matcherName: '',
message: error.message,
passed: false,
stack: error.stack
}));
}
};
const addAssertionErrors = result => {
const assertionErrors = (0, _expect.extractExpectedAssertionsErrors)();
if (assertionErrors.length) {
const jasmineErrors = assertionErrors.map(({actual, error, expected}) => ({
actual,
expected,
message: error.stack,
passed: false
}));
result.status = 'failed';
result.failedExpectations = result.failedExpectations.concat(jasmineErrors);
}
};
const patchJasmine = () => {
global.jasmine.Spec = (realSpec => {
class Spec extends realSpec {
constructor(attr) {
const resultCallback = attr.resultCallback;
attr.resultCallback = function (result) {
addSuppressedErrors(result);
addAssertionErrors(result);
resultCallback.call(attr, result);
};
const onStart = attr.onStart;
attr.onStart = context => {
(0, _expect.setState)({
currentTestName: context.getFullName()
});
onStart && onStart.call(attr, context);
};
super(attr);
}
}
return Spec;
})(global.jasmine.Spec);
};
async function setupJestGlobals({
config,
globalConfig,
localRequire,
testPath
}) {
// Jest tests snapshotSerializers in order preceding built-in serializers.
// Therefore, add in reverse because the last added is the first tested.
config.snapshotSerializers
.concat()
.reverse()
.forEach(path => {
(0, _jestSnapshot.addSerializer)(localRequire(path));
});
patchJasmine();
const {expand, updateSnapshot} = globalConfig;
const {prettierPath, snapshotFormat} = config;
const snapshotResolver = await (0, _jestSnapshot.buildSnapshotResolver)(
config,
localRequire
);
const snapshotPath = snapshotResolver.resolveSnapshotPath(testPath);
const snapshotState = new _jestSnapshot.SnapshotState(snapshotPath, {
expand,
prettierPath,
snapshotFormat,
updateSnapshot
}); // @ts-expect-error: snapshotState is a jest extension of `expect`
(0, _expect.setState)({
snapshotState,
testPath
}); // Return it back to the outer scope (test runner outside the VM).
return snapshotState;
}

View File

@@ -0,0 +1,26 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type Suite from './jasmine/Suite';
declare type Options = {
nodeComplete: (suite: TreeNode) => void;
nodeStart: (suite: TreeNode) => void;
queueRunnerFactory: any;
runnableIds: Array<string>;
tree: TreeNode;
};
export declare type TreeNode = {
afterAllFns: Array<unknown>;
beforeAllFns: Array<unknown>;
disabled?: boolean;
execute: (onComplete: () => void, enabled: boolean) => void;
id: string;
onException: (error: Error) => void;
sharedUserContext: () => unknown;
children?: Array<TreeNode>;
} & Pick<Suite, 'getResult' | 'parentSuite' | 'result' | 'markedPending'>;
export default function treeProcessor(options: Options): void;
export {};

View File

@@ -0,0 +1,82 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = treeProcessor;
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function treeProcessor(options) {
const {nodeComplete, nodeStart, queueRunnerFactory, runnableIds, tree} =
options;
function isEnabled(node, parentEnabled) {
return parentEnabled || runnableIds.indexOf(node.id) !== -1;
}
function getNodeHandler(node, parentEnabled) {
const enabled = isEnabled(node, parentEnabled);
return node.children
? getNodeWithChildrenHandler(node, enabled)
: getNodeWithoutChildrenHandler(node, enabled);
}
function getNodeWithoutChildrenHandler(node, enabled) {
return function fn(done = () => {}) {
node.execute(done, enabled);
};
}
function getNodeWithChildrenHandler(node, enabled) {
return async function fn(done = () => {}) {
nodeStart(node);
await queueRunnerFactory({
onException: error => node.onException(error),
queueableFns: wrapChildren(node, enabled),
userContext: node.sharedUserContext()
});
nodeComplete(node);
done();
};
}
function hasNoEnabledTest(node) {
var _node$children$every, _node$children;
return (
node.disabled ||
node.markedPending ||
((_node$children$every =
(_node$children = node.children) === null || _node$children === void 0
? void 0
: _node$children.every(hasNoEnabledTest)) !== null &&
_node$children$every !== void 0
? _node$children$every
: false)
);
}
function wrapChildren(node, enabled) {
if (!node.children) {
throw new Error('`node.children` is not defined.');
}
const children = node.children.map(child => ({
fn: getNodeHandler(child, enabled)
}));
if (hasNoEnabledTest(node)) {
return children;
}
return node.beforeAllFns.concat(children).concat(node.afterAllFns);
}
const treeHandler = getNodeHandler(tree, false);
return treeHandler();
}

82
frontend/node_modules/jest-jasmine2/build/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,82 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="node" />
import type { AssertionError } from 'assert';
import type { Config } from '@jest/types';
import expect = require('expect');
import type CallTracker from './jasmine/CallTracker';
import type Env from './jasmine/Env';
import type JsApiReporter from './jasmine/JsApiReporter';
import type ReportDispatcher from './jasmine/ReportDispatcher';
import type { default as Spec, SpecResult } from './jasmine/Spec';
import type SpyStrategy from './jasmine/SpyStrategy';
import type { default as Suite, SuiteResult } from './jasmine/Suite';
import type Timer from './jasmine/Timer';
import type createSpy from './jasmine/createSpy';
import type SpyRegistry from './jasmine/spyRegistry';
export declare type SpecDefinitionsFn = () => void;
export interface AssertionErrorWithStack extends AssertionError {
stack: string;
}
export declare type SyncExpectationResult = {
pass: boolean;
message: () => string;
};
export declare type AsyncExpectationResult = Promise<SyncExpectationResult>;
export declare type ExpectationResult = SyncExpectationResult | AsyncExpectationResult;
export declare type RawMatcherFn = (expected: unknown, actual: unknown, options?: unknown) => ExpectationResult;
export declare type RunDetails = {
totalSpecsDefined?: number;
failedExpectations?: SuiteResult['failedExpectations'];
};
export declare type Reporter = {
jasmineDone: (runDetails: RunDetails) => void;
jasmineStarted: (runDetails: RunDetails) => void;
specDone: (result: SpecResult) => void;
specStarted: (spec: SpecResult) => void;
suiteDone: (result: SuiteResult) => void;
suiteStarted: (result: SuiteResult) => void;
};
export interface Spy extends Record<string, any> {
(this: Record<string, unknown>, ...args: Array<any>): unknown;
and: SpyStrategy;
calls: CallTracker;
restoreObjectToOriginalState?: () => void;
}
declare type JasmineMatcher = {
(matchersUtil: unknown, context: unknown): JasmineMatcher;
compare: () => RawMatcherFn;
negativeCompare: () => RawMatcherFn;
};
export declare type JasmineMatchersObject = {
[id: string]: JasmineMatcher;
};
export declare type Jasmine = {
_DEFAULT_TIMEOUT_INTERVAL: number;
DEFAULT_TIMEOUT_INTERVAL: number;
currentEnv_: ReturnType<typeof Env>['prototype'];
getEnv: () => ReturnType<typeof Env>['prototype'];
createSpy: typeof createSpy;
Env: ReturnType<typeof Env>;
JsApiReporter: typeof JsApiReporter;
ReportDispatcher: typeof ReportDispatcher;
Spec: typeof Spec;
SpyRegistry: typeof SpyRegistry;
Suite: typeof Suite;
Timer: typeof Timer;
version: string;
testPath: Config.Path;
addMatchers: (matchers: JasmineMatchersObject) => void;
} & typeof expect & typeof globalThis;
declare global {
namespace NodeJS {
interface Global {
expect: typeof expect;
}
}
}
export {};

7
frontend/node_modules/jest-jasmine2/build/types.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
'use strict';
var _expect = _interopRequireDefault(require('expect'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Facebook, Inc. and its affiliates.
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,193 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="node" />
import type * as Global from './Global';
declare type Process = NodeJS.Process;
export declare type DoneFn = Global.DoneFn;
export declare type BlockFn = Global.BlockFn;
export declare type BlockName = Global.BlockName;
export declare type BlockMode = void | 'skip' | 'only' | 'todo';
export declare type TestMode = BlockMode;
export declare type TestName = Global.TestName;
export declare type TestFn = Global.TestFn;
export declare type HookFn = Global.HookFn;
export declare type AsyncFn = TestFn | HookFn;
export declare type SharedHookType = 'afterAll' | 'beforeAll';
export declare type HookType = SharedHookType | 'afterEach' | 'beforeEach';
export declare type TestContext = Global.TestContext;
export declare type Exception = any;
export declare type FormattedError = string;
export declare type Hook = {
asyncError: Error;
fn: HookFn;
type: HookType;
parent: DescribeBlock;
seenDone: boolean;
timeout: number | undefined | null;
};
export interface EventHandler {
(event: AsyncEvent, state: State): void | Promise<void>;
(event: SyncEvent, state: State): void;
}
export declare type Event = SyncEvent | AsyncEvent;
interface JestGlobals extends Global.TestFrameworkGlobals {
expect: unknown;
}
export declare type SyncEvent = {
asyncError: Error;
mode: BlockMode;
name: 'start_describe_definition';
blockName: BlockName;
} | {
mode: BlockMode;
name: 'finish_describe_definition';
blockName: BlockName;
} | {
asyncError: Error;
name: 'add_hook';
hookType: HookType;
fn: HookFn;
timeout: number | undefined;
} | {
asyncError: Error;
name: 'add_test';
testName: TestName;
fn: TestFn;
mode?: TestMode;
timeout: number | undefined;
} | {
name: 'error';
error: Exception;
};
export declare type AsyncEvent = {
name: 'setup';
testNamePattern?: string;
runtimeGlobals: JestGlobals;
parentProcess: Process;
} | {
name: 'include_test_location_in_result';
} | {
name: 'hook_start';
hook: Hook;
} | {
name: 'hook_success';
describeBlock?: DescribeBlock;
test?: TestEntry;
hook: Hook;
} | {
name: 'hook_failure';
error: string | Exception;
describeBlock?: DescribeBlock;
test?: TestEntry;
hook: Hook;
} | {
name: 'test_fn_start';
test: TestEntry;
} | {
name: 'test_fn_success';
test: TestEntry;
} | {
name: 'test_fn_failure';
error: Exception;
test: TestEntry;
} | {
name: 'test_retry';
test: TestEntry;
} | {
name: 'test_start';
test: TestEntry;
} | {
name: 'test_skip';
test: TestEntry;
} | {
name: 'test_todo';
test: TestEntry;
} | {
name: 'test_done';
test: TestEntry;
} | {
name: 'run_describe_start';
describeBlock: DescribeBlock;
} | {
name: 'run_describe_finish';
describeBlock: DescribeBlock;
} | {
name: 'run_start';
} | {
name: 'run_finish';
} | {
name: 'teardown';
};
export declare type MatcherResults = {
actual: unknown;
expected: unknown;
name: string;
pass: boolean;
};
export declare type TestStatus = 'skip' | 'done' | 'todo';
export declare type TestResult = {
duration?: number | null;
errors: Array<FormattedError>;
errorsDetailed: Array<MatcherResults | unknown>;
invocations: number;
status: TestStatus;
location?: {
column: number;
line: number;
} | null;
testPath: Array<TestName | BlockName>;
};
export declare type RunResult = {
unhandledErrors: Array<FormattedError>;
testResults: TestResults;
};
export declare type TestResults = Array<TestResult>;
export declare type GlobalErrorHandlers = {
uncaughtException: Array<(exception: Exception) => void>;
unhandledRejection: Array<(exception: Exception, promise: Promise<unknown>) => void>;
};
export declare type State = {
currentDescribeBlock: DescribeBlock;
currentlyRunningTest?: TestEntry | null;
expand?: boolean;
hasFocusedTests: boolean;
hasStarted: boolean;
originalGlobalErrorHandlers?: GlobalErrorHandlers;
parentProcess: Process | null;
rootDescribeBlock: DescribeBlock;
testNamePattern?: RegExp | null;
testTimeout: number;
unhandledErrors: Array<Exception>;
includeTestLocationInResult: boolean;
};
export declare type DescribeBlock = {
type: 'describeBlock';
children: Array<DescribeBlock | TestEntry>;
hooks: Array<Hook>;
mode: BlockMode;
name: BlockName;
parent?: DescribeBlock;
/** @deprecated Please get from `children` array instead */
tests: Array<TestEntry>;
};
export declare type TestError = Exception | [Exception | undefined, Exception];
export declare type TestEntry = {
type: 'test';
asyncError: Exception;
errors: Array<TestError>;
fn: TestFn;
invocations: number;
mode: TestMode;
name: TestName;
parent: DescribeBlock;
startedAt?: number | null;
duration?: number | null;
seenDone: boolean;
status?: TestStatus | null;
timeout?: number;
};
export {};

View File

@@ -0,0 +1 @@
'use strict';

View File

@@ -0,0 +1,462 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { ForegroundColor } from 'chalk';
import type { ReportOptions } from 'istanbul-reports';
import type { Arguments } from 'yargs';
declare type CoverageProvider = 'babel' | 'v8';
declare type Timers = 'real' | 'fake' | 'modern' | 'legacy';
export declare type Path = string;
export declare type Glob = string;
export declare type HasteConfig = {
/** Whether to hash files using SHA-1. */
computeSha1?: boolean;
/** The platform to use as the default, e.g. 'ios'. */
defaultPlatform?: string | null;
/** Force use of Node's `fs` APIs rather than shelling out to `find` */
forceNodeFilesystemAPI?: boolean;
/**
* Whether to follow symlinks when crawling for files.
* This options cannot be used in projects which use watchman.
* Projects with `watchman` set to true will error if this option is set to true.
*/
enableSymlinks?: boolean;
/** Path to a custom implementation of Haste. */
hasteImplModulePath?: string;
/** All platforms to target, e.g ['ios', 'android']. */
platforms?: Array<string>;
/** Whether to throw on error on module collision. */
throwOnModuleCollision?: boolean;
/** Custom HasteMap module */
hasteMapModulePath?: string;
};
export declare type CoverageReporterName = keyof ReportOptions;
export declare type CoverageReporterWithOptions<K = CoverageReporterName> = K extends CoverageReporterName ? ReportOptions[K] extends never ? never : [K, Partial<ReportOptions[K]>] : never;
export declare type CoverageReporters = Array<CoverageReporterName | CoverageReporterWithOptions>;
export declare type ReporterConfig = [string, Record<string, unknown>];
export declare type TransformerConfig = [string, Record<string, unknown>];
export interface ConfigGlobals {
[K: string]: unknown;
}
export interface PrettyFormatOptions {
}
export declare type DefaultOptions = {
automock: boolean;
bail: number;
cache: boolean;
cacheDirectory: Path;
changedFilesWithAncestor: boolean;
ci: boolean;
clearMocks: boolean;
collectCoverage: boolean;
coveragePathIgnorePatterns: Array<string>;
coverageReporters: Array<CoverageReporterName>;
coverageProvider: CoverageProvider;
detectLeaks: boolean;
detectOpenHandles: boolean;
errorOnDeprecated: boolean;
expand: boolean;
extensionsToTreatAsEsm: Array<Path>;
forceCoverageMatch: Array<Glob>;
globals: ConfigGlobals;
haste: HasteConfig;
injectGlobals: boolean;
listTests: boolean;
maxConcurrency: number;
maxWorkers: number | string;
moduleDirectories: Array<string>;
moduleFileExtensions: Array<string>;
moduleNameMapper: Record<string, string | Array<string>>;
modulePathIgnorePatterns: Array<string>;
noStackTrace: boolean;
notify: boolean;
notifyMode: NotifyMode;
passWithNoTests: boolean;
prettierPath: string;
resetMocks: boolean;
resetModules: boolean;
restoreMocks: boolean;
roots: Array<Path>;
runTestsByPath: boolean;
runner: string;
setupFiles: Array<Path>;
setupFilesAfterEnv: Array<Path>;
skipFilter: boolean;
slowTestThreshold: number;
snapshotSerializers: Array<Path>;
testEnvironment: string;
testEnvironmentOptions: Record<string, unknown>;
testFailureExitCode: string | number;
testLocationInResults: boolean;
testMatch: Array<Glob>;
testPathIgnorePatterns: Array<string>;
testRegex: Array<string>;
testRunner: string;
testSequencer: string;
testURL: string;
timers: Timers;
transformIgnorePatterns: Array<Glob>;
useStderr: boolean;
watch: boolean;
watchPathIgnorePatterns: Array<string>;
watchman: boolean;
};
export declare type DisplayName = {
name: string;
color: typeof ForegroundColor;
};
export declare type InitialOptionsWithRootDir = InitialOptions & Required<Pick<InitialOptions, 'rootDir'>>;
export declare type InitialProjectOptions = Pick<InitialOptions & {
cwd?: string;
}, keyof ProjectConfig>;
export declare type InitialOptions = Partial<{
automock: boolean;
bail: boolean | number;
cache: boolean;
cacheDirectory: Path;
ci: boolean;
clearMocks: boolean;
changedFilesWithAncestor: boolean;
changedSince: string;
collectCoverage: boolean;
collectCoverageFrom: Array<Glob>;
collectCoverageOnlyFrom: {
[key: string]: boolean;
};
coverageDirectory: string;
coveragePathIgnorePatterns: Array<string>;
coverageProvider: CoverageProvider;
coverageReporters: CoverageReporters;
coverageThreshold: CoverageThreshold;
dependencyExtractor: string;
detectLeaks: boolean;
detectOpenHandles: boolean;
displayName: string | DisplayName;
expand: boolean;
extensionsToTreatAsEsm: Array<Path>;
extraGlobals: Array<string>;
filter: Path;
findRelatedTests: boolean;
forceCoverageMatch: Array<Glob>;
forceExit: boolean;
json: boolean;
globals: ConfigGlobals;
globalSetup: string | null | undefined;
globalTeardown: string | null | undefined;
haste: HasteConfig;
injectGlobals: boolean;
reporters: Array<string | ReporterConfig>;
logHeapUsage: boolean;
lastCommit: boolean;
listTests: boolean;
maxConcurrency: number;
maxWorkers: number | string;
moduleDirectories: Array<string>;
moduleFileExtensions: Array<string>;
moduleLoader: Path;
moduleNameMapper: {
[key: string]: string | Array<string>;
};
modulePathIgnorePatterns: Array<string>;
modulePaths: Array<string>;
name: string;
noStackTrace: boolean;
notify: boolean;
notifyMode: string;
onlyChanged: boolean;
onlyFailures: boolean;
outputFile: Path;
passWithNoTests: boolean;
/**
* @deprecated Use `transformIgnorePatterns` options instead.
*/
preprocessorIgnorePatterns: Array<Glob>;
preset: string | null | undefined;
prettierPath: string | null | undefined;
projects: Array<Glob | InitialProjectOptions>;
replname: string | null | undefined;
resetMocks: boolean;
resetModules: boolean;
resolver: Path | null | undefined;
restoreMocks: boolean;
rootDir: Path;
roots: Array<Path>;
runner: string;
runTestsByPath: boolean;
/**
* @deprecated Use `transform` options instead.
*/
scriptPreprocessor: string;
setupFiles: Array<Path>;
/**
* @deprecated Use `setupFilesAfterEnv` options instead.
*/
setupTestFrameworkScriptFile: Path;
setupFilesAfterEnv: Array<Path>;
silent: boolean;
skipFilter: boolean;
skipNodeResolution: boolean;
slowTestThreshold: number;
snapshotResolver: Path;
snapshotSerializers: Array<Path>;
snapshotFormat: PrettyFormatOptions;
errorOnDeprecated: boolean;
testEnvironment: string;
testEnvironmentOptions: Record<string, unknown>;
testFailureExitCode: string | number;
testLocationInResults: boolean;
testMatch: Array<Glob>;
testNamePattern: string;
/**
* @deprecated Use `roots` options instead.
*/
testPathDirs: Array<Path>;
testPathIgnorePatterns: Array<string>;
testRegex: string | Array<string>;
testResultsProcessor: string;
testRunner: string;
testSequencer: string;
testURL: string;
testTimeout: number;
timers: Timers;
transform: {
[regex: string]: Path | TransformerConfig;
};
transformIgnorePatterns: Array<Glob>;
watchPathIgnorePatterns: Array<string>;
unmockedModulePathPatterns: Array<string>;
updateSnapshot: boolean;
useStderr: boolean;
verbose?: boolean;
watch: boolean;
watchAll: boolean;
watchman: boolean;
watchPlugins: Array<string | [string, Record<string, unknown>]>;
}>;
export declare type SnapshotUpdateState = 'all' | 'new' | 'none';
declare type NotifyMode = 'always' | 'failure' | 'success' | 'change' | 'success-change' | 'failure-change';
export declare type CoverageThresholdValue = {
branches?: number;
functions?: number;
lines?: number;
statements?: number;
};
declare type CoverageThreshold = {
[path: string]: CoverageThresholdValue;
global: CoverageThresholdValue;
};
export declare type GlobalConfig = {
bail: number;
changedSince?: string;
changedFilesWithAncestor: boolean;
collectCoverage: boolean;
collectCoverageFrom: Array<Glob>;
collectCoverageOnlyFrom?: {
[key: string]: boolean;
};
coverageDirectory: string;
coveragePathIgnorePatterns?: Array<string>;
coverageProvider: CoverageProvider;
coverageReporters: CoverageReporters;
coverageThreshold?: CoverageThreshold;
detectLeaks: boolean;
detectOpenHandles: boolean;
expand: boolean;
filter?: Path;
findRelatedTests: boolean;
forceExit: boolean;
json: boolean;
globalSetup?: string;
globalTeardown?: string;
lastCommit: boolean;
logHeapUsage: boolean;
listTests: boolean;
maxConcurrency: number;
maxWorkers: number;
noStackTrace: boolean;
nonFlagArgs: Array<string>;
noSCM?: boolean;
notify: boolean;
notifyMode: NotifyMode;
outputFile?: Path;
onlyChanged: boolean;
onlyFailures: boolean;
passWithNoTests: boolean;
projects: Array<Glob>;
replname?: string;
reporters?: Array<string | ReporterConfig>;
runTestsByPath: boolean;
rootDir: Path;
silent?: boolean;
skipFilter: boolean;
snapshotFormat: PrettyFormatOptions;
errorOnDeprecated: boolean;
testFailureExitCode: number;
testNamePattern?: string;
testPathPattern: string;
testResultsProcessor?: string;
testSequencer: string;
testTimeout?: number;
updateSnapshot: SnapshotUpdateState;
useStderr: boolean;
verbose?: boolean;
watch: boolean;
watchAll: boolean;
watchman: boolean;
watchPlugins?: Array<{
path: string;
config: Record<string, unknown>;
}> | null;
};
export declare type ProjectConfig = {
automock: boolean;
cache: boolean;
cacheDirectory: Path;
clearMocks: boolean;
coveragePathIgnorePatterns: Array<string>;
cwd: Path;
dependencyExtractor?: string;
detectLeaks: boolean;
detectOpenHandles: boolean;
displayName?: DisplayName;
errorOnDeprecated: boolean;
extensionsToTreatAsEsm: Array<Path>;
extraGlobals: Array<keyof typeof globalThis>;
filter?: Path;
forceCoverageMatch: Array<Glob>;
globalSetup?: string;
globalTeardown?: string;
globals: ConfigGlobals;
haste: HasteConfig;
injectGlobals: boolean;
moduleDirectories: Array<string>;
moduleFileExtensions: Array<string>;
moduleLoader?: Path;
moduleNameMapper: Array<[string, string]>;
modulePathIgnorePatterns: Array<string>;
modulePaths?: Array<string>;
name: string;
prettierPath: string;
resetMocks: boolean;
resetModules: boolean;
resolver?: Path;
restoreMocks: boolean;
rootDir: Path;
roots: Array<Path>;
runner: string;
setupFiles: Array<Path>;
setupFilesAfterEnv: Array<Path>;
skipFilter: boolean;
skipNodeResolution?: boolean;
slowTestThreshold: number;
snapshotResolver?: Path;
snapshotSerializers: Array<Path>;
snapshotFormat: PrettyFormatOptions;
testEnvironment: string;
testEnvironmentOptions: Record<string, unknown>;
testMatch: Array<Glob>;
testLocationInResults: boolean;
testPathIgnorePatterns: Array<string>;
testRegex: Array<string | RegExp>;
testRunner: string;
testURL: string;
timers: Timers;
transform: Array<[string, Path, Record<string, unknown>]>;
transformIgnorePatterns: Array<Glob>;
watchPathIgnorePatterns: Array<string>;
unmockedModulePathPatterns?: Array<string>;
};
export declare type Argv = Arguments<Partial<{
all: boolean;
automock: boolean;
bail: boolean | number;
cache: boolean;
cacheDirectory: string;
changedFilesWithAncestor: boolean;
changedSince: string;
ci: boolean;
clearCache: boolean;
clearMocks: boolean;
collectCoverage: boolean;
collectCoverageFrom: string;
collectCoverageOnlyFrom: Array<string>;
color: boolean;
colors: boolean;
config: string;
coverage: boolean;
coverageDirectory: string;
coveragePathIgnorePatterns: Array<string>;
coverageReporters: Array<string>;
coverageThreshold: string;
debug: boolean;
env: string;
expand: boolean;
findRelatedTests: boolean;
forceExit: boolean;
globals: string;
globalSetup: string | null | undefined;
globalTeardown: string | null | undefined;
haste: string;
init: boolean;
injectGlobals: boolean;
json: boolean;
lastCommit: boolean;
logHeapUsage: boolean;
maxWorkers: number | string;
moduleDirectories: Array<string>;
moduleFileExtensions: Array<string>;
moduleNameMapper: string;
modulePathIgnorePatterns: Array<string>;
modulePaths: Array<string>;
noStackTrace: boolean;
notify: boolean;
notifyMode: string;
onlyChanged: boolean;
onlyFailures: boolean;
outputFile: string;
preset: string | null | undefined;
projects: Array<string>;
prettierPath: string | null | undefined;
resetMocks: boolean;
resetModules: boolean;
resolver: string | null | undefined;
restoreMocks: boolean;
rootDir: string;
roots: Array<string>;
runInBand: boolean;
selectProjects: Array<string>;
setupFiles: Array<string>;
setupFilesAfterEnv: Array<string>;
showConfig: boolean;
silent: boolean;
snapshotSerializers: Array<string>;
testEnvironment: string;
testEnvironmentOptions: string;
testFailureExitCode: string | null | undefined;
testMatch: Array<string>;
testNamePattern: string;
testPathIgnorePatterns: Array<string>;
testPathPattern: Array<string>;
testRegex: string | Array<string>;
testResultsProcessor: string;
testRunner: string;
testSequencer: string;
testURL: string;
testTimeout: number | null | undefined;
timers: string;
transform: string;
transformIgnorePatterns: Array<string>;
unmockedModulePathPatterns: Array<string> | null | undefined;
updateSnapshot: boolean;
useStderr: boolean;
verbose: boolean;
version: boolean;
watch: boolean;
watchAll: boolean;
watchman: boolean;
watchPathIgnorePatterns: Array<string>;
}>>;
export {};

View File

@@ -0,0 +1 @@
'use strict';

View File

@@ -0,0 +1,95 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { CoverageMapData } from 'istanbul-lib-coverage';
export declare type ValidTestReturnValues = void | undefined;
declare type TestReturnValuePromise = Promise<unknown>;
declare type TestReturnValueGenerator = Generator<void, unknown, void>;
export declare type TestReturnValue = ValidTestReturnValues | TestReturnValuePromise;
export declare type TestContext = Record<string, unknown>;
export declare type DoneFn = (reason?: string | Error) => void;
export declare type DoneTakingTestFn = (this: TestContext | undefined, done: DoneFn) => ValidTestReturnValues;
export declare type PromiseReturningTestFn = (this: TestContext | undefined) => TestReturnValue;
export declare type GeneratorReturningTestFn = (this: TestContext | undefined) => TestReturnValueGenerator;
export declare type TestName = string;
export declare type TestFn = PromiseReturningTestFn | GeneratorReturningTestFn | DoneTakingTestFn;
export declare type ConcurrentTestFn = () => TestReturnValuePromise;
export declare type BlockFn = () => void;
export declare type BlockName = string;
export declare type HookFn = TestFn;
export declare type Col = unknown;
export declare type Row = ReadonlyArray<Col>;
export declare type Table = ReadonlyArray<Row>;
export declare type ArrayTable = Table | Row;
export declare type TemplateTable = TemplateStringsArray;
export declare type TemplateData = ReadonlyArray<unknown>;
export declare type EachTable = ArrayTable | TemplateTable;
export declare type TestCallback = BlockFn | TestFn | ConcurrentTestFn;
export declare type EachTestFn<EachCallback extends TestCallback> = (...args: ReadonlyArray<any>) => ReturnType<EachCallback>;
declare type Jasmine = {
_DEFAULT_TIMEOUT_INTERVAL?: number;
addMatchers: (matchers: Record<string, unknown>) => void;
};
declare type Each<EachCallback extends TestCallback> = ((table: EachTable, ...taggedTemplateData: TemplateData) => (name: BlockName | TestName, test: EachTestFn<EachCallback>, timeout?: number) => void) | (() => () => void);
export interface HookBase {
(fn: HookFn, timeout?: number): void;
}
export interface ItBase {
(testName: TestName, fn: TestFn, timeout?: number): void;
each: Each<TestFn>;
}
export interface It extends ItBase {
only: ItBase;
skip: ItBase;
todo: (testName: TestName) => void;
}
export interface ItConcurrentBase {
(testName: TestName, testFn: ConcurrentTestFn, timeout?: number): void;
each: Each<ConcurrentTestFn>;
}
export interface ItConcurrentExtended extends ItConcurrentBase {
only: ItConcurrentBase;
skip: ItConcurrentBase;
}
export interface ItConcurrent extends It {
concurrent: ItConcurrentExtended;
}
export interface DescribeBase {
(blockName: BlockName, blockFn: BlockFn): void;
each: Each<BlockFn>;
}
export interface Describe extends DescribeBase {
only: DescribeBase;
skip: DescribeBase;
}
export interface TestFrameworkGlobals {
it: ItConcurrent;
test: ItConcurrent;
fit: ItBase & {
concurrent?: ItConcurrentBase;
};
xit: ItBase;
xtest: ItBase;
describe: Describe;
xdescribe: DescribeBase;
fdescribe: DescribeBase;
beforeAll: HookBase;
beforeEach: HookBase;
afterEach: HookBase;
afterAll: HookBase;
}
export interface GlobalAdditions extends TestFrameworkGlobals {
__coverage__: CoverageMapData;
jasmine: Jasmine;
fail: () => void;
pending: () => void;
spyOn: () => void;
spyOnProperty: () => void;
}
export interface Global extends GlobalAdditions, Omit<typeof globalThis, keyof GlobalAdditions> {
[extras: string]: unknown;
}
export {};

View File

@@ -0,0 +1 @@
'use strict';

View File

@@ -0,0 +1,31 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare type Milliseconds = number;
declare type Status = 'passed' | 'failed' | 'skipped' | 'pending' | 'todo' | 'disabled';
declare type Callsite = {
column: number;
line: number;
};
export declare type AssertionResult = {
ancestorTitles: Array<string>;
duration?: Milliseconds | null;
failureDetails: Array<unknown>;
failureMessages: Array<string>;
fullName: string;
invocations?: number;
location?: Callsite | null;
numPassingAsserts: number;
status: Status;
title: string;
};
export declare type SerializableError = {
code?: unknown;
message: string;
stack: string | null | undefined;
type?: string;
};
export {};

View File

@@ -0,0 +1 @@
'use strict';

View File

@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare type TransformResult = {
code: string;
originalCode: string;
sourceMapPath: string | null;
};

View File

@@ -0,0 +1 @@
'use strict';

View File

@@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type * as Circus from './Circus';
import type * as Config from './Config';
import type * as Global from './Global';
import type * as TestResult from './TestResult';
import type * as TransformTypes from './Transform';
export type { Circus, Config, Global, TestResult, TransformTypes };

View File

@@ -0,0 +1 @@
'use strict';

View File

@@ -0,0 +1,37 @@
{
"name": "@jest/types",
"version": "27.5.1",
"repository": {
"type": "git",
"url": "https://github.com/facebook/jest.git",
"directory": "packages/jest-types"
},
"engines": {
"node": "^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@types/istanbul-lib-coverage": "^2.0.0",
"@types/istanbul-reports": "^3.0.0",
"@types/node": "*",
"@types/yargs": "^16.0.0",
"chalk": "^4.0.0"
},
"devDependencies": {
"@tsd/typescript": "~4.1.5",
"tsd-lite": "^0.5.1"
},
"publishConfig": {
"access": "public"
},
"gitHead": "67c1aa20c5fec31366d733e901fee2b981cb1850"
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
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,15 @@
# Installation
> `npm install --save @types/yargs`
# Summary
This package contains type definitions for yargs (https://github.com/chevex/yargs).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs/v16.
### Additional Details
* Last updated: Mon, 20 Nov 2023 23:36:24 GMT
* Dependencies: [@types/yargs-parser](https://npmjs.com/package/@types/yargs-parser)
# Credits
These definitions were written by [Martin Poelstra](https://github.com/poelstra), [Mizunashi Mana](https://github.com/mizunashi-mana), [Jeffery Grajkowski](https://github.com/pushplay), [Jimi (Dimitris) Charalampidis](https://github.com/JimiC), [Steffen Viken Valvåg](https://github.com/steffenvv), [Emily Marigold Klassen](https://github.com/forivall), [ExE Boss](https://github.com/ExE-Boss), and [Aankhen](https://github.com/Aankhen).

View File

@@ -0,0 +1,5 @@
import * as Parser from "yargs-parser";
export function applyExtends(config: Record<string, any>, cwd: string, mergeExtends: boolean): Record<string, any>;
export function hideBin(argv: string[]): string[];
export { Parser };

View File

@@ -0,0 +1,917 @@
// The following TSLint rules have been disabled:
// unified-signatures: Because there is useful information in the argument names of the overloaded signatures
// Convention:
// Use 'union types' when:
// - parameter types have similar signature type (i.e. 'string | ReadonlyArray<string>')
// - parameter names have the same semantic meaning (i.e. ['command', 'commands'] , ['key', 'keys'])
// An example for not using 'union types' is the declaration of 'env' where `prefix` and `enable` parameters
// have different semantics. On the other hand, in the declaration of 'usage', a `command: string` parameter
// has the same semantic meaning with declaring an overload method by using `commands: ReadonlyArray<string>`,
// thus it's preferred to use `command: string | ReadonlyArray<string>`
// Use parameterless declaration instead of declaring all parameters optional,
// when all parameters are optional and more than one
import { Configuration, DetailedArguments } from "yargs-parser";
declare namespace yargs {
type BuilderCallback<T, R> =
| ((args: Argv<T>) => PromiseLike<Argv<R>>)
| ((args: Argv<T>) => Argv<R>)
| ((args: Argv<T>) => void);
type ParserConfigurationOptions = Configuration & {
/** Sort commands alphabetically. Default is `false` */
"sort-commands": boolean;
};
/**
* The type parameter `T` is the expected shape of the parsed options.
* `Arguments<T>` is those options plus `_` and `$0`, and an indexer falling
* back to `unknown` for unknown options.
*
* For the return type / `argv` property, we create a mapped type over
* `Arguments<T>` to simplify the inferred type signature in client code.
*/
interface Argv<T = {}> {
(): { [key in keyof Arguments<T>]: Arguments<T>[key] };
(args: readonly string[], cwd?: string): Argv<T>;
/**
* Set key names as equivalent such that updates to a key will propagate to aliases and vice-versa.
*
* Optionally `.alias()` can take an object that maps keys to aliases.
* Each key of this object should be the canonical version of the option, and each value should be a string or an array of strings.
*/
// Aliases for previously declared options can inherit the types of those options.
alias<K1 extends keyof T, K2 extends string>(
shortName: K1,
longName: K2 | readonly K2[],
): Argv<T & { [key in K2]: T[K1] }>;
alias<K1 extends keyof T, K2 extends string>(
shortName: K2,
longName: K1 | readonly K1[],
): Argv<T & { [key in K2]: T[K1] }>;
alias(shortName: string | readonly string[], longName: string | readonly string[]): Argv<T>;
alias(aliases: { [shortName: string]: string | readonly string[] }): Argv<T>;
/**
* Get the arguments as a plain old object.
*
* Arguments without a corresponding flag show up in the `argv._` array.
*
* The script name or node command is available at `argv.$0` similarly to how `$0` works in bash or perl.
*
* If `yargs` is executed in an environment that embeds node and there's no script name (e.g. Electron or nw.js),
* it will ignore the first parameter since it expects it to be the script name. In order to override
* this behavior, use `.parse(process.argv.slice(1))` instead of .argv and the first parameter won't be ignored.
*/
argv: { [key in keyof Arguments<T>]: Arguments<T>[key] };
/**
* Tell the parser to interpret `key` as an array.
* If `.array('foo')` is set, `--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`.
* Also, if you use the option multiple times all the values will be flattened in one array so `--foo foo --foo bar` will be parsed as `['foo', 'bar']`
*
* When the option is used with a positional, use `--` to tell `yargs` to stop adding values to the array.
*/
array<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: ToArray<T[key]> }>;
array<K extends string>(
key: K | readonly K[],
): Argv<T & { [key in K]: Array<string | number> | undefined }>;
/**
* Interpret `key` as a boolean. If a non-flag option follows `key` in `process.argv`, that string won't get set as the value of `key`.
*
* `key` will default to `false`, unless a `default(key, undefined)` is explicitly set.
*
* If `key` is an array, interpret all the elements as booleans.
*/
boolean<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: boolean | undefined }>;
boolean<K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: boolean | undefined }>;
/**
* Check that certain conditions are met in the provided arguments.
* @param func Called with two arguments, the parsed `argv` hash and an array of options and their aliases.
* If `func` throws or returns a non-truthy value, show the thrown error, usage information, and exit.
* @param global Indicates whether `check()` should be enabled both at the top-level and for each sub-command.
*/
check(func: (argv: Arguments<T>, aliases: { [alias: string]: string }) => any, global?: boolean): Argv<T>;
/**
* Limit valid values for key to a predefined set of choices, given as an array or as an individual value.
* If this method is called multiple times, all enumerated values will be merged together.
* Choices are generally strings or numbers, and value matching is case-sensitive.
*
* Optionally `.choices()` can take an object that maps multiple keys to their choices.
*
* Choices can also be specified as choices in the object given to `option()`.
*/
choices<K extends keyof T, C extends readonly any[]>(
key: K,
values: C,
): Argv<Omit<T, K> & { [key in K]: C[number] | undefined }>;
choices<K extends string, C extends readonly any[]>(
key: K,
values: C,
): Argv<T & { [key in K]: C[number] | undefined }>;
choices<C extends { [key: string]: readonly any[] }>(
choices: C,
): Argv<Omit<T, keyof C> & { [key in keyof C]: C[key][number] | undefined }>;
/**
* Provide a synchronous function to coerce or transform the value(s) given on the command line for `key`.
*
* The coercion function should accept one argument, representing the parsed value from the command line, and should return a new value or throw an error.
* The returned value will be used as the value for `key` (or one of its aliases) in `argv`.
*
* If the function throws, the error will be treated as a validation failure, delegating to either a custom `.fail()` handler or printing the error message in the console.
*
* Coercion will be applied to a value after all other modifications, such as `.normalize()`.
*
* Optionally `.coerce()` can take an object that maps several keys to their respective coercion function.
*
* You can also map the same function to several keys at one time. Just pass an array of keys as the first argument to `.coerce()`.
*
* If you are using dot-notion or arrays, .e.g., `user.email` and `user.password`, coercion will be applied to the final object that has been parsed
*/
coerce<K extends keyof T, V>(
key: K | readonly K[],
func: (arg: any) => V,
): Argv<Omit<T, K> & { [key in K]: V | undefined }>;
coerce<K extends string, V>(
key: K | readonly K[],
func: (arg: any) => V,
): Argv<T & { [key in K]: V | undefined }>;
coerce<O extends { [key: string]: (arg: any) => any }>(
opts: O,
): Argv<Omit<T, keyof O> & { [key in keyof O]: ReturnType<O[key]> | undefined }>;
/**
* Define the commands exposed by your application.
* @param command Should be a string representing the command or an array of strings representing the command and its aliases.
* @param description Use to provide a description for each command your application accepts (the values stored in `argv._`).
* Set `description` to false to create a hidden command. Hidden commands don't show up in the help output and aren't available for completion.
* @param [builder] Object to give hints about the options that your command accepts.
* Can also be a function. This function is executed with a yargs instance, and can be used to provide advanced command specific help.
*
* Note that when `void` is returned, the handler `argv` object type will not include command-specific arguments.
* @param [handler] Function, which will be executed with the parsed `argv` object.
*/
command<U = T>(
command: string | readonly string[],
description: string,
builder?: BuilderCallback<T, U>,
handler?: (args: Arguments<U>) => void,
middlewares?: Array<MiddlewareFunction<U>>,
deprecated?: boolean | string,
): Argv<U>;
command<O extends { [key: string]: Options }>(
command: string | readonly string[],
description: string,
builder?: O,
handler?: (args: Arguments<InferredOptionTypes<O>>) => void,
middlewares?: Array<MiddlewareFunction<O>>,
deprecated?: boolean | string,
): Argv<T>;
command<U>(command: string | readonly string[], description: string, module: CommandModule<T, U>): Argv<U>;
command<U = T>(
command: string | readonly string[],
showInHelp: false,
builder?: BuilderCallback<T, U>,
handler?: (args: Arguments<U>) => void,
middlewares?: Array<MiddlewareFunction<U>>,
deprecated?: boolean | string,
): Argv<T>;
command<O extends { [key: string]: Options }>(
command: string | readonly string[],
showInHelp: false,
builder?: O,
handler?: (args: Arguments<InferredOptionTypes<O>>) => void,
): Argv<T>;
command<U>(command: string | readonly string[], showInHelp: false, module: CommandModule<T, U>): Argv<U>;
command<U>(module: CommandModule<T, U>): Argv<U>;
// Advanced API
/** Apply command modules from a directory relative to the module calling this method. */
commandDir(dir: string, opts?: RequireDirectoryOptions): Argv<T>;
/**
* Enable bash/zsh-completion shortcuts for commands and options.
*
* If invoked without parameters, `.completion()` will make completion the command to output the completion script.
*
* @param [cmd] When present in `argv._`, will result in the `.bashrc` or `.zshrc` completion script being outputted.
* To enable bash/zsh completions, concat the generated script to your `.bashrc` or `.bash_profile` (or `.zshrc` for zsh).
* @param [description] Provide a description in your usage instructions for the command that generates the completion scripts.
* @param [func] Rather than relying on yargs' default completion functionality, which shiver me timbers is pretty awesome, you can provide your own completion method.
*/
completion(): Argv<T>;
completion(cmd: string, func?: AsyncCompletionFunction): Argv<T>;
completion(cmd: string, func?: SyncCompletionFunction): Argv<T>;
completion(cmd: string, func?: PromiseCompletionFunction): Argv<T>;
completion(cmd: string, description?: string | false, func?: AsyncCompletionFunction): Argv<T>;
completion(cmd: string, description?: string | false, func?: SyncCompletionFunction): Argv<T>;
completion(cmd: string, description?: string | false, func?: PromiseCompletionFunction): Argv<T>;
/**
* Tells the parser that if the option specified by `key` is passed in, it should be interpreted as a path to a JSON config file.
* The file is loaded and parsed, and its properties are set as arguments.
* Because the file is loaded using Node's require(), the filename MUST end in `.json` to be interpreted correctly.
*
* If invoked without parameters, `.config()` will make --config the option to pass the JSON config file.
*
* @param [description] Provided to customize the config (`key`) option in the usage string.
* @param [explicitConfigurationObject] An explicit configuration `object`
*/
config(): Argv<T>;
config(
key: string | readonly string[],
description?: string,
parseFn?: (configPath: string) => object,
): Argv<T>;
config(key: string | readonly string[], parseFn: (configPath: string) => object): Argv<T>;
config(explicitConfigurationObject: object): Argv<T>;
/**
* Given the key `x` is set, the key `y` must not be set. `y` can either be a single string or an array of argument names that `x` conflicts with.
*
* Optionally `.conflicts()` can accept an object specifying multiple conflicting keys.
*/
conflicts(key: string, value: string | readonly string[]): Argv<T>;
conflicts(conflicts: { [key: string]: string | readonly string[] }): Argv<T>;
/**
* Interpret `key` as a boolean flag, but set its parsed value to the number of flag occurrences rather than `true` or `false`. Default value is thus `0`.
*/
count<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: number }>;
count<K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: number }>;
/**
* Set `argv[key]` to `value` if no option was specified in `process.argv`.
*
* Optionally `.default()` can take an object that maps keys to default values.
*
* The default value can be a `function` which returns a value. The name of the function will be used in the usage string.
*
* Optionally, `description` can also be provided and will take precedence over displaying the value in the usage instructions.
*/
default<K extends keyof T, V>(key: K, value: V, description?: string): Argv<Omit<T, K> & { [key in K]: V }>;
default<K extends string, V>(key: K, value: V, description?: string): Argv<T & { [key in K]: V }>;
default<D extends { [key: string]: any }>(defaults: D, description?: string): Argv<Omit<T, keyof D> & D>;
/**
* @deprecated since version 6.6.0
* Use '.demandCommand()' or '.demandOption()' instead
*/
demand<K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv<Defined<T, K>>;
demand<K extends string>(key: K | readonly K[], msg?: string | true): Argv<T & { [key in K]: unknown }>;
demand(key: string | readonly string[], required?: boolean): Argv<T>;
demand(positionals: number, msg: string): Argv<T>;
demand(positionals: number, required?: boolean): Argv<T>;
demand(positionals: number, max: number, msg?: string): Argv<T>;
/**
* @param key If is a string, show the usage information and exit if key wasn't specified in `process.argv`.
* If is an array, demand each element.
* @param msg If string is given, it will be printed when the argument is missing, instead of the standard error message.
* @param demand Controls whether the option is demanded; this is useful when using .options() to specify command line parameters.
*/
demandOption<K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv<Defined<T, K>>;
demandOption<K extends string>(
key: K | readonly K[],
msg?: string | true,
): Argv<T & { [key in K]: unknown }>;
demandOption(key: string | readonly string[], demand?: boolean): Argv<T>;
/**
* Demand in context of commands.
* You can demand a minimum and a maximum number a user can have within your program, as well as provide corresponding error messages if either of the demands is not met.
*/
demandCommand(): Argv<T>;
demandCommand(min: number, minMsg?: string): Argv<T>;
demandCommand(min: number, max?: number, minMsg?: string, maxMsg?: string): Argv<T>;
/**
* Shows a [deprecated] notice in front of the option
*/
deprecateOption(option: string, msg?: string): Argv<T>;
/**
* Describe a `key` for the generated usage information.
*
* Optionally `.describe()` can take an object that maps keys to descriptions.
*/
describe(key: string | readonly string[], description: string): Argv<T>;
describe(descriptions: { [key: string]: string }): Argv<T>;
/** Should yargs attempt to detect the os' locale? Defaults to `true`. */
detectLocale(detect: boolean): Argv<T>;
/**
* Tell yargs to parse environment variables matching the given prefix and apply them to argv as though they were command line arguments.
*
* Use the "__" separator in the environment variable to indicate nested options. (e.g. prefix_nested__foo => nested.foo)
*
* If this method is called with no argument or with an empty string or with true, then all env vars will be applied to argv.
*
* Program arguments are defined in this order of precedence:
* 1. Command line args
* 2. Env vars
* 3. Config file/objects
* 4. Configured defaults
*
* Env var parsing is disabled by default, but you can also explicitly disable it by calling `.env(false)`, e.g. if you need to undo previous configuration.
*/
env(): Argv<T>;
env(prefix: string): Argv<T>;
env(enable: boolean): Argv<T>;
/** A message to print at the end of the usage instructions */
epilog(msg: string): Argv<T>;
/** A message to print at the end of the usage instructions */
epilogue(msg: string): Argv<T>;
/**
* Give some example invocations of your program.
* Inside `cmd`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl.
* Examples will be printed out as part of the help message.
*/
example(command: string, description: string): Argv<T>;
example(command: ReadonlyArray<[string, string?]>): Argv<T>;
/** Manually indicate that the program should exit, and provide context about why we wanted to exit. Follows the behavior set by `.exitProcess().` */
exit(code: number, err: Error): void;
/**
* By default, yargs exits the process when the user passes a help flag, the user uses the `.version` functionality, validation fails, or the command handler fails.
* Calling `.exitProcess(false)` disables this behavior, enabling further actions after yargs have been validated.
*/
exitProcess(enabled: boolean): Argv<T>;
/**
* Method to execute when a failure occurs, rather than printing the failure message.
* @param func Is called with the failure message that would have been printed, the Error instance originally thrown and yargs state when the failure occurred.
*/
fail(func: (msg: string, err: Error, yargs: Argv<T>) => any): Argv<T>;
/**
* Allows to programmatically get completion choices for any line.
* @param args An array of the words in the command line to complete.
* @param done The callback to be called with the resulting completions.
*/
getCompletion(args: readonly string[], done: (completions: readonly string[]) => void): Argv<T>;
/**
* Indicate that an option (or group of options) should not be reset when a command is executed
*
* Options default to being global.
*/
global(key: string | readonly string[]): Argv<T>;
/** Given a key, or an array of keys, places options under an alternative heading when displaying usage instructions */
group(key: string | readonly string[], groupName: string): Argv<T>;
/** Hides a key from the generated usage information. Unless a `--show-hidden` option is also passed with `--help` (see `showHidden()`). */
hide(key: string): Argv<T>;
/**
* Configure an (e.g. `--help`) and implicit command that displays the usage string and exits the process.
* By default yargs enables help on the `--help` option.
*
* Note that any multi-char aliases (e.g. `help`) used for the help option will also be used for the implicit command.
* If there are no multi-char aliases (e.g. `h`), then all single-char aliases will be used for the command.
*
* If invoked without parameters, `.help()` will use `--help` as the option and help as the implicit command to trigger help output.
*
* @param [description] Customizes the description of the help option in the usage string.
* @param [enableExplicit] If `false` is provided, it will disable --help.
*/
help(): Argv<T>;
help(enableExplicit: boolean): Argv<T>;
help(option: string, enableExplicit: boolean): Argv<T>;
help(option: string, description?: string, enableExplicit?: boolean): Argv<T>;
/**
* Given the key `x` is set, it is required that the key `y` is set.
* y` can either be the name of an argument to imply, a number indicating the position of an argument or an array of multiple implications to associate with `x`.
*
* Optionally `.implies()` can accept an object specifying multiple implications.
*/
implies(key: string, value: string | readonly string[]): Argv<T>;
implies(implies: { [key: string]: string | readonly string[] }): Argv<T>;
/**
* Return the locale that yargs is currently using.
*
* By default, yargs will auto-detect the operating system's locale so that yargs-generated help content will display in the user's language.
*/
locale(): string;
/**
* Override the auto-detected locale from the user's operating system with a static locale.
* Note that the OS locale can be modified by setting/exporting the `LC_ALL` environment variable.
*/
locale(loc: string): Argv<T>;
/**
* Define global middleware functions to be called first, in list order, for all cli command.
* @param callbacks Can be a function or a list of functions. Each callback gets passed a reference to argv.
* @param [applyBeforeValidation] Set to `true` to apply middleware before validation. This will execute the middleware prior to validation checks, but after parsing.
*/
middleware(
callbacks: MiddlewareFunction<T> | ReadonlyArray<MiddlewareFunction<T>>,
applyBeforeValidation?: boolean,
): Argv<T>;
/**
* The number of arguments that should be consumed after a key. This can be a useful hint to prevent parsing ambiguity.
*
* Optionally `.nargs()` can take an object of `key`/`narg` pairs.
*/
nargs(key: string, count: number): Argv<T>;
nargs(nargs: { [key: string]: number }): Argv<T>;
/** The key provided represents a path and should have `path.normalize()` applied. */
normalize<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>;
normalize<K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: string | undefined }>;
/**
* Tell the parser to always interpret key as a number.
*
* If `key` is an array, all elements will be parsed as numbers.
*
* If the option is given on the command line without a value, `argv` will be populated with `undefined`.
*
* If the value given on the command line cannot be parsed as a number, `argv` will be populated with `NaN`.
*
* Note that decimals, hexadecimals, and scientific notation are all accepted.
*/
number<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: ToNumber<T[key]> }>;
number<K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: number | undefined }>;
/**
* Method to execute when a command finishes successfully.
* @param func Is called with the successful result of the command that finished.
*/
onFinishCommand(func: (result: any) => void): Argv<T>;
/**
* This method can be used to make yargs aware of options that could exist.
* You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option.
*/
option<K extends keyof T, O extends Options>(
key: K,
options: O,
): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
option<K extends string, O extends Options>(
key: K,
options: O,
): Argv<T & { [key in K]: InferredOptionType<O> }>;
option<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>;
/**
* This method can be used to make yargs aware of options that could exist.
* You can also pass an opt object which can hold further customization, like `.alias()`, `.demandOption()` etc. for that option.
*/
options<K extends keyof T, O extends Options>(
key: K,
options: O,
): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
options<K extends string, O extends Options>(
key: K,
options: O,
): Argv<T & { [key in K]: InferredOptionType<O> }>;
options<O extends { [key: string]: Options }>(options: O): Argv<Omit<T, keyof O> & InferredOptionTypes<O>>;
/**
* Parse `args` instead of `process.argv`. Returns the `argv` object. `args` may either be a pre-processed argv array, or a raw argument string.
*
* Note: Providing a callback to parse() disables the `exitProcess` setting until after the callback is invoked.
* @param [context] Provides a useful mechanism for passing state information to commands
*/
parse(): { [key in keyof Arguments<T>]: Arguments<T>[key] };
parse(
arg: string | readonly string[],
context?: object,
parseCallback?: ParseCallback<T>,
): { [key in keyof Arguments<T>]: Arguments<T>[key] };
/**
* If the arguments have not been parsed, this property is `false`.
*
* If the arguments have been parsed, this contain detailed parsed arguments.
*/
parsed: DetailedArguments | false;
/** Allows to configure advanced yargs features. */
parserConfiguration(configuration: Partial<ParserConfigurationOptions>): Argv<T>;
/**
* Similar to `config()`, indicates that yargs should interpret the object from the specified key in package.json as a configuration object.
* @param [cwd] If provided, the package.json will be read from this location
*/
pkgConf(key: string | readonly string[], cwd?: string): Argv<T>;
/**
* Allows you to configure a command's positional arguments with an API similar to `.option()`.
* `.positional()` should be called in a command's builder function, and is not available on the top-level yargs instance. If so, it will throw an error.
*/
positional<K extends keyof T, O extends PositionalOptions>(
key: K,
opt: O,
): Argv<Omit<T, K> & { [key in K]: InferredOptionType<O> }>;
positional<K extends string, O extends PositionalOptions>(
key: K,
opt: O,
): Argv<T & { [key in K]: InferredOptionType<O> }>;
/** Should yargs provide suggestions regarding similar commands if no matching command is found? */
recommendCommands(): Argv<T>;
/**
* @deprecated since version 6.6.0
* Use '.demandCommand()' or '.demandOption()' instead
*/
require<K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv<Defined<T, K>>;
require(key: string, msg: string): Argv<T>;
require(key: string, required: boolean): Argv<T>;
require(keys: readonly number[], msg: string): Argv<T>;
require(keys: readonly number[], required: boolean): Argv<T>;
require(positionals: number, required: boolean): Argv<T>;
require(positionals: number, msg: string): Argv<T>;
/**
* @deprecated since version 6.6.0
* Use '.demandCommand()' or '.demandOption()' instead
*/
required<K extends keyof T>(key: K | readonly K[], msg?: string | true): Argv<Defined<T, K>>;
required(key: string, msg: string): Argv<T>;
required(key: string, required: boolean): Argv<T>;
required(keys: readonly number[], msg: string): Argv<T>;
required(keys: readonly number[], required: boolean): Argv<T>;
required(positionals: number, required: boolean): Argv<T>;
required(positionals: number, msg: string): Argv<T>;
requiresArg(key: string | readonly string[]): Argv<T>;
/**
* @deprecated since version 6.6.0
* Use '.global()' instead
*/
reset(): Argv<T>;
/** Set the name of your script ($0). Default is the base filename executed by node (`process.argv[1]`) */
scriptName($0: string): Argv<T>;
/**
* Generate a bash completion script.
* Users of your application can install this script in their `.bashrc`, and yargs will provide completion shortcuts for commands and options.
*/
showCompletionScript(): Argv<T>;
/**
* Configure the `--show-hidden` option that displays the hidden keys (see `hide()`).
* @param option If `boolean`, it enables/disables this option altogether. i.e. hidden keys will be permanently hidden if first argument is `false`.
* If `string` it changes the key name ("--show-hidden").
* @param description Changes the default description ("Show hidden options")
*/
showHidden(option?: string | boolean): Argv<T>;
showHidden(option: string, description?: string): Argv<T>;
/**
* Print the usage data using the console function consoleLevel for printing.
* @param [consoleLevel='error']
*/
showHelp(consoleLevel?: string): Argv<T>;
/**
* Provide the usage data as a string.
* @param printCallback a function with a single argument.
*/
showHelp(printCallback: (s: string) => void): Argv<T>;
/**
* By default, yargs outputs a usage string if any error is detected.
* Use the `.showHelpOnFail()` method to customize this behavior.
* @param enable If `false`, the usage string is not output.
* @param [message] Message that is output after the error message.
*/
showHelpOnFail(enable: boolean, message?: string): Argv<T>;
/** Specifies either a single option key (string), or an array of options. If any of the options is present, yargs validation is skipped. */
skipValidation(key: string | readonly string[]): Argv<T>;
/**
* Any command-line argument given that is not demanded, or does not have a corresponding description, will be reported as an error.
*
* Unrecognized commands will also be reported as errors.
*/
strict(): Argv<T>;
strict(enabled: boolean): Argv<T>;
/**
* Similar to .strict(), except that it only applies to unrecognized commands.
* A user can still provide arbitrary options, but unknown positional commands
* will raise an error.
*/
strictCommands(): Argv<T>;
strictCommands(enabled: boolean): Argv<T>;
/**
* Similar to `.strict()`, except that it only applies to unrecognized options. A
* user can still provide arbitrary positional options, but unknown options
* will raise an error.
*/
strictOptions(): Argv<T>;
strictOptions(enabled: boolean): Argv<T>;
/**
* Tell the parser logic not to interpret `key` as a number or boolean. This can be useful if you need to preserve leading zeros in an input.
*
* If `key` is an array, interpret all the elements as strings.
*
* `.string('_')` will result in non-hyphenated arguments being interpreted as strings, regardless of whether they resemble numbers.
*/
string<K extends keyof T>(key: K | readonly K[]): Argv<Omit<T, K> & { [key in K]: ToString<T[key]> }>;
string<K extends string>(key: K | readonly K[]): Argv<T & { [key in K]: string | undefined }>;
// Intended to be used with '.wrap()'
terminalWidth(): number;
updateLocale(obj: { [key: string]: string }): Argv<T>;
/**
* Override the default strings used by yargs with the key/value pairs provided in obj
*
* If you explicitly specify a locale(), you should do so before calling `updateStrings()`.
*/
updateStrings(obj: { [key: string]: string }): Argv<T>;
/**
* Set a usage message to show which commands to use.
* Inside `message`, the string `$0` will get interpolated to the current script name or node command for the present script similar to how `$0` works in bash or perl.
*
* If the optional `description`/`builder`/`handler` are provided, `.usage()` acts an an alias for `.command()`.
* This allows you to use `.usage()` to configure the default command that will be run as an entry-point to your application
* and allows you to provide configuration for the positional arguments accepted by your program:
*/
usage(message: string): Argv<T>;
usage<U>(
command: string | readonly string[],
description: string,
builder?: (args: Argv<T>) => Argv<U>,
handler?: (args: Arguments<U>) => void,
): Argv<T>;
usage<U>(
command: string | readonly string[],
showInHelp: boolean,
builder?: (args: Argv<T>) => Argv<U>,
handler?: (args: Arguments<U>) => void,
): Argv<T>;
usage<O extends { [key: string]: Options }>(
command: string | readonly string[],
description: string,
builder?: O,
handler?: (args: Arguments<InferredOptionTypes<O>>) => void,
): Argv<T>;
usage<O extends { [key: string]: Options }>(
command: string | readonly string[],
showInHelp: boolean,
builder?: O,
handler?: (args: Arguments<InferredOptionTypes<O>>) => void,
): Argv<T>;
/**
* Add an option (e.g. `--version`) that displays the version number (given by the version parameter) and exits the process.
* By default yargs enables version for the `--version` option.
*
* If no arguments are passed to version (`.version()`), yargs will parse the package.json of your module and use its version value.
*
* If the boolean argument `false` is provided, it will disable `--version`.
*/
version(): Argv<T>;
version(version: string): Argv<T>;
version(enable: boolean): Argv<T>;
version(optionKey: string, version: string): Argv<T>;
version(optionKey: string, description: string, version: string): Argv<T>;
/**
* Format usage output to wrap at columns many columns.
*
* By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to specify no column limit (no right-align).
* Use `.wrap(yargs.terminalWidth())` to maximize the width of yargs' usage instructions.
*/
wrap(columns: number | null): Argv<T>;
}
type Arguments<T = {}> = T & {
/** Non-option arguments */
_: Array<string | number>;
/** The script name or node command */
$0: string;
/** All remaining options */
[argName: string]: unknown;
};
interface RequireDirectoryOptions {
/** Look for command modules in all subdirectories and apply them as a flattened (non-hierarchical) list. */
recurse?: boolean | undefined;
/** The types of files to look for when requiring command modules. */
extensions?: readonly string[] | undefined;
/**
* A synchronous function called for each command module encountered.
* Accepts `commandObject`, `pathToFile`, and `filename` as arguments.
* Returns `commandObject` to include the command; any falsy value to exclude/skip it.
*/
visit?: ((commandObject: any, pathToFile?: string, filename?: string) => any) | undefined;
/** Whitelist certain modules */
include?: RegExp | ((pathToFile: string) => boolean) | undefined;
/** Blacklist certain modules. */
exclude?: RegExp | ((pathToFile: string) => boolean) | undefined;
}
interface Options {
/** string or array of strings, alias(es) for the canonical option key, see `alias()` */
alias?: string | readonly string[] | undefined;
/** boolean, interpret option as an array, see `array()` */
array?: boolean | undefined;
/** boolean, interpret option as a boolean flag, see `boolean()` */
boolean?: boolean | undefined;
/** value or array of values, limit valid option arguments to a predefined set, see `choices()` */
choices?: Choices | undefined;
/** function, coerce or transform parsed command line values into another value, see `coerce()` */
coerce?: ((arg: any) => any) | undefined;
/** boolean, interpret option as a path to a JSON config file, see `config()` */
config?: boolean | undefined;
/** function, provide a custom config parsing function, see `config()` */
configParser?: ((configPath: string) => object) | undefined;
/** string or object, require certain keys not to be set, see `conflicts()` */
conflicts?: string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
/** boolean, interpret option as a count of boolean flags, see `count()` */
count?: boolean | undefined;
/** value, set a default value for the option, see `default()` */
default?: any;
/** string, use this description for the default value in help content, see `default()` */
defaultDescription?: string | undefined;
/**
* @deprecated since version 6.6.0
* Use 'demandOption' instead
*/
demand?: boolean | string | undefined;
/** boolean or string, mark the argument as deprecated, see `deprecateOption()` */
deprecate?: boolean | string | undefined;
/** boolean or string, mark the argument as deprecated, see `deprecateOption()` */
deprecated?: boolean | string | undefined;
/** boolean or string, demand the option be given, with optional error message, see `demandOption()` */
demandOption?: boolean | string | undefined;
/** string, the option description for help content, see `describe()` */
desc?: string | undefined;
/** string, the option description for help content, see `describe()` */
describe?: string | undefined;
/** string, the option description for help content, see `describe()` */
description?: string | undefined;
/** boolean, indicate that this key should not be reset when a command is invoked, see `global()` */
global?: boolean | undefined;
/** string, when displaying usage instructions place the option under an alternative group heading, see `group()` */
group?: string | undefined;
/** don't display option in help output. */
hidden?: boolean | undefined;
/** string or object, require certain keys to be set, see `implies()` */
implies?: string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
/** number, specify how many arguments should be consumed for the option, see `nargs()` */
nargs?: number | undefined;
/** boolean, apply path.normalize() to the option, see `normalize()` */
normalize?: boolean | undefined;
/** boolean, interpret option as a number, `number()` */
number?: boolean | undefined;
/**
* @deprecated since version 6.6.0
* Use 'demandOption' instead
*/
require?: boolean | string | undefined;
/**
* @deprecated since version 6.6.0
* Use 'demandOption' instead
*/
required?: boolean | string | undefined;
/** boolean, require the option be specified with a value, see `requiresArg()` */
requiresArg?: boolean | undefined;
/** boolean, skips validation if the option is present, see `skipValidation()` */
skipValidation?: boolean | undefined;
/** boolean, interpret option as a string, see `string()` */
string?: boolean | undefined;
type?: "array" | "count" | PositionalOptionsType | undefined;
}
interface PositionalOptions {
/** string or array of strings, see `alias()` */
alias?: string | readonly string[] | undefined;
/** boolean, interpret option as an array, see `array()` */
array?: boolean | undefined;
/** value or array of values, limit valid option arguments to a predefined set, see `choices()` */
choices?: Choices | undefined;
/** function, coerce or transform parsed command line values into another value, see `coerce()` */
coerce?: ((arg: any) => any) | undefined;
/** string or object, require certain keys not to be set, see `conflicts()` */
conflicts?: string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
/** value, set a default value for the option, see `default()` */
default?: any;
/** boolean or string, demand the option be given, with optional error message, see `demandOption()` */
demandOption?: boolean | string | undefined;
/** string, the option description for help content, see `describe()` */
desc?: string | undefined;
/** string, the option description for help content, see `describe()` */
describe?: string | undefined;
/** string, the option description for help content, see `describe()` */
description?: string | undefined;
/** string or object, require certain keys to be set, see `implies()` */
implies?: string | readonly string[] | { [key: string]: string | readonly string[] } | undefined;
/** boolean, apply path.normalize() to the option, see normalize() */
normalize?: boolean | undefined;
type?: PositionalOptionsType | undefined;
}
/** Remove keys K in T */
type Omit<T, K> = { [key in Exclude<keyof T, K>]: T[key] };
/** Remove undefined as a possible value for keys K in T */
type Defined<T, K extends keyof T> = Omit<T, K> & { [key in K]: Exclude<T[key], undefined> };
/** Convert T to T[] and T | undefined to T[] | undefined */
type ToArray<T> = Array<Exclude<T, undefined>> | Extract<T, undefined>;
/** Gives string[] if T is an array type, otherwise string. Preserves | undefined. */
type ToString<T> = (Exclude<T, undefined> extends any[] ? string[] : string) | Extract<T, undefined>;
/** Gives number[] if T is an array type, otherwise number. Preserves | undefined. */
type ToNumber<T> = (Exclude<T, undefined> extends any[] ? number[] : number) | Extract<T, undefined>;
type InferredOptionType<O extends Options | PositionalOptions> = O extends
{ default: any; coerce: (arg: any) => infer T } ? T
: O extends { default: infer D } ? D
: O extends { type: "count" } ? number
: O extends { count: true } ? number
: O extends { required: string | true } ? RequiredOptionType<O>
: O extends { require: string | true } ? RequiredOptionType<O>
: O extends { demand: string | true } ? RequiredOptionType<O>
: O extends { demandOption: string | true } ? RequiredOptionType<O>
: RequiredOptionType<O> | undefined;
type RequiredOptionType<O extends Options | PositionalOptions> = O extends { type: "array"; string: true }
? string[]
: O extends { type: "array"; number: true } ? number[]
: O extends { type: "array"; normalize: true } ? string[]
: O extends { type: "string"; array: true } ? string[]
: O extends { type: "number"; array: true } ? number[]
: O extends { string: true; array: true } ? string[]
: O extends { number: true; array: true } ? number[]
: O extends { normalize: true; array: true } ? string[]
: O extends { type: "array" } ? Array<string | number>
: O extends { type: "boolean" } ? boolean
: O extends { type: "number" } ? number
: O extends { type: "string" } ? string
: O extends { array: true } ? Array<string | number>
: O extends { boolean: true } ? boolean
: O extends { number: true } ? number
: O extends { string: true } ? string
: O extends { normalize: true } ? string
: O extends { choices: ReadonlyArray<infer C> } ? C
: O extends { coerce: (arg: any) => infer T } ? T
: unknown;
type InferredOptionTypes<O extends { [key: string]: Options }> = { [key in keyof O]: InferredOptionType<O[key]> };
interface CommandModule<T = {}, U = {}> {
/** array of strings (or a single string) representing aliases of `exports.command`, positional args defined in an alias are ignored */
aliases?: readonly string[] | string | undefined;
/** object declaring the options the command accepts, or a function accepting and returning a yargs instance */
builder?: CommandBuilder<T, U> | undefined;
/** string (or array of strings) that executes this command when given on the command line, first string may contain positional args */
command?: readonly string[] | string | undefined;
/** boolean (or string) to show deprecation notice */
deprecated?: boolean | string | undefined;
/** string used as the description for the command in help text, use `false` for a hidden command */
describe?: string | false | undefined;
/** a function which will be passed the parsed argv. */
handler: (args: Arguments<U>) => void;
}
type ParseCallback<T = {}> = (err: Error | undefined, argv: Arguments<T>, output: string) => void;
type CommandBuilder<T = {}, U = {}> =
| { [key: string]: Options }
| ((args: Argv<T>) => Argv<U>)
| ((args: Argv<T>) => PromiseLike<Argv<U>>);
type SyncCompletionFunction = (current: string, argv: any) => string[];
type AsyncCompletionFunction = (
current: string,
argv: any,
done: (completion: readonly string[]) => void,
) => void;
type PromiseCompletionFunction = (current: string, argv: any) => Promise<string[]>;
type MiddlewareFunction<T = {}> = (args: Arguments<T>) => void;
type Choices = ReadonlyArray<string | number | true | undefined>;
type PositionalOptionsType = "boolean" | "number" | "string";
}
declare var yargs: yargs.Argv;
export = yargs;

View File

@@ -0,0 +1,62 @@
{
"name": "@types/yargs",
"version": "16.0.9",
"description": "TypeScript definitions for yargs",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs",
"license": "MIT",
"contributors": [
{
"name": "Martin Poelstra",
"githubUsername": "poelstra",
"url": "https://github.com/poelstra"
},
{
"name": "Mizunashi Mana",
"githubUsername": "mizunashi-mana",
"url": "https://github.com/mizunashi-mana"
},
{
"name": "Jeffery Grajkowski",
"githubUsername": "pushplay",
"url": "https://github.com/pushplay"
},
{
"name": "Jimi (Dimitris) Charalampidis",
"githubUsername": "JimiC",
"url": "https://github.com/JimiC"
},
{
"name": "Steffen Viken Valvåg",
"githubUsername": "steffenvv",
"url": "https://github.com/steffenvv"
},
{
"name": "Emily Marigold Klassen",
"githubUsername": "forivall",
"url": "https://github.com/forivall"
},
{
"name": "ExE Boss",
"githubUsername": "ExE-Boss",
"url": "https://github.com/ExE-Boss"
},
{
"name": "Aankhen",
"githubUsername": "Aankhen",
"url": "https://github.com/Aankhen"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/yargs"
},
"scripts": {},
"dependencies": {
"@types/yargs-parser": "*"
},
"typesPublisherContentHash": "cb1afff2e12b5d722156de0eabb2bd446fd1eb57638052e13771b041d96e0e52",
"typeScriptVersion": "4.5"
}

View File

@@ -0,0 +1,9 @@
import { Argv } from ".";
export = Yargs;
declare function Yargs(
processArgs?: readonly string[],
cwd?: string,
parentRequire?: NodeRequire,
): Argv;

View File

@@ -0,0 +1,415 @@
/**
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}%}
`);
```
@example
```
import chalk = require('chalk');
log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`)
```
*/
(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;

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,68 @@
{
"name": "chalk",
"version": "4.1.2",
"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"
}
}
}

View File

@@ -0,0 +1,341 @@
<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](https://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">
<br>
---
<div align="center">
<p>
<p>
<sup>
Sindre Sorhus' open source work is supported by the community on <a href="https://github.com/sponsors/sindresorhus">GitHub Sponsors</a> and <a href="https://stakes.social/0x44d871aebF0126Bf646753E2C976Aa7e68A66c15">Dev</a>
</sup>
</p>
<sup>Special thanks to:</sup>
<br>
<br>
<a href="https://standardresume.co/tech">
<img src="https://sindresorhus.com/assets/thanks/standard-resume-logo.svg" width="160"/>
</a>
<br>
<br>
<a href="https://retool.com/?utm_campaign=sindresorhus">
<img src="https://sindresorhus.com/assets/thanks/retool-logo.svg" width="230"/>
</a>
<br>
<br>
<a href="https://doppler.com/?utm_campaign=github_repo&utm_medium=referral&utm_content=chalk&utm_source=github">
<div>
<img src="https://dashboard.doppler.com/imgs/logo-long.svg" width="240" alt="Doppler">
</div>
<b>All your environment variables, in one place</b>
<div>
<span>Stop struggling with scattered API keys, hacking together home-brewed tools,</span>
<br>
<span>and avoiding access controls. Keep your team and servers in sync with Doppler.</span>
</div>
</a>
<br>
<a href="https://uibakery.io/?utm_source=chalk&utm_medium=sponsor&utm_campaign=github">
<div>
<img src="https://sindresorhus.com/assets/thanks/uibakery-logo.jpg" width="270" alt="UI Bakery">
</div>
</a>
</p>
</div>
---
<br>
## 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](https://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 three statements are equivalent:
```js
console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
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-)

View File

@@ -0,0 +1,229 @@
'use strict';
const ansiStyles = require('ansi-styles');
const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color');
const {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
} = require('./util');
const {isArray} = Array;
// `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_) => {
if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
// Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
return applyStyle(builder, chalkTag(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 (!isArray(firstString) || !isArray(firstString.raw)) {
// 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;

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('');
};

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,178 @@
# Changelog
## v3.9.0
- better support for Azure Pipelines ([#116](https://github.com/watson/ci-info/pull/116)), [5ea8d85](https://github.com/watson/ci-info/commit/5ea8d85)
- detect PullRequest in Azure Pipelines [5ea8d85](https://github.com/watson/ci-info/commit/5ea8d85)
## v3.8.0
- support Harness CI [76a2867](https://github.com/watson/ci-info/commit/76a2867)
## v3.7.1
- ignore ci detection when CI is set to `'false'` [24cc450](https://github.com/watson/ci-info/commit/24cc450)
## v3.7.0
- support Sourcehut CI [85b96ea](https://github.com/watson/ci-info/commit/85b96ea)
- support ReleaseHub CI [409d886](https://github.com/watson/ci-info/commit/409d886)
## v3.6.2
- fix VERCEL environment detection ([#98](https://github.com/watson/ci-info/pull/98))
## v3.6.1
- fix error in typings [357b454](https://github.com/watson/ci-info/commit/357b454)
## v3.6.0
This release attempts to bring parity with [@npmcli/ci-detect](https://github.com/npm/ci-detect). See [#95](https://github.com/watson/ci-info/pull/95) for more details.
- support gerrit ([#95](https://github.com/watson/ci-info/pull/95))
- support google cloud build ([#95](https://github.com/watson/ci-info/pull/95))
- support heroku ([#95](https://github.com/watson/ci-info/pull/95))
- support anonymous CI's that exposes BUILD_ID and CI_NAME env vars ([#95](https://github.com/watson/ci-info/pull/95))
- support more vercel environments ([#95](https://github.com/watson/ci-info/pull/95))
## v3.5.0
- support Woodpecker CI ([#90](https://github.com/watson/ci-info/pull/90))
## v3.4.0
- partial support Appflow CI (only CI detection) ([#84](https://github.com/watson/ci-info/pull/84))
- support Codemagic CI ([#85](https://github.com/watson/ci-info/pull/85))
- support Xcode Server CI ([#86](https://github.com/watson/ci-info/pull/86))
- support Xcode Cloud CI ([#86](https://github.com/watson/ci-info/pull/86))
## v3.3.2
- fix: export correct typings for `EAS`
## v3.3.1
- fix: export `EAS_BUILD` constant in typings
- Add support for nodejs v18
## v3.3.0
- support Expo Application Services ([#70](https://github.com/watson/ci-info/pull/70))
## v3.2.0
- support LayerCI ([#68](https://github.com/watson/ci-info/pull/68))
- support Appcircle ([#69](https://github.com/watson/ci-info/pull/69))
- support Codefresh CI ([#65](https://github.com/watson/ci-info/pull/65))
- add support for nodejs v16
## v3.1.1
Bug Fixes:
- remove duplicate declaration in typings
## v3.1.0
Features:
- add typings
## v3.0.0
Features:
- Add support nodejs versions: 14, 15
- support Nevercode ([#30](https://github.com/watson/ci-info/pull/30))
- support Render CI ([#36](https://github.com/watson/ci-info/pull/36))
- support Now CI ([#37](https://github.com/watson/ci-info/pull/37))
- support GitLab PR ([#59](https://github.com/watson/ci-info/pull/59))
- support Screwdriver CD ([#60](https://github.com/watson/ci-info/pull/60))
- support Visual Studio App Center ([#61](https://github.com/watson/ci-info/pull/61))
Bug Fixes:
- update Netlify env constant ([#47](https://github.com/watson/ci-info/pull/47))
Breaking changes:
- Drop support for Node.js end-of-life versions: 6, 13
- replace `Zeit Now` with `Vercel` ([#55](https://github.com/watson/ci-info/pull/55))
## v2.0.0
Breaking changes:
- Drop support for Node.js end-of-life versions: 0.10, 0.12, 4, 5, 7, and 9
- Team Foundation Server will now be detected as Azure Pipelines. The constant `ci.TFS` no longer exists - use
`ci.AZURE_PIPELINES` instead
- Remove deprecated `ci.TDDIUM` constant - use `ci.SOLANDO` instead
New features:
- feat: support Azure Pipelines ([#23](https://github.com/watson/ci-info/pull/23))
- feat: support Netlify CI ([#26](https://github.com/watson/ci-info/pull/26))
- feat: support Bitbucket pipelines PR detection ([#27](https://github.com/watson/ci-info/pull/27))
## v1.6.0
- feat: add Sail CI support
- feat: add Buddy support
- feat: add Bitrise support
- feat: detect Jenkins PRs
- feat: detect Drone PRs
## v1.5.1
- fix: use full path to vendors.json
## v1.5.0
- feat: add dsari detection ([#15](https://github.com/watson/ci-info/pull/15))
- feat: add ci.isPR ([#16](https://github.com/watson/ci-info/pull/16))
## v1.4.0
- feat: add Cirrus CI detection ([#13](https://github.com/watson/ci-info/pull/13))
- feat: add Shippable CI detection ([#14](https://github.com/watson/ci-info/pull/14))
## v1.3.1
- chore: reduce npm package size by not including `.github` folder content
([#11](https://github.com/watson/ci-info/pull/11))
## v1.3.0
- feat: add support for Strider CD
- chore: deprecate vendor constant `TDDIUM` in favor of `SOLANO`
- docs: add missing vendor constant to docs
## v1.2.0
- feat: detect solano-ci ([#9](https://github.com/watson/ci-info/pull/9))
## v1.1.3
- fix: fix spelling of Hunson in `ci.name`
## v1.1.2
- fix: no more false positive matches for Jenkins
## v1.1.1
- docs: sort lists of CI servers in README.md
- docs: add missing AWS CodeBuild to the docs
## v1.1.0
- feat: add AWS CodeBuild to CI detection ([#2](https://github.com/watson/ci-info/pull/2))
## v1.0.1
- chore: reduce npm package size by using an `.npmignore` file ([#3](https://github.com/watson/ci-info/pull/3))
## v1.0.0
- Initial release

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016 Thomas Watson Steen
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,135 @@
# ci-info
Get details about the current Continuous Integration environment.
Please [open an
issue](https://github.com/watson/ci-info/issues/new?template=ci-server-not-detected.md)
if your CI server isn't properly detected :)
[![npm](https://img.shields.io/npm/v/ci-info.svg)](https://www.npmjs.com/package/ci-info)
[![Tests](https://github.com/watson/ci-info/workflows/Tests/badge.svg)](https://github.com/watson/ci-info/actions)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard)
## Installation
```bash
npm install ci-info --save
```
## Usage
```js
var ci = require('ci-info')
if (ci.isCI) {
console.log('The name of the CI server is:', ci.name)
} else {
console.log('This program is not running on a CI server')
}
```
## Supported CI tools
Officially supported CI servers:
| Name | Constant | isPR |
| ------------------------------------------------------------------------------- | ----------------------- | ---- |
| [AWS CodeBuild](https://aws.amazon.com/codebuild/) | `ci.CODEBUILD` | 🚫 |
| [AppVeyor](http://www.appveyor.com) | `ci.APPVEYOR` | ✅ |
| [Azure Pipelines](https://azure.microsoft.com/en-us/services/devops/pipelines/) | `ci.AZURE_PIPELINES` | ✅ |
| [Appcircle](https://appcircle.io/) | `ci.APPCIRCLE` | 🚫 |
| [Bamboo](https://www.atlassian.com/software/bamboo) by Atlassian | `ci.BAMBOO` | 🚫 |
| [Bitbucket Pipelines](https://bitbucket.org/product/features/pipelines) | `ci.BITBUCKET` | ✅ |
| [Bitrise](https://www.bitrise.io/) | `ci.BITRISE` | ✅ |
| [Buddy](https://buddy.works/) | `ci.BUDDY` | ✅ |
| [Buildkite](https://buildkite.com) | `ci.BUILDKITE` | ✅ |
| [CircleCI](http://circleci.com) | `ci.CIRCLE` | ✅ |
| [Cirrus CI](https://cirrus-ci.org) | `ci.CIRRUS` | ✅ |
| [Codefresh](https://codefresh.io/) | `ci.CODEFRESH` | ✅ |
| [Codeship](https://codeship.com) | `ci.CODESHIP` | 🚫 |
| [Drone](https://drone.io) | `ci.DRONE` | ✅ |
| [dsari](https://github.com/rfinnie/dsari) | `ci.DSARI` | 🚫 |
| [Expo Application Services](https://expo.dev/eas) | `ci.EAS` | 🚫 |
| [Gerrit CI](https://www.gerritcodereview.com) | `ci.GERRIT` | 🚫 |
| [GitHub Actions](https://github.com/features/actions/) | `ci.GITHUB_ACTIONS` | ✅ |
| [GitLab CI](https://about.gitlab.com/gitlab-ci/) | `ci.GITLAB` | ✅ |
| [GoCD](https://www.go.cd/) | `ci.GOCD` | 🚫 |
| [Google Cloud Build](https://cloud.google.com/build) | `ci.GOOGLE_CLOUD_BUILD` | 🚫 |
| [Harness CI](https://www.harness.io/products/continuous-integration) | `ci.HARNESS` | 🚫 |
| [Heroku](https://www.heroku.com) | `ci.HEROKU` | 🚫 |
| [Hudson](http://hudson-ci.org) | `ci.HUDSON` | 🚫 |
| [Jenkins CI](https://jenkins-ci.org) | `ci.JENKINS` | ✅ |
| [LayerCI](https://layerci.com/) | `ci.LAYERCI` | ✅ |
| [Magnum CI](https://magnum-ci.com) | `ci.MAGNUM` | 🚫 |
| [Netlify CI](https://www.netlify.com/) | `ci.NETLIFY` | ✅ |
| [Nevercode](http://nevercode.io/) | `ci.NEVERCODE` | ✅ |
| [ReleaseHub](https://releasehub.com/) | `ci.RELEASEHUB` | 🚫 |
| [Render](https://render.com/) | `ci.RENDER` | ✅ |
| [Sail CI](https://sail.ci/) | `ci.SAIL` | ✅ |
| [Screwdriver](https://screwdriver.cd/) | `ci.SCREWDRIVER` | ✅ |
| [Semaphore](https://semaphoreci.com) | `ci.SEMAPHORE` | ✅ |
| [Shippable](https://www.shippable.com/) | `ci.SHIPPABLE` | ✅ |
| [Solano CI](https://www.solanolabs.com/) | `ci.SOLANO` | ✅ |
| [Sourcehut](https://sourcehut.org/) | `ci.SOURCEHUT` | 🚫 |
| [Strider CD](https://strider-cd.github.io/) | `ci.STRIDER` | 🚫 |
| [TaskCluster](http://docs.taskcluster.net) | `ci.TASKCLUSTER` | 🚫 |
| [TeamCity](https://www.jetbrains.com/teamcity/) by JetBrains | `ci.TEAMCITY` | 🚫 |
| [Travis CI](http://travis-ci.org) | `ci.TRAVIS` | ✅ |
| [Vercel](https://vercel.com/) | `ci.VERCEL` | ✅ |
| [Visual Studio App Center](https://appcenter.ms/) | `ci.APPCENTER` | 🚫 |
| [Woodpecker](https://woodpecker-ci.org/) | `ci.WOODPECKER` | ✅ |
## API
### `ci.name`
Returns a string containing name of the CI server the code is running on.
If CI server is not detected, it returns `null`.
Don't depend on the value of this string not to change for a specific
vendor. If you find your self writing `ci.name === 'Travis CI'`, you
most likely want to use `ci.TRAVIS` instead.
### `ci.isCI`
Returns a boolean. Will be `true` if the code is running on a CI server,
otherwise `false`.
Some CI servers not listed here might still trigger the `ci.isCI`
boolean to be set to `true` if they use certain vendor neutral
environment variables. In those cases `ci.name` will be `null` and no
vendor specific boolean will be set to `true`.
### `ci.isPR`
Returns a boolean if PR detection is supported for the current CI server. Will
be `true` if a PR is being tested, otherwise `false`. If PR detection is
not supported for the current CI server, the value will be `null`.
### `ci.<VENDOR-CONSTANT>`
A vendor specific boolean constant is exposed for each support CI
vendor. A constant will be `true` if the code is determined to run on
the given CI server, otherwise `false`.
Examples of vendor constants are `ci.TRAVIS` or `ci.APPVEYOR`. For a
complete list, see the support table above.
Deprecated vendor constants that will be removed in the next major
release:
- `ci.TDDIUM` (Solano CI) This have been renamed `ci.SOLANO`
## Ports
ci-info has been ported to the following languages
| Language | Repository |
|----------|------------|
| Go | https://github.com/hofstadter-io/cinful |
| Rust | https://github.com/sagiegurari/ci_info |
| Kotlin | https://github.com/cloudflightio/ci-info |
## License
[MIT](LICENSE)

View File

@@ -0,0 +1,75 @@
// This file is generated at pre-commit by running `node create-typings.js`.
/**
* Returns a boolean. Will be `true` if the code is running on a CI server,
* otherwise `false`.
*
* Some CI servers not listed here might still trigger the `ci.isCI`
* boolean to be set to `true` if they use certain vendor neutral environment
* variables. In those cases `ci.name` will be `null` and no vendor specific
* boolean will be set to `true`.
*/
export const isCI: boolean;
/**
* Returns a boolean if PR detection is supported for the current CI server.
* Will be `true` if a PR is being tested, otherwise `false`. If PR detection is
* not supported for the current CI server, the value will be `null`.
*/
export const isPR: boolean | null;
/**
* Returns a string containing name of the CI server the code is running on. If
* CI server is not detected, it returns `null`.
*
* Don't depend on the value of this string not to change for a specific vendor.
* If you find your self writing `ci.name === 'Travis CI'`, you most likely want
* to use `ci.TRAVIS` instead.
*/
export const name: string | null;
export const APPCIRCLE: boolean;
export const APPVEYOR: boolean;
export const CODEBUILD: boolean;
export const AZURE_PIPELINES: boolean;
export const BAMBOO: boolean;
export const BITBUCKET: boolean;
export const BITRISE: boolean;
export const BUDDY: boolean;
export const BUILDKITE: boolean;
export const CIRCLE: boolean;
export const CIRRUS: boolean;
export const CODEFRESH: boolean;
export const CODEMAGIC: boolean;
export const CODESHIP: boolean;
export const DRONE: boolean;
export const DSARI: boolean;
export const EAS: boolean;
export const GERRIT: boolean;
export const GITHUB_ACTIONS: boolean;
export const GITLAB: boolean;
export const GOCD: boolean;
export const GOOGLE_CLOUD_BUILD: boolean;
export const HARNESS: boolean;
export const HEROKU: boolean;
export const HUDSON: boolean;
export const JENKINS: boolean;
export const LAYERCI: boolean;
export const MAGNUM: boolean;
export const NETLIFY: boolean;
export const NEVERCODE: boolean;
export const RELEASEHUB: boolean;
export const RENDER: boolean;
export const SAIL: boolean;
export const SCREWDRIVER: boolean;
export const SEMAPHORE: boolean;
export const SHIPPABLE: boolean;
export const SOLANO: boolean;
export const SOURCEHUT: boolean;
export const STRIDER: boolean;
export const TASKCLUSTER: boolean;
export const TEAMCITY: boolean;
export const TRAVIS: boolean;
export const VERCEL: boolean;
export const APPCENTER: boolean;
export const WOODPECKER: boolean;
export const XCODE_CLOUD: boolean;
export const XCODE_SERVER: boolean;

View File

@@ -0,0 +1,90 @@
'use strict'
const vendors = require('./vendors.json')
const env = process.env
// Used for testing only
Object.defineProperty(exports, '_vendors', {
value: vendors.map(function (v) {
return v.constant
})
})
exports.name = null
exports.isPR = null
vendors.forEach(function (vendor) {
const envs = Array.isArray(vendor.env) ? vendor.env : [vendor.env]
const isCI = envs.every(function (obj) {
return checkEnv(obj)
})
exports[vendor.constant] = isCI
if (!isCI) {
return
}
exports.name = vendor.name
switch (typeof vendor.pr) {
case 'string':
// "pr": "CIRRUS_PR"
exports.isPR = !!env[vendor.pr]
break
case 'object':
if ('env' in vendor.pr) {
// "pr": { "env": "BUILDKITE_PULL_REQUEST", "ne": "false" }
exports.isPR = vendor.pr.env in env && env[vendor.pr.env] !== vendor.pr.ne
} else if ('any' in vendor.pr) {
// "pr": { "any": ["ghprbPullId", "CHANGE_ID"] }
exports.isPR = vendor.pr.any.some(function (key) {
return !!env[key]
})
} else {
// "pr": { "DRONE_BUILD_EVENT": "pull_request" }
exports.isPR = checkEnv(vendor.pr)
}
break
default:
// PR detection not supported for this vendor
exports.isPR = null
}
})
exports.isCI = !!(
env.CI !== 'false' && // Bypass all checks if CI env is explicitly set to 'false'
(env.BUILD_ID || // Jenkins, Cloudbees
env.BUILD_NUMBER || // Jenkins, TeamCity
env.CI || // Travis CI, CircleCI, Cirrus CI, Gitlab CI, Appveyor, CodeShip, dsari
env.CI_APP_ID || // Appflow
env.CI_BUILD_ID || // Appflow
env.CI_BUILD_NUMBER || // Appflow
env.CI_NAME || // Codeship and others
env.CONTINUOUS_INTEGRATION || // Travis CI, Cirrus CI
env.RUN_ID || // TaskCluster, dsari
exports.name ||
false)
)
function checkEnv (obj) {
// "env": "CIRRUS"
if (typeof obj === 'string') return !!env[obj]
// "env": { "env": "NODE", "includes": "/app/.heroku/node/bin/node" }
if ('env' in obj) {
// Currently there are no other types, uncomment when there are
// if ('includes' in obj) {
return env[obj.env] && env[obj.env].includes(obj.includes)
// }
}
if ('any' in obj) {
return obj.any.some(function (k) {
return !!env[k]
})
}
return Object.keys(obj).every(function (k) {
return env[k] === obj[k]
})
}

View File

@@ -0,0 +1,45 @@
{
"name": "ci-info",
"version": "3.9.0",
"description": "Get details about the current Continuous Integration environment",
"main": "index.js",
"typings": "index.d.ts",
"author": "Thomas Watson Steen <w@tson.dk> (https://twitter.com/wa7son)",
"license": "MIT",
"repository": "https://github.com/watson/ci-info.git",
"bugs": "https://github.com/watson/ci-info/issues",
"homepage": "https://github.com/watson/ci-info",
"keywords": [
"ci",
"continuous",
"integration",
"test",
"detect"
],
"files": [
"vendors.json",
"index.js",
"index.d.ts",
"CHANGELOG.md"
],
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/sibiraj-s"
}
],
"scripts": {
"lint:fix": "standard --fix",
"test": "standard && node test.js",
"prepare": "husky install"
},
"devDependencies": {
"clear-module": "^4.1.2",
"husky": "^8.0.3",
"standard": "^17.1.0",
"tape": "^5.7.0"
},
"engines": {
"node": ">=8"
}
}

View File

@@ -0,0 +1,321 @@
[
{
"name": "Appcircle",
"constant": "APPCIRCLE",
"env": "AC_APPCIRCLE"
},
{
"name": "AppVeyor",
"constant": "APPVEYOR",
"env": "APPVEYOR",
"pr": "APPVEYOR_PULL_REQUEST_NUMBER"
},
{
"name": "AWS CodeBuild",
"constant": "CODEBUILD",
"env": "CODEBUILD_BUILD_ARN"
},
{
"name": "Azure Pipelines",
"constant": "AZURE_PIPELINES",
"env": "TF_BUILD",
"pr": {
"BUILD_REASON": "PullRequest"
}
},
{
"name": "Bamboo",
"constant": "BAMBOO",
"env": "bamboo_planKey"
},
{
"name": "Bitbucket Pipelines",
"constant": "BITBUCKET",
"env": "BITBUCKET_COMMIT",
"pr": "BITBUCKET_PR_ID"
},
{
"name": "Bitrise",
"constant": "BITRISE",
"env": "BITRISE_IO",
"pr": "BITRISE_PULL_REQUEST"
},
{
"name": "Buddy",
"constant": "BUDDY",
"env": "BUDDY_WORKSPACE_ID",
"pr": "BUDDY_EXECUTION_PULL_REQUEST_ID"
},
{
"name": "Buildkite",
"constant": "BUILDKITE",
"env": "BUILDKITE",
"pr": {
"env": "BUILDKITE_PULL_REQUEST",
"ne": "false"
}
},
{
"name": "CircleCI",
"constant": "CIRCLE",
"env": "CIRCLECI",
"pr": "CIRCLE_PULL_REQUEST"
},
{
"name": "Cirrus CI",
"constant": "CIRRUS",
"env": "CIRRUS_CI",
"pr": "CIRRUS_PR"
},
{
"name": "Codefresh",
"constant": "CODEFRESH",
"env": "CF_BUILD_ID",
"pr": {
"any": [
"CF_PULL_REQUEST_NUMBER",
"CF_PULL_REQUEST_ID"
]
}
},
{
"name": "Codemagic",
"constant": "CODEMAGIC",
"env": "CM_BUILD_ID",
"pr": "CM_PULL_REQUEST"
},
{
"name": "Codeship",
"constant": "CODESHIP",
"env": {
"CI_NAME": "codeship"
}
},
{
"name": "Drone",
"constant": "DRONE",
"env": "DRONE",
"pr": {
"DRONE_BUILD_EVENT": "pull_request"
}
},
{
"name": "dsari",
"constant": "DSARI",
"env": "DSARI"
},
{
"name": "Expo Application Services",
"constant": "EAS",
"env": "EAS_BUILD"
},
{
"name": "Gerrit",
"constant": "GERRIT",
"env": "GERRIT_PROJECT"
},
{
"name": "GitHub Actions",
"constant": "GITHUB_ACTIONS",
"env": "GITHUB_ACTIONS",
"pr": {
"GITHUB_EVENT_NAME": "pull_request"
}
},
{
"name": "GitLab CI",
"constant": "GITLAB",
"env": "GITLAB_CI",
"pr": "CI_MERGE_REQUEST_ID"
},
{
"name": "GoCD",
"constant": "GOCD",
"env": "GO_PIPELINE_LABEL"
},
{
"name": "Google Cloud Build",
"constant": "GOOGLE_CLOUD_BUILD",
"env": "BUILDER_OUTPUT"
},
{
"name": "Harness CI",
"constant": "HARNESS",
"env": "HARNESS_BUILD_ID"
},
{
"name": "Heroku",
"constant": "HEROKU",
"env": {
"env": "NODE",
"includes": "/app/.heroku/node/bin/node"
}
},
{
"name": "Hudson",
"constant": "HUDSON",
"env": "HUDSON_URL"
},
{
"name": "Jenkins",
"constant": "JENKINS",
"env": [
"JENKINS_URL",
"BUILD_ID"
],
"pr": {
"any": [
"ghprbPullId",
"CHANGE_ID"
]
}
},
{
"name": "LayerCI",
"constant": "LAYERCI",
"env": "LAYERCI",
"pr": "LAYERCI_PULL_REQUEST"
},
{
"name": "Magnum CI",
"constant": "MAGNUM",
"env": "MAGNUM"
},
{
"name": "Netlify CI",
"constant": "NETLIFY",
"env": "NETLIFY",
"pr": {
"env": "PULL_REQUEST",
"ne": "false"
}
},
{
"name": "Nevercode",
"constant": "NEVERCODE",
"env": "NEVERCODE",
"pr": {
"env": "NEVERCODE_PULL_REQUEST",
"ne": "false"
}
},
{
"name": "ReleaseHub",
"constant": "RELEASEHUB",
"env": "RELEASE_BUILD_ID"
},
{
"name": "Render",
"constant": "RENDER",
"env": "RENDER",
"pr": {
"IS_PULL_REQUEST": "true"
}
},
{
"name": "Sail CI",
"constant": "SAIL",
"env": "SAILCI",
"pr": "SAIL_PULL_REQUEST_NUMBER"
},
{
"name": "Screwdriver",
"constant": "SCREWDRIVER",
"env": "SCREWDRIVER",
"pr": {
"env": "SD_PULL_REQUEST",
"ne": "false"
}
},
{
"name": "Semaphore",
"constant": "SEMAPHORE",
"env": "SEMAPHORE",
"pr": "PULL_REQUEST_NUMBER"
},
{
"name": "Shippable",
"constant": "SHIPPABLE",
"env": "SHIPPABLE",
"pr": {
"IS_PULL_REQUEST": "true"
}
},
{
"name": "Solano CI",
"constant": "SOLANO",
"env": "TDDIUM",
"pr": "TDDIUM_PR_ID"
},
{
"name": "Sourcehut",
"constant": "SOURCEHUT",
"env": {
"CI_NAME": "sourcehut"
}
},
{
"name": "Strider CD",
"constant": "STRIDER",
"env": "STRIDER"
},
{
"name": "TaskCluster",
"constant": "TASKCLUSTER",
"env": [
"TASK_ID",
"RUN_ID"
]
},
{
"name": "TeamCity",
"constant": "TEAMCITY",
"env": "TEAMCITY_VERSION"
},
{
"name": "Travis CI",
"constant": "TRAVIS",
"env": "TRAVIS",
"pr": {
"env": "TRAVIS_PULL_REQUEST",
"ne": "false"
}
},
{
"name": "Vercel",
"constant": "VERCEL",
"env": {
"any": [
"NOW_BUILDER",
"VERCEL"
]
},
"pr": "VERCEL_GIT_PULL_REQUEST_ID"
},
{
"name": "Visual Studio App Center",
"constant": "APPCENTER",
"env": "APPCENTER_BUILD_ID"
},
{
"name": "Woodpecker",
"constant": "WOODPECKER",
"env": {
"CI": "woodpecker"
},
"pr": {
"CI_BUILD_EVENT": "pull_request"
}
},
{
"name": "Xcode Cloud",
"constant": "XCODE_CLOUD",
"env": "CI_XCODE_PROJECT",
"pr": "CI_PULL_REQUEST_NUMBER"
},
{
"name": "Xcode Server",
"constant": "XCODE_SERVER",
"env": "XCS"
}
]

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Facebook, Inc. and its affiliates.
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,3 @@
# expect
This package exports the `expect` function used in [Jest](https://jestjs.io/). You can find its documentation [on Jest's website](https://jestjs.io/docs/expect).

View File

@@ -0,0 +1,75 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { AsymmetricMatcher as AsymmetricMatcherInterface, MatcherState } from './types';
export declare abstract class AsymmetricMatcher<T, State extends MatcherState = MatcherState> implements AsymmetricMatcherInterface {
protected sample: T;
protected inverse: boolean;
$$typeof: symbol;
constructor(sample: T, inverse?: boolean);
protected getMatcherContext(): State;
abstract asymmetricMatch(other: unknown): boolean;
abstract toString(): string;
getExpectedType?(): string;
toAsymmetricMatcher?(): string;
}
declare class Any extends AsymmetricMatcher<any> {
constructor(sample: unknown);
asymmetricMatch(other: unknown): boolean;
toString(): string;
getExpectedType(): string;
toAsymmetricMatcher(): string;
}
declare class Anything extends AsymmetricMatcher<void> {
asymmetricMatch(other: unknown): boolean;
toString(): string;
toAsymmetricMatcher(): string;
}
declare class ArrayContaining extends AsymmetricMatcher<Array<unknown>> {
constructor(sample: Array<unknown>, inverse?: boolean);
asymmetricMatch(other: Array<unknown>): boolean;
toString(): string;
getExpectedType(): string;
}
declare class ObjectContaining extends AsymmetricMatcher<Record<string, unknown>> {
constructor(sample: Record<string, unknown>, inverse?: boolean);
asymmetricMatch(other: any): boolean;
toString(): string;
getExpectedType(): string;
}
declare class StringContaining extends AsymmetricMatcher<string> {
constructor(sample: string, inverse?: boolean);
asymmetricMatch(other: string): boolean;
toString(): string;
getExpectedType(): string;
}
declare class StringMatching extends AsymmetricMatcher<RegExp> {
constructor(sample: string | RegExp, inverse?: boolean);
asymmetricMatch(other: string): boolean;
toString(): string;
getExpectedType(): string;
}
declare class CloseTo extends AsymmetricMatcher<number> {
private precision;
constructor(sample: number, precision?: number, inverse?: boolean);
asymmetricMatch(other: number): boolean;
toString(): string;
getExpectedType(): string;
}
export declare const any: (expectedObject: unknown) => Any;
export declare const anything: () => Anything;
export declare const arrayContaining: (sample: Array<unknown>) => ArrayContaining;
export declare const arrayNotContaining: (sample: Array<unknown>) => ArrayContaining;
export declare const objectContaining: (sample: Record<string, unknown>) => ObjectContaining;
export declare const objectNotContaining: (sample: Record<string, unknown>) => ObjectContaining;
export declare const stringContaining: (expected: string) => StringContaining;
export declare const stringNotContaining: (expected: string) => StringContaining;
export declare const stringMatching: (expected: string | RegExp) => StringMatching;
export declare const stringNotMatching: (expected: string | RegExp) => StringMatching;
export declare const closeTo: (expected: number, precision?: number | undefined) => CloseTo;
export declare const notCloseTo: (expected: number, precision?: number | undefined) => CloseTo;
export {};

View File

@@ -0,0 +1,432 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.stringNotMatching =
exports.stringNotContaining =
exports.stringMatching =
exports.stringContaining =
exports.objectNotContaining =
exports.objectContaining =
exports.notCloseTo =
exports.closeTo =
exports.arrayNotContaining =
exports.arrayContaining =
exports.anything =
exports.any =
exports.AsymmetricMatcher =
void 0;
var matcherUtils = _interopRequireWildcard(require('jest-matcher-utils'));
var _jasmineUtils = require('./jasmineUtils');
var _jestMatchersObject = require('./jestMatchersObject');
var _utils = require('./utils');
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const utils = Object.freeze({
...matcherUtils,
iterableEquality: _utils.iterableEquality,
subsetEquality: _utils.subsetEquality
});
class AsymmetricMatcher {
constructor(sample, inverse = false) {
_defineProperty(this, '$$typeof', Symbol.for('jest.asymmetricMatcher'));
this.sample = sample;
this.inverse = inverse;
}
getMatcherContext() {
return {
...(0, _jestMatchersObject.getState)(),
equals: _jasmineUtils.equals,
isNot: this.inverse,
utils
};
}
}
exports.AsymmetricMatcher = AsymmetricMatcher;
class Any extends AsymmetricMatcher {
constructor(sample) {
if (typeof sample === 'undefined') {
throw new TypeError(
'any() expects to be passed a constructor function. ' +
'Please pass one or use anything() to match any object.'
);
}
super(sample);
}
asymmetricMatch(other) {
if (this.sample == String) {
return typeof other == 'string' || other instanceof String;
}
if (this.sample == Number) {
return typeof other == 'number' || other instanceof Number;
}
if (this.sample == Function) {
return typeof other == 'function' || other instanceof Function;
}
if (this.sample == Boolean) {
return typeof other == 'boolean' || other instanceof Boolean;
}
if (this.sample == BigInt) {
return typeof other == 'bigint' || other instanceof BigInt;
}
if (this.sample == Symbol) {
return typeof other == 'symbol' || other instanceof Symbol;
}
if (this.sample == Object) {
return typeof other == 'object';
}
return other instanceof this.sample;
}
toString() {
return 'Any';
}
getExpectedType() {
if (this.sample == String) {
return 'string';
}
if (this.sample == Number) {
return 'number';
}
if (this.sample == Function) {
return 'function';
}
if (this.sample == Object) {
return 'object';
}
if (this.sample == Boolean) {
return 'boolean';
}
return (0, _jasmineUtils.fnNameFor)(this.sample);
}
toAsymmetricMatcher() {
return 'Any<' + (0, _jasmineUtils.fnNameFor)(this.sample) + '>';
}
}
class Anything extends AsymmetricMatcher {
asymmetricMatch(other) {
return !(0, _jasmineUtils.isUndefined)(other) && other !== null;
}
toString() {
return 'Anything';
} // No getExpectedType method, because it matches either null or undefined.
toAsymmetricMatcher() {
return 'Anything';
}
}
class ArrayContaining extends AsymmetricMatcher {
constructor(sample, inverse = false) {
super(sample, inverse);
}
asymmetricMatch(other) {
if (!Array.isArray(this.sample)) {
throw new Error(
`You must provide an array to ${this.toString()}, not '` +
typeof this.sample +
"'."
);
}
const result =
this.sample.length === 0 ||
(Array.isArray(other) &&
this.sample.every(item =>
other.some(another => (0, _jasmineUtils.equals)(item, another))
));
return this.inverse ? !result : result;
}
toString() {
return `Array${this.inverse ? 'Not' : ''}Containing`;
}
getExpectedType() {
return 'array';
}
}
class ObjectContaining extends AsymmetricMatcher {
constructor(sample, inverse = false) {
super(sample, inverse);
}
asymmetricMatch(other) {
if (typeof this.sample !== 'object') {
throw new Error(
`You must provide an object to ${this.toString()}, not '` +
typeof this.sample +
"'."
);
}
let result = true;
for (const property in this.sample) {
if (
!(0, _jasmineUtils.hasProperty)(other, property) ||
!(0, _jasmineUtils.equals)(this.sample[property], other[property])
) {
result = false;
break;
}
}
return this.inverse ? !result : result;
}
toString() {
return `Object${this.inverse ? 'Not' : ''}Containing`;
}
getExpectedType() {
return 'object';
}
}
class StringContaining extends AsymmetricMatcher {
constructor(sample, inverse = false) {
if (!(0, _jasmineUtils.isA)('String', sample)) {
throw new Error('Expected is not a string');
}
super(sample, inverse);
}
asymmetricMatch(other) {
const result =
(0, _jasmineUtils.isA)('String', other) && other.includes(this.sample);
return this.inverse ? !result : result;
}
toString() {
return `String${this.inverse ? 'Not' : ''}Containing`;
}
getExpectedType() {
return 'string';
}
}
class StringMatching extends AsymmetricMatcher {
constructor(sample, inverse = false) {
if (
!(0, _jasmineUtils.isA)('String', sample) &&
!(0, _jasmineUtils.isA)('RegExp', sample)
) {
throw new Error('Expected is not a String or a RegExp');
}
super(new RegExp(sample), inverse);
}
asymmetricMatch(other) {
const result =
(0, _jasmineUtils.isA)('String', other) && this.sample.test(other);
return this.inverse ? !result : result;
}
toString() {
return `String${this.inverse ? 'Not' : ''}Matching`;
}
getExpectedType() {
return 'string';
}
}
class CloseTo extends AsymmetricMatcher {
constructor(sample, precision = 2, inverse = false) {
if (!(0, _jasmineUtils.isA)('Number', sample)) {
throw new Error('Expected is not a Number');
}
if (!(0, _jasmineUtils.isA)('Number', precision)) {
throw new Error('Precision is not a Number');
}
super(sample);
_defineProperty(this, 'precision', void 0);
this.inverse = inverse;
this.precision = precision;
}
asymmetricMatch(other) {
if (!(0, _jasmineUtils.isA)('Number', other)) {
return false;
}
let result = false;
if (other === Infinity && this.sample === Infinity) {
result = true; // Infinity - Infinity is NaN
} else if (other === -Infinity && this.sample === -Infinity) {
result = true; // -Infinity - -Infinity is NaN
} else {
result =
Math.abs(this.sample - other) < Math.pow(10, -this.precision) / 2;
}
return this.inverse ? !result : result;
}
toString() {
return `Number${this.inverse ? 'Not' : ''}CloseTo`;
}
getExpectedType() {
return 'number';
}
}
const any = expectedObject => new Any(expectedObject);
exports.any = any;
const anything = () => new Anything();
exports.anything = anything;
const arrayContaining = sample => new ArrayContaining(sample);
exports.arrayContaining = arrayContaining;
const arrayNotContaining = sample => new ArrayContaining(sample, true);
exports.arrayNotContaining = arrayNotContaining;
const objectContaining = sample => new ObjectContaining(sample);
exports.objectContaining = objectContaining;
const objectNotContaining = sample => new ObjectContaining(sample, true);
exports.objectNotContaining = objectNotContaining;
const stringContaining = expected => new StringContaining(expected);
exports.stringContaining = stringContaining;
const stringNotContaining = expected => new StringContaining(expected, true);
exports.stringNotContaining = stringNotContaining;
const stringMatching = expected => new StringMatching(expected);
exports.stringMatching = stringMatching;
const stringNotMatching = expected => new StringMatching(expected, true);
exports.stringNotMatching = stringNotMatching;
const closeTo = (expected, precision) => new CloseTo(expected, precision);
exports.closeTo = closeTo;
const notCloseTo = (expected, precision) =>
new CloseTo(expected, precision, true);
exports.notCloseTo = notCloseTo;

View File

@@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { Expect } from './types';
declare const extractExpectedAssertionsErrors: Expect['extractExpectedAssertionsErrors'];
export default extractExpectedAssertionsErrors;

View File

@@ -0,0 +1,90 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var _jestMatcherUtils = require('jest-matcher-utils');
var _jestMatchersObject = require('./jestMatchersObject');
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
const resetAssertionsLocalState = () => {
(0, _jestMatchersObject.setState)({
assertionCalls: 0,
expectedAssertionsNumber: null,
isExpectingAssertions: false
});
}; // Create and format all errors related to the mismatched number of `expect`
// calls and reset the matcher's state.
const extractExpectedAssertionsErrors = () => {
const result = [];
const {
assertionCalls,
expectedAssertionsNumber,
expectedAssertionsNumberError,
isExpectingAssertions,
isExpectingAssertionsError
} = (0, _jestMatchersObject.getState)();
resetAssertionsLocalState();
if (
typeof expectedAssertionsNumber === 'number' &&
assertionCalls !== expectedAssertionsNumber
) {
const numOfAssertionsExpected = (0, _jestMatcherUtils.EXPECTED_COLOR)(
(0, _jestMatcherUtils.pluralize)('assertion', expectedAssertionsNumber)
);
expectedAssertionsNumberError.message =
(0, _jestMatcherUtils.matcherHint)(
'.assertions',
'',
String(expectedAssertionsNumber),
{
isDirectExpectCall: true
}
) +
'\n\n' +
`Expected ${numOfAssertionsExpected} to be called but received ` +
(0, _jestMatcherUtils.RECEIVED_COLOR)(
(0, _jestMatcherUtils.pluralize)('assertion call', assertionCalls || 0)
) +
'.';
result.push({
actual: assertionCalls.toString(),
error: expectedAssertionsNumberError,
expected: expectedAssertionsNumber.toString()
});
}
if (isExpectingAssertions && assertionCalls === 0) {
const expected = (0, _jestMatcherUtils.EXPECTED_COLOR)(
'at least one assertion'
);
const received = (0, _jestMatcherUtils.RECEIVED_COLOR)('received none');
isExpectingAssertionsError.message =
(0, _jestMatcherUtils.matcherHint)('.hasAssertions', '', '', {
isDirectExpectCall: true
}) +
'\n\n' +
`Expected ${expected} to be called but ${received}.`;
result.push({
actual: 'none',
error: isExpectingAssertionsError,
expected: 'at least one'
});
}
return result;
};
var _default = extractExpectedAssertionsErrors;
exports.default = _default;

View File

@@ -0,0 +1,15 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { Expect, MatcherState as JestMatcherState, Matchers as MatcherInterface } from './types';
declare const expectExport: Expect<JestMatcherState>;
declare namespace expectExport {
type MatcherState = JestMatcherState;
interface Matchers<R, T = unknown> extends MatcherInterface<R, T> {
}
}
export = expectExport;

View File

@@ -0,0 +1,485 @@
'use strict';
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var matcherUtils = _interopRequireWildcard(require('jest-matcher-utils'));
var _asymmetricMatchers = require('./asymmetricMatchers');
var _extractExpectedAssertionsErrors = _interopRequireDefault(
require('./extractExpectedAssertionsErrors')
);
var _jasmineUtils = require('./jasmineUtils');
var _jestMatchersObject = require('./jestMatchersObject');
var _matchers = _interopRequireDefault(require('./matchers'));
var _spyMatchers = _interopRequireDefault(require('./spyMatchers'));
var _toThrowMatchers = _interopRequireWildcard(require('./toThrowMatchers'));
var _utils = require('./utils');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== 'function') return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function (nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interopRequireWildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (key !== 'default' && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Symbol = global['jest-symbol-do-not-touch'] || global.Symbol;
var global = (function () {
if (typeof globalThis !== 'undefined') {
return globalThis;
} else if (typeof global !== 'undefined') {
return global;
} else if (typeof self !== 'undefined') {
return self;
} else if (typeof window !== 'undefined') {
return window;
} else {
return Function('return this')();
}
})();
var Promise = global[Symbol.for('jest-native-promise')] || global.Promise;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
class JestAssertionError extends Error {
constructor(...args) {
super(...args);
_defineProperty(this, 'matcherResult', void 0);
}
}
const isPromise = obj =>
!!obj &&
(typeof obj === 'object' || typeof obj === 'function') &&
typeof obj.then === 'function';
const createToThrowErrorMatchingSnapshotMatcher = function (matcher) {
return function (received, testNameOrInlineSnapshot) {
return matcher.apply(this, [received, testNameOrInlineSnapshot, true]);
};
};
const getPromiseMatcher = (name, matcher) => {
if (name === 'toThrow' || name === 'toThrowError') {
return (0, _toThrowMatchers.createMatcher)(name, true);
} else if (
name === 'toThrowErrorMatchingSnapshot' ||
name === 'toThrowErrorMatchingInlineSnapshot'
) {
return createToThrowErrorMatchingSnapshotMatcher(matcher);
}
return null;
};
const expect = (actual, ...rest) => {
if (rest.length !== 0) {
throw new Error('Expect takes at most one argument.');
}
const allMatchers = (0, _jestMatchersObject.getMatchers)();
const expectation = {
not: {},
rejects: {
not: {}
},
resolves: {
not: {}
}
};
const err = new JestAssertionError();
Object.keys(allMatchers).forEach(name => {
const matcher = allMatchers[name];
const promiseMatcher = getPromiseMatcher(name, matcher) || matcher;
expectation[name] = makeThrowingMatcher(matcher, false, '', actual);
expectation.not[name] = makeThrowingMatcher(matcher, true, '', actual);
expectation.resolves[name] = makeResolveMatcher(
name,
promiseMatcher,
false,
actual,
err
);
expectation.resolves.not[name] = makeResolveMatcher(
name,
promiseMatcher,
true,
actual,
err
);
expectation.rejects[name] = makeRejectMatcher(
name,
promiseMatcher,
false,
actual,
err
);
expectation.rejects.not[name] = makeRejectMatcher(
name,
promiseMatcher,
true,
actual,
err
);
});
return expectation;
};
const getMessage = message =>
(message && message()) ||
matcherUtils.RECEIVED_COLOR('No message was specified for this matcher.');
const makeResolveMatcher =
(matcherName, matcher, isNot, actual, outerErr) =>
(...args) => {
const options = {
isNot,
promise: 'resolves'
};
if (!isPromise(actual)) {
throw new JestAssertionError(
matcherUtils.matcherErrorMessage(
matcherUtils.matcherHint(matcherName, undefined, '', options),
`${matcherUtils.RECEIVED_COLOR('received')} value must be a promise`,
matcherUtils.printWithType(
'Received',
actual,
matcherUtils.printReceived
)
)
);
}
const innerErr = new JestAssertionError();
return actual.then(
result =>
makeThrowingMatcher(matcher, isNot, 'resolves', result, innerErr).apply(
null,
args
),
reason => {
outerErr.message =
matcherUtils.matcherHint(matcherName, undefined, '', options) +
'\n\n' +
'Received promise rejected instead of resolved\n' +
`Rejected to value: ${matcherUtils.printReceived(reason)}`;
return Promise.reject(outerErr);
}
);
};
const makeRejectMatcher =
(matcherName, matcher, isNot, actual, outerErr) =>
(...args) => {
const options = {
isNot,
promise: 'rejects'
};
const actualWrapper = typeof actual === 'function' ? actual() : actual;
if (!isPromise(actualWrapper)) {
throw new JestAssertionError(
matcherUtils.matcherErrorMessage(
matcherUtils.matcherHint(matcherName, undefined, '', options),
`${matcherUtils.RECEIVED_COLOR(
'received'
)} value must be a promise or a function returning a promise`,
matcherUtils.printWithType(
'Received',
actual,
matcherUtils.printReceived
)
)
);
}
const innerErr = new JestAssertionError();
return actualWrapper.then(
result => {
outerErr.message =
matcherUtils.matcherHint(matcherName, undefined, '', options) +
'\n\n' +
'Received promise resolved instead of rejected\n' +
`Resolved to value: ${matcherUtils.printReceived(result)}`;
return Promise.reject(outerErr);
},
reason =>
makeThrowingMatcher(matcher, isNot, 'rejects', reason, innerErr).apply(
null,
args
)
);
};
const makeThrowingMatcher = (matcher, isNot, promise, actual, err) =>
function throwingMatcher(...args) {
let throws = true;
const utils = {
...matcherUtils,
iterableEquality: _utils.iterableEquality,
subsetEquality: _utils.subsetEquality
};
const matcherContext = {
// When throws is disabled, the matcher will not throw errors during test
// execution but instead add them to the global matcher state. If a
// matcher throws, test execution is normally stopped immediately. The
// snapshot matcher uses it because we want to log all snapshot
// failures in a test.
dontThrow: () => (throws = false),
...(0, _jestMatchersObject.getState)(),
equals: _jasmineUtils.equals,
error: err,
isNot,
promise,
utils
};
const processResult = (result, asyncError) => {
_validateResult(result);
(0, _jestMatchersObject.getState)().assertionCalls++;
if ((result.pass && isNot) || (!result.pass && !isNot)) {
// XOR
const message = getMessage(result.message);
let error;
if (err) {
error = err;
error.message = message;
} else if (asyncError) {
error = asyncError;
error.message = message;
} else {
error = new JestAssertionError(message); // Try to remove this function from the stack trace frame.
// Guard for some environments (browsers) that do not support this feature.
if (Error.captureStackTrace) {
Error.captureStackTrace(error, throwingMatcher);
}
} // Passing the result of the matcher with the error so that a custom
// reporter could access the actual and expected objects of the result
// for example in order to display a custom visual diff
error.matcherResult = {...result, message};
if (throws) {
throw error;
} else {
(0, _jestMatchersObject.getState)().suppressedErrors.push(error);
}
}
};
const handleError = error => {
if (
matcher[_jestMatchersObject.INTERNAL_MATCHER_FLAG] === true &&
!(error instanceof JestAssertionError) &&
error.name !== 'PrettyFormatPluginError' && // Guard for some environments (browsers) that do not support this feature.
Error.captureStackTrace
) {
// Try to remove this and deeper functions from the stack trace frame.
Error.captureStackTrace(error, throwingMatcher);
}
throw error;
};
let potentialResult;
try {
potentialResult =
matcher[_jestMatchersObject.INTERNAL_MATCHER_FLAG] === true
? matcher.call(matcherContext, actual, ...args) // It's a trap specifically for inline snapshot to capture this name
: // in the stack trace, so that it can correctly get the custom matcher
// function call.
(function __EXTERNAL_MATCHER_TRAP__() {
return matcher.call(matcherContext, actual, ...args);
})();
if (isPromise(potentialResult)) {
const asyncResult = potentialResult;
const asyncError = new JestAssertionError();
if (Error.captureStackTrace) {
Error.captureStackTrace(asyncError, throwingMatcher);
}
return asyncResult
.then(aResult => processResult(aResult, asyncError))
.catch(handleError);
} else {
const syncResult = potentialResult;
return processResult(syncResult);
}
} catch (error) {
return handleError(error);
}
};
expect.extend = matchers =>
(0, _jestMatchersObject.setMatchers)(matchers, false, expect);
expect.anything = _asymmetricMatchers.anything;
expect.any = _asymmetricMatchers.any;
expect.not = {
arrayContaining: _asymmetricMatchers.arrayNotContaining,
closeTo: _asymmetricMatchers.notCloseTo,
objectContaining: _asymmetricMatchers.objectNotContaining,
stringContaining: _asymmetricMatchers.stringNotContaining,
stringMatching: _asymmetricMatchers.stringNotMatching
};
expect.arrayContaining = _asymmetricMatchers.arrayContaining;
expect.closeTo = _asymmetricMatchers.closeTo;
expect.objectContaining = _asymmetricMatchers.objectContaining;
expect.stringContaining = _asymmetricMatchers.stringContaining;
expect.stringMatching = _asymmetricMatchers.stringMatching;
const _validateResult = result => {
if (
typeof result !== 'object' ||
typeof result.pass !== 'boolean' ||
(result.message &&
typeof result.message !== 'string' &&
typeof result.message !== 'function')
) {
throw new Error(
'Unexpected return from a matcher function.\n' +
'Matcher functions should ' +
'return an object in the following format:\n' +
' {message?: string | function, pass: boolean}\n' +
`'${matcherUtils.stringify(result)}' was returned`
);
}
};
function assertions(expected) {
const error = new Error();
if (Error.captureStackTrace) {
Error.captureStackTrace(error, assertions);
}
(0, _jestMatchersObject.setState)({
expectedAssertionsNumber: expected,
expectedAssertionsNumberError: error
});
}
function hasAssertions(...args) {
const error = new Error();
if (Error.captureStackTrace) {
Error.captureStackTrace(error, hasAssertions);
}
matcherUtils.ensureNoExpected(args[0], '.hasAssertions');
(0, _jestMatchersObject.setState)({
isExpectingAssertions: true,
isExpectingAssertionsError: error
});
} // add default jest matchers
(0, _jestMatchersObject.setMatchers)(_matchers.default, true, expect);
(0, _jestMatchersObject.setMatchers)(_spyMatchers.default, true, expect);
(0, _jestMatchersObject.setMatchers)(_toThrowMatchers.default, true, expect);
expect.addSnapshotSerializer = () => void 0;
expect.assertions = assertions;
expect.hasAssertions = hasAssertions;
expect.getState = _jestMatchersObject.getState;
expect.setState = _jestMatchersObject.setState;
expect.extractExpectedAssertionsErrors =
_extractExpectedAssertionsErrors.default;
const expectExport = expect;
module.exports = expectExport;

View File

@@ -0,0 +1,8 @@
import type { Tester } from './types';
export declare function equals(a: unknown, b: unknown, customTesters?: Array<Tester>, strictCheck?: boolean): boolean;
export declare function isA(typeName: string, value: unknown): boolean;
export declare function fnNameFor(func: Function): string;
export declare function isUndefined(obj: any): boolean;
export declare function hasProperty(obj: object | null, property: string): boolean;
export declare function isImmutableUnorderedKeyed(maybeKeyed: any): boolean;
export declare function isImmutableUnorderedSet(maybeSet: any): boolean;

View File

@@ -0,0 +1,279 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.equals = equals;
exports.fnNameFor = fnNameFor;
exports.hasProperty = hasProperty;
exports.isA = isA;
exports.isImmutableUnorderedKeyed = isImmutableUnorderedKeyed;
exports.isImmutableUnorderedSet = isImmutableUnorderedSet;
exports.isUndefined = isUndefined;
/*
Copyright (c) 2008-2016 Pivotal Labs
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.
*/
/* eslint-disable */
// Extracted out of jasmine 2.5.2
function equals(a, b, customTesters, strictCheck) {
customTesters = customTesters || [];
return eq(a, b, [], [], customTesters, strictCheck ? hasKey : hasDefinedKey);
}
const functionToString = Function.prototype.toString;
function isAsymmetric(obj) {
return !!obj && isA('Function', obj.asymmetricMatch);
}
function asymmetricMatch(a, b) {
var asymmetricA = isAsymmetric(a),
asymmetricB = isAsymmetric(b);
if (asymmetricA && asymmetricB) {
return undefined;
}
if (asymmetricA) {
return a.asymmetricMatch(b);
}
if (asymmetricB) {
return b.asymmetricMatch(a);
}
} // Equality function lovingly adapted from isEqual in
// [Underscore](http://underscorejs.org)
function eq(a, b, aStack, bStack, customTesters, hasKey) {
var result = true;
var asymmetricResult = asymmetricMatch(a, b);
if (asymmetricResult !== undefined) {
return asymmetricResult;
}
for (var i = 0; i < customTesters.length; i++) {
var customTesterResult = customTesters[i](a, b);
if (customTesterResult !== undefined) {
return customTesterResult;
}
}
if (a instanceof Error && b instanceof Error) {
return a.message == b.message;
}
if (Object.is(a, b)) {
return true;
} // A strict comparison is necessary because `null == undefined`.
if (a === null || b === null) {
return a === b;
}
var className = Object.prototype.toString.call(a);
if (className != Object.prototype.toString.call(b)) {
return false;
}
switch (className) {
case '[object Boolean]':
case '[object String]':
case '[object Number]':
if (typeof a !== typeof b) {
// One is a primitive, one a `new Primitive()`
return false;
} else if (typeof a !== 'object' && typeof b !== 'object') {
// both are proper primitives
return Object.is(a, b);
} else {
// both are `new Primitive()`s
return Object.is(a.valueOf(), b.valueOf());
}
case '[object Date]':
// Coerce dates to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source === b.source && a.flags === b.flags;
}
if (typeof a !== 'object' || typeof b !== 'object') {
return false;
} // Use DOM3 method isEqualNode (IE>=9)
if (isDomNode(a) && isDomNode(b)) {
return a.isEqualNode(b);
} // Used to detect circular references.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
// circular references at same depth are equal
// circular reference is not equal to non-circular one
if (aStack[length] === a) {
return bStack[length] === b;
} else if (bStack[length] === b) {
return false;
}
} // Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b); // Recursively compare objects and arrays.
// Compare array lengths to determine if a deep comparison is necessary.
if (className == '[object Array]' && a.length !== b.length) {
return false;
} // Deep compare objects.
var aKeys = keys(a, hasKey),
key;
var size = aKeys.length; // Ensure that both objects contain the same number of properties before comparing deep equality.
if (keys(b, hasKey).length !== size) {
return false;
}
while (size--) {
key = aKeys[size]; // Deep compare each member
result =
hasKey(b, key) &&
eq(a[key], b[key], aStack, bStack, customTesters, hasKey);
if (!result) {
return false;
}
} // Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
}
function keys(obj, hasKey) {
var keys = [];
for (var key in obj) {
if (hasKey(obj, key)) {
keys.push(key);
}
}
return keys.concat(
Object.getOwnPropertySymbols(obj).filter(
symbol => Object.getOwnPropertyDescriptor(obj, symbol).enumerable
)
);
}
function hasDefinedKey(obj, key) {
return hasKey(obj, key) && obj[key] !== undefined;
}
function hasKey(obj, key) {
return Object.prototype.hasOwnProperty.call(obj, key);
}
function isA(typeName, value) {
return Object.prototype.toString.apply(value) === '[object ' + typeName + ']';
}
function isDomNode(obj) {
return (
obj !== null &&
typeof obj === 'object' &&
typeof obj.nodeType === 'number' &&
typeof obj.nodeName === 'string' &&
typeof obj.isEqualNode === 'function'
);
}
function fnNameFor(func) {
if (func.name) {
return func.name;
}
const matches = functionToString
.call(func)
.match(/^(?:async)?\s*function\s*\*?\s*([\w$]+)\s*\(/);
return matches ? matches[1] : '<anonymous>';
}
function isUndefined(obj) {
return obj === void 0;
}
function getPrototype(obj) {
if (Object.getPrototypeOf) {
return Object.getPrototypeOf(obj);
}
if (obj.constructor.prototype == obj) {
return null;
}
return obj.constructor.prototype;
}
function hasProperty(obj, property) {
if (!obj) {
return false;
}
if (Object.prototype.hasOwnProperty.call(obj, property)) {
return true;
}
return hasProperty(getPrototype(obj), property);
} // SENTINEL constants are from https://github.com/facebook/immutable-js
const IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
const IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@';
const IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';
function isImmutableUnorderedKeyed(maybeKeyed) {
return !!(
maybeKeyed &&
maybeKeyed[IS_KEYED_SENTINEL] &&
!maybeKeyed[IS_ORDERED_SENTINEL]
);
}
function isImmutableUnorderedSet(maybeSet) {
return !!(
maybeSet &&
maybeSet[IS_SET_SENTINEL] &&
!maybeSet[IS_ORDERED_SENTINEL]
);
}

View File

@@ -0,0 +1,13 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import type { Expect, MatcherState, MatchersObject } from './types';
export declare const INTERNAL_MATCHER_FLAG: unique symbol;
export declare const getState: <State extends MatcherState = MatcherState>() => State;
export declare const setState: <State extends MatcherState = MatcherState>(state: Partial<State>) => void;
export declare const getMatchers: <State extends MatcherState = MatcherState>() => MatchersObject<State>;
export declare const setMatchers: <State extends MatcherState = MatcherState>(matchers: MatchersObject<State>, isInternal: boolean, expect: Expect) => void;

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