Add Robot_JoyIt driver

This commit is contained in:
2026-01-17 16:50:07 +01:00
parent e9e50acf5f
commit 0cfb4d5a95
15848 changed files with 570836 additions and 268976 deletions

1
node_modules/@jest/console/LICENSE generated vendored
View File

@@ -1,6 +1,7 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Copyright Contributors to the Jest project.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -1,197 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _assert() {
const data = require('assert');
_assert = function () {
return data;
};
return data;
}
function _console() {
const data = require('console');
_console = function () {
return data;
};
return data;
}
function _util() {
const data = require('util');
_util = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class BufferedConsole extends _console().Console {
_buffer = [];
_counters = {};
_timers = {};
_groupDepth = 0;
Console = _console().Console;
constructor() {
super({
write: message => {
BufferedConsole.write(this._buffer, 'log', message, null);
return true;
}
});
}
static write(buffer, type, message, level) {
const stackLevel = level != null ? level : 2;
const rawStack = new (_jestUtil().ErrorWithStack)(
undefined,
BufferedConsole.write
).stack;
(0, _jestUtil().invariant)(rawStack != null, 'always have a stack trace');
const origin = rawStack
.split('\n')
.slice(stackLevel)
.filter(Boolean)
.join('\n');
buffer.push({
message,
origin,
type
});
return buffer;
}
_log(type, message) {
BufferedConsole.write(
this._buffer,
type,
' '.repeat(this._groupDepth) + message,
3
);
}
assert(value, message) {
try {
(0, _assert().strict)(value, message);
} catch (error) {
if (!(error instanceof _assert().AssertionError)) {
throw error;
}
// https://github.com/jestjs/jest/pull/13422#issuecomment-1273396392
this._log('assert', error.toString().replace(/:\n\n.*\n/gs, ''));
}
}
count(label = 'default') {
if (!this._counters[label]) {
this._counters[label] = 0;
}
this._log(
'count',
(0, _util().format)(`${label}: ${++this._counters[label]}`)
);
}
countReset(label = 'default') {
this._counters[label] = 0;
}
debug(firstArg, ...rest) {
this._log('debug', (0, _util().format)(firstArg, ...rest));
}
dir(firstArg, options = {}) {
const representation = (0, _util().inspect)(firstArg, options);
this._log('dir', (0, _util().formatWithOptions)(options, representation));
}
dirxml(firstArg, ...rest) {
this._log('dirxml', (0, _util().format)(firstArg, ...rest));
}
error(firstArg, ...rest) {
this._log('error', (0, _util().format)(firstArg, ...rest));
}
group(title, ...rest) {
this._groupDepth++;
if (title != null || rest.length > 0) {
this._log(
'group',
_chalk().default.bold((0, _util().format)(title, ...rest))
);
}
}
groupCollapsed(title, ...rest) {
this._groupDepth++;
if (title != null || rest.length > 0) {
this._log(
'groupCollapsed',
_chalk().default.bold((0, _util().format)(title, ...rest))
);
}
}
groupEnd() {
if (this._groupDepth > 0) {
this._groupDepth--;
}
}
info(firstArg, ...rest) {
this._log('info', (0, _util().format)(firstArg, ...rest));
}
log(firstArg, ...rest) {
this._log('log', (0, _util().format)(firstArg, ...rest));
}
time(label = 'default') {
if (this._timers[label] != null) {
return;
}
this._timers[label] = new Date();
}
timeEnd(label = 'default') {
const startTime = this._timers[label];
if (startTime != null) {
const endTime = new Date();
const time = endTime.getTime() - startTime.getTime();
this._log(
'time',
(0, _util().format)(`${label}: ${(0, _jestUtil().formatTime)(time)}`)
);
delete this._timers[label];
}
}
timeLog(label = 'default', ...data) {
const startTime = this._timers[label];
if (startTime != null) {
const endTime = new Date();
const time = endTime.getTime() - startTime.getTime();
this._log(
'time',
(0, _util().format)(
`${label}: ${(0, _jestUtil().formatTime)(time)}`,
...data
)
);
}
}
warn(firstArg, ...rest) {
this._log('warn', (0, _util().format)(firstArg, ...rest));
}
getBuffer() {
return this._buffer.length ? this._buffer : undefined;
}
}
exports.default = BufferedConsole;

View File

@@ -1,182 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _assert() {
const data = require('assert');
_assert = function () {
return data;
};
return data;
}
function _console() {
const data = require('console');
_console = function () {
return data;
};
return data;
}
function _util() {
const data = require('util');
_util = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class CustomConsole extends _console().Console {
_stdout;
_stderr;
_formatBuffer;
_counters = {};
_timers = {};
_groupDepth = 0;
Console = _console().Console;
constructor(stdout, stderr, formatBuffer = (_type, message) => message) {
super(stdout, stderr);
this._stdout = stdout;
this._stderr = stderr;
this._formatBuffer = formatBuffer;
}
_log(type, message) {
(0, _jestUtil().clearLine)(this._stdout);
super.log(
this._formatBuffer(type, ' '.repeat(this._groupDepth) + message)
);
}
_logError(type, message) {
(0, _jestUtil().clearLine)(this._stderr);
super.error(
this._formatBuffer(type, ' '.repeat(this._groupDepth) + message)
);
}
assert(value, message) {
try {
(0, _assert().strict)(value, message);
} catch (error) {
if (!(error instanceof _assert().AssertionError)) {
throw error;
}
// https://github.com/jestjs/jest/pull/13422#issuecomment-1273396392
this._logError('assert', error.toString().replace(/:\n\n.*\n/gs, ''));
}
}
count(label = 'default') {
if (!this._counters[label]) {
this._counters[label] = 0;
}
this._log(
'count',
(0, _util().format)(`${label}: ${++this._counters[label]}`)
);
}
countReset(label = 'default') {
this._counters[label] = 0;
}
debug(firstArg, ...args) {
this._log('debug', (0, _util().format)(firstArg, ...args));
}
dir(firstArg, options = {}) {
const representation = (0, _util().inspect)(firstArg, options);
this._log('dir', (0, _util().formatWithOptions)(options, representation));
}
dirxml(firstArg, ...args) {
this._log('dirxml', (0, _util().format)(firstArg, ...args));
}
error(firstArg, ...args) {
this._logError('error', (0, _util().format)(firstArg, ...args));
}
group(title, ...args) {
this._groupDepth++;
if (title != null || args.length > 0) {
this._log(
'group',
_chalk().default.bold((0, _util().format)(title, ...args))
);
}
}
groupCollapsed(title, ...args) {
this._groupDepth++;
if (title != null || args.length > 0) {
this._log(
'groupCollapsed',
_chalk().default.bold((0, _util().format)(title, ...args))
);
}
}
groupEnd() {
if (this._groupDepth > 0) {
this._groupDepth--;
}
}
info(firstArg, ...args) {
this._log('info', (0, _util().format)(firstArg, ...args));
}
log(firstArg, ...args) {
this._log('log', (0, _util().format)(firstArg, ...args));
}
time(label = 'default') {
if (this._timers[label] != null) {
return;
}
this._timers[label] = new Date();
}
timeEnd(label = 'default') {
const startTime = this._timers[label];
if (startTime != null) {
const endTime = new Date().getTime();
const time = endTime - startTime.getTime();
this._log(
'time',
(0, _util().format)(`${label}: ${(0, _jestUtil().formatTime)(time)}`)
);
delete this._timers[label];
}
}
timeLog(label = 'default', ...data) {
const startTime = this._timers[label];
if (startTime != null) {
const endTime = new Date();
const time = endTime.getTime() - startTime.getTime();
this._log(
'time',
(0, _util().format)(
`${label}: ${(0, _jestUtil().formatTime)(time)}`,
...data
)
);
}
}
warn(firstArg, ...args) {
this._logError('warn', (0, _util().format)(firstArg, ...args));
}
getBuffer() {
return undefined;
}
}
exports.default = CustomConsole;

View File

@@ -1,35 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var _CustomConsole = _interopRequireDefault(require('./CustomConsole'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/* eslint-disable @typescript-eslint/no-empty-function */
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class NullConsole extends _CustomConsole.default {
assert() {}
debug() {}
dir() {}
error() {}
info() {}
log() {}
time() {}
timeEnd() {}
timeLog() {}
trace() {}
warn() {}
group() {}
groupCollapsed() {}
groupEnd() {}
}
exports.default = NullConsole;

View File

@@ -1,70 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getConsoleOutput;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestMessageUtil() {
const data = require('jest-message-util');
_jestMessageUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getConsoleOutput(buffer, config, globalConfig) {
const TITLE_INDENT =
globalConfig.verbose === true ? ' '.repeat(2) : ' '.repeat(4);
const CONSOLE_INDENT = TITLE_INDENT + ' '.repeat(2);
const logEntries = buffer.reduce((output, {type, message, origin}) => {
message = message
.split(/\n/)
.map(line => CONSOLE_INDENT + line)
.join('\n');
let typeMessage = `console.${type}`;
let noStackTrace = true;
let noCodeFrame = true;
if (type === 'warn') {
message = _chalk().default.yellow(message);
typeMessage = _chalk().default.yellow(typeMessage);
noStackTrace = globalConfig?.noStackTrace ?? false;
noCodeFrame = false;
} else if (type === 'error') {
message = _chalk().default.red(message);
typeMessage = _chalk().default.red(typeMessage);
noStackTrace = globalConfig?.noStackTrace ?? false;
noCodeFrame = false;
}
const options = {
noCodeFrame,
noStackTrace
};
const formattedStackTrace = (0, _jestMessageUtil().formatStackTrace)(
origin,
config,
options
);
return `${
output + TITLE_INDENT + _chalk().default.dim(typeMessage)
}\n${message.trimRight()}\n${_chalk().default.dim(
formattedStackTrace.trimRight()
)}\n\n`;
}, '');
return `${logEntries.trimRight()}\n`;
}

105
node_modules/@jest/console/build/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,105 @@
import { Console } from "console";
import { InspectOptions } from "util";
import { StackTraceConfig } from "jest-message-util";
import { WriteStream } from "tty";
import { Config } from "@jest/types";
//#region src/types.d.ts
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
type LogMessage = string;
type LogEntry = {
message: LogMessage;
origin: string;
type: LogType;
};
type LogType = 'assert' | 'count' | 'debug' | 'dir' | 'dirxml' | 'error' | 'group' | 'groupCollapsed' | 'info' | 'log' | 'time' | 'warn';
type ConsoleBuffer = Array<LogEntry>;
//#endregion
//#region src/BufferedConsole.d.ts
declare class BufferedConsole extends Console {
private readonly _buffer;
private _counters;
private _timers;
private _groupDepth;
Console: typeof Console;
constructor();
static write(this: void, buffer: ConsoleBuffer, type: LogType, message: LogMessage, stackLevel?: number): ConsoleBuffer;
private _log;
assert(value: unknown, message?: string | Error): void;
count(label?: string): void;
countReset(label?: string): void;
debug(firstArg: unknown, ...rest: Array<unknown>): void;
dir(firstArg: unknown, options?: InspectOptions): void;
dirxml(firstArg: unknown, ...rest: Array<unknown>): void;
error(firstArg: unknown, ...rest: Array<unknown>): void;
group(title?: string, ...rest: Array<unknown>): void;
groupCollapsed(title?: string, ...rest: Array<unknown>): void;
groupEnd(): void;
info(firstArg: unknown, ...rest: Array<unknown>): void;
log(firstArg: unknown, ...rest: Array<unknown>): void;
time(label?: string): void;
timeEnd(label?: string): void;
timeLog(label?: string, ...data: Array<unknown>): void;
warn(firstArg: unknown, ...rest: Array<unknown>): void;
getBuffer(): ConsoleBuffer | undefined;
}
//#endregion
//#region src/CustomConsole.d.ts
type Formatter = (type: LogType, message: LogMessage) => string;
declare class CustomConsole extends Console {
private readonly _stdout;
private readonly _stderr;
private readonly _formatBuffer;
private _counters;
private _timers;
private _groupDepth;
Console: typeof Console;
constructor(stdout: WriteStream, stderr: WriteStream, formatBuffer?: Formatter);
private _log;
private _logError;
assert(value: unknown, message?: string | Error): asserts value;
count(label?: string): void;
countReset(label?: string): void;
debug(firstArg: unknown, ...args: Array<unknown>): void;
dir(firstArg: unknown, options?: InspectOptions): void;
dirxml(firstArg: unknown, ...args: Array<unknown>): void;
error(firstArg: unknown, ...args: Array<unknown>): void;
group(title?: string, ...args: Array<unknown>): void;
groupCollapsed(title?: string, ...args: Array<unknown>): void;
groupEnd(): void;
info(firstArg: unknown, ...args: Array<unknown>): void;
log(firstArg: unknown, ...args: Array<unknown>): void;
time(label?: string): void;
timeEnd(label?: string): void;
timeLog(label?: string, ...data: Array<unknown>): void;
warn(firstArg: unknown, ...args: Array<unknown>): void;
getBuffer(): undefined;
}
//#endregion
//#region src/NullConsole.d.ts
declare class NullConsole extends CustomConsole {
assert(): void;
debug(): void;
dir(): void;
error(): void;
info(): void;
log(): void;
time(): void;
timeEnd(): void;
timeLog(): void;
trace(): void;
warn(): void;
group(): void;
groupCollapsed(): void;
groupEnd(): void;
}
//#endregion
//#region src/getConsoleOutput.d.ts
declare function getConsoleOutput(buffer: ConsoleBuffer, config: StackTraceConfig, globalConfig: Config.GlobalConfig): string;
//#endregion
export { BufferedConsole, ConsoleBuffer, CustomConsole, LogEntry, LogMessage, LogType, NullConsole, getConsoleOutput };

View File

@@ -4,11 +4,11 @@
* 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 {Config} from '@jest/types';
import {Console as Console_2} from 'console';
import {WriteStream} from 'tty';
import {InspectOptions} from 'util';
import {Config} from '@jest/types';
import {StackTraceConfig} from 'jest-message-util';
export declare class BufferedConsole extends Console_2 {
@@ -23,7 +23,7 @@ export declare class BufferedConsole extends Console_2 {
buffer: ConsoleBuffer,
type: LogType,
message: LogMessage,
level?: number | null,
stackLevel?: number,
): ConsoleBuffer;
private _log;
assert(value: unknown, message?: string | Error): void;
@@ -56,8 +56,8 @@ export declare class CustomConsole extends Console_2 {
private _groupDepth;
Console: typeof Console_2;
constructor(
stdout: NodeJS.WriteStream,
stderr: NodeJS.WriteStream,
stdout: WriteStream,
stderr: WriteStream,
formatBuffer?: Formatter,
);
private _log;

View File

@@ -1,36 +1,521 @@
'use strict';
/*!
* /**
* * Copyright (c) Meta Platforms, Inc. and affiliates.
* *
* * This source code is licensed under the MIT license found in the
* * LICENSE file in the root directory of this source tree.
* * /
*/
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
Object.defineProperty(exports, '__esModule', {
/***/ "./src/BufferedConsole.ts":
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({
value: true
});
Object.defineProperty(exports, 'BufferedConsole', {
}));
exports["default"] = void 0;
function _assert() {
const data = require("assert");
_assert = function () {
return data;
};
return data;
}
function _console() {
const data = require("console");
_console = function () {
return data;
};
return data;
}
function _util() {
const data = require("util");
_util = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require("chalk"));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require("jest-util");
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class BufferedConsole extends _console().Console {
_buffer = [];
_counters = {};
_timers = {};
_groupDepth = 0;
Console = _console().Console;
constructor() {
super({
write: message => {
BufferedConsole.write(this._buffer, 'log', message);
return true;
}
});
}
static write(buffer, type, message, stackLevel = 2) {
const rawStack = new (_jestUtil().ErrorWithStack)(undefined, BufferedConsole.write).stack;
(0, _jestUtil().invariant)(rawStack != null, 'always have a stack trace');
const origin = rawStack.split('\n').slice(stackLevel).filter(Boolean).join('\n');
buffer.push({
message,
origin,
type
});
return buffer;
}
_log(type, message) {
BufferedConsole.write(this._buffer, type, ' '.repeat(this._groupDepth) + message, 3);
}
assert(value, message) {
try {
_assert().strict.ok(value, message);
} catch (error) {
if (!(error instanceof _assert().AssertionError)) {
throw error;
}
// https://github.com/jestjs/jest/pull/13422#issuecomment-1273396392
this._log('assert', error.toString().replaceAll(/:\n\n.*\n/gs, ''));
}
}
count(label = 'default') {
if (!this._counters[label]) {
this._counters[label] = 0;
}
this._log('count', (0, _util().format)(`${label}: ${++this._counters[label]}`));
}
countReset(label = 'default') {
this._counters[label] = 0;
}
debug(firstArg, ...rest) {
this._log('debug', (0, _util().format)(firstArg, ...rest));
}
dir(firstArg, options = {}) {
const representation = (0, _util().inspect)(firstArg, options);
this._log('dir', (0, _util().formatWithOptions)(options, representation));
}
dirxml(firstArg, ...rest) {
this._log('dirxml', (0, _util().format)(firstArg, ...rest));
}
error(firstArg, ...rest) {
this._log('error', (0, _util().format)(firstArg, ...rest));
}
group(title, ...rest) {
this._groupDepth++;
if (title != null || rest.length > 0) {
this._log('group', _chalk().default.bold((0, _util().format)(title, ...rest)));
}
}
groupCollapsed(title, ...rest) {
this._groupDepth++;
if (title != null || rest.length > 0) {
this._log('groupCollapsed', _chalk().default.bold((0, _util().format)(title, ...rest)));
}
}
groupEnd() {
if (this._groupDepth > 0) {
this._groupDepth--;
}
}
info(firstArg, ...rest) {
this._log('info', (0, _util().format)(firstArg, ...rest));
}
log(firstArg, ...rest) {
this._log('log', (0, _util().format)(firstArg, ...rest));
}
time(label = 'default') {
if (this._timers[label] != null) {
return;
}
this._timers[label] = new Date();
}
timeEnd(label = 'default') {
const startTime = this._timers[label];
if (startTime != null) {
const endTime = new Date();
const time = endTime.getTime() - startTime.getTime();
this._log('time', (0, _util().format)(`${label}: ${(0, _jestUtil().formatTime)(time)}`));
delete this._timers[label];
}
}
timeLog(label = 'default', ...data) {
const startTime = this._timers[label];
if (startTime != null) {
const endTime = new Date();
const time = endTime.getTime() - startTime.getTime();
this._log('time', (0, _util().format)(`${label}: ${(0, _jestUtil().formatTime)(time)}`, ...data));
}
}
warn(firstArg, ...rest) {
this._log('warn', (0, _util().format)(firstArg, ...rest));
}
getBuffer() {
return this._buffer.length > 0 ? this._buffer : undefined;
}
}
exports["default"] = BufferedConsole;
/***/ }),
/***/ "./src/CustomConsole.ts":
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
function _assert() {
const data = require("assert");
_assert = function () {
return data;
};
return data;
}
function _console() {
const data = require("console");
_console = function () {
return data;
};
return data;
}
function _util() {
const data = require("util");
_util = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require("chalk"));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require("jest-util");
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class CustomConsole extends _console().Console {
_stdout;
_stderr;
_formatBuffer;
_counters = {};
_timers = {};
_groupDepth = 0;
Console = _console().Console;
constructor(stdout, stderr, formatBuffer = (_type, message) => message) {
super(stdout, stderr);
this._stdout = stdout;
this._stderr = stderr;
this._formatBuffer = formatBuffer;
}
_log(type, message) {
(0, _jestUtil().clearLine)(this._stdout);
super.log(this._formatBuffer(type, ' '.repeat(this._groupDepth) + message));
}
_logError(type, message) {
(0, _jestUtil().clearLine)(this._stderr);
super.error(this._formatBuffer(type, ' '.repeat(this._groupDepth) + message));
}
assert(value, message) {
try {
_assert().strict.ok(value, message);
} catch (error) {
if (!(error instanceof _assert().AssertionError)) {
throw error;
}
// https://github.com/jestjs/jest/pull/13422#issuecomment-1273396392
this._logError('assert', error.toString().replaceAll(/:\n\n.*\n/gs, ''));
}
}
count(label = 'default') {
if (!this._counters[label]) {
this._counters[label] = 0;
}
this._log('count', (0, _util().format)(`${label}: ${++this._counters[label]}`));
}
countReset(label = 'default') {
this._counters[label] = 0;
}
debug(firstArg, ...args) {
this._log('debug', (0, _util().format)(firstArg, ...args));
}
dir(firstArg, options = {}) {
const representation = (0, _util().inspect)(firstArg, options);
this._log('dir', (0, _util().formatWithOptions)(options, representation));
}
dirxml(firstArg, ...args) {
this._log('dirxml', (0, _util().format)(firstArg, ...args));
}
error(firstArg, ...args) {
this._logError('error', (0, _util().format)(firstArg, ...args));
}
group(title, ...args) {
this._groupDepth++;
if (title != null || args.length > 0) {
this._log('group', _chalk().default.bold((0, _util().format)(title, ...args)));
}
}
groupCollapsed(title, ...args) {
this._groupDepth++;
if (title != null || args.length > 0) {
this._log('groupCollapsed', _chalk().default.bold((0, _util().format)(title, ...args)));
}
}
groupEnd() {
if (this._groupDepth > 0) {
this._groupDepth--;
}
}
info(firstArg, ...args) {
this._log('info', (0, _util().format)(firstArg, ...args));
}
log(firstArg, ...args) {
this._log('log', (0, _util().format)(firstArg, ...args));
}
time(label = 'default') {
if (this._timers[label] != null) {
return;
}
this._timers[label] = new Date();
}
timeEnd(label = 'default') {
const startTime = this._timers[label];
if (startTime != null) {
const endTime = Date.now();
const time = endTime - startTime.getTime();
this._log('time', (0, _util().format)(`${label}: ${(0, _jestUtil().formatTime)(time)}`));
delete this._timers[label];
}
}
timeLog(label = 'default', ...data) {
const startTime = this._timers[label];
if (startTime != null) {
const endTime = new Date();
const time = endTime.getTime() - startTime.getTime();
this._log('time', (0, _util().format)(`${label}: ${(0, _jestUtil().formatTime)(time)}`, ...data));
}
}
warn(firstArg, ...args) {
this._logError('warn', (0, _util().format)(firstArg, ...args));
}
getBuffer() {
return undefined;
}
}
exports["default"] = CustomConsole;
/***/ }),
/***/ "./src/NullConsole.ts":
/***/ ((__unused_webpack_module, exports, __webpack_require__) => {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = void 0;
var _CustomConsole = _interopRequireDefault(__webpack_require__("./src/CustomConsole.ts"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/* eslint-disable @typescript-eslint/no-empty-function */
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class NullConsole extends _CustomConsole.default {
assert() {}
debug() {}
dir() {}
error() {}
info() {}
log() {}
time() {}
timeEnd() {}
timeLog() {}
trace() {}
warn() {}
group() {}
groupCollapsed() {}
groupEnd() {}
}
exports["default"] = NullConsole;
/***/ }),
/***/ "./src/getConsoleOutput.ts":
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports["default"] = getConsoleOutput;
function _chalk() {
const data = _interopRequireDefault(require("chalk"));
_chalk = function () {
return data;
};
return data;
}
function _jestMessageUtil() {
const data = require("jest-message-util");
_jestMessageUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getConsoleOutput(buffer, config, globalConfig) {
const TITLE_INDENT = globalConfig.verbose === true ? ' '.repeat(2) : ' '.repeat(4);
const CONSOLE_INDENT = TITLE_INDENT + ' '.repeat(2);
const logEntries = buffer.reduce((output, {
type,
message,
origin
}) => {
message = message.split(/\n/).map(line => CONSOLE_INDENT + line).join('\n');
let typeMessage = `console.${type}`;
let noStackTrace = true;
let noCodeFrame = true;
if (type === 'warn') {
message = _chalk().default.yellow(message);
typeMessage = _chalk().default.yellow(typeMessage);
noStackTrace = globalConfig?.noStackTrace ?? false;
noCodeFrame = false;
} else if (type === 'error') {
message = _chalk().default.red(message);
typeMessage = _chalk().default.red(typeMessage);
noStackTrace = globalConfig?.noStackTrace ?? false;
noCodeFrame = false;
}
const options = {
noCodeFrame,
noStackTrace
};
const formattedStackTrace = (0, _jestMessageUtil().formatStackTrace)(origin, config, options);
return `${output + TITLE_INDENT + _chalk().default.dim(typeMessage)}\n${message.trimEnd()}\n${_chalk().default.dim(formattedStackTrace.trimEnd())}\n\n`;
}, '');
return `${logEntries.trimEnd()}\n`;
}
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
(() => {
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({
value: true
}));
Object.defineProperty(exports, "BufferedConsole", ({
enumerable: true,
get: function () {
return _BufferedConsole.default;
}
});
Object.defineProperty(exports, 'CustomConsole', {
}));
Object.defineProperty(exports, "CustomConsole", ({
enumerable: true,
get: function () {
return _CustomConsole.default;
}
});
Object.defineProperty(exports, 'NullConsole', {
}));
Object.defineProperty(exports, "NullConsole", ({
enumerable: true,
get: function () {
return _NullConsole.default;
}
});
Object.defineProperty(exports, 'getConsoleOutput', {
}));
Object.defineProperty(exports, "getConsoleOutput", ({
enumerable: true,
get: function () {
return _getConsoleOutput.default;
}
});
var _BufferedConsole = _interopRequireDefault(require('./BufferedConsole'));
var _CustomConsole = _interopRequireDefault(require('./CustomConsole'));
var _NullConsole = _interopRequireDefault(require('./NullConsole'));
var _getConsoleOutput = _interopRequireDefault(require('./getConsoleOutput'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
}));
var _BufferedConsole = _interopRequireDefault(__webpack_require__("./src/BufferedConsole.ts"));
var _CustomConsole = _interopRequireDefault(__webpack_require__("./src/CustomConsole.ts"));
var _NullConsole = _interopRequireDefault(__webpack_require__("./src/NullConsole.ts"));
var _getConsoleOutput = _interopRequireDefault(__webpack_require__("./src/getConsoleOutput.ts"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
})();
module.exports = __webpack_exports__;
/******/ })()
;

6
node_modules/@jest/console/build/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import cjsModule from './index.js';
export const BufferedConsole = cjsModule.BufferedConsole;
export const CustomConsole = cjsModule.CustomConsole;
export const NullConsole = cjsModule.NullConsole;
export const getConsoleOutput = cjsModule.getConsoleOutput;

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@jest/console",
"version": "29.7.0",
"version": "30.2.0",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
@@ -12,26 +12,28 @@
"exports": {
".": {
"types": "./build/index.d.ts",
"require": "./build/index.js",
"import": "./build/index.mjs",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@jest/types": "^29.6.3",
"@jest/types": "30.2.0",
"@types/node": "*",
"chalk": "^4.0.0",
"jest-message-util": "^29.7.0",
"jest-util": "^29.7.0",
"chalk": "^4.1.2",
"jest-message-util": "30.2.0",
"jest-util": "30.2.0",
"slash": "^3.0.0"
},
"devDependencies": {
"@jest/test-utils": "^29.7.0"
"@jest/test-utils": "30.2.0"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "4e56991693da7cd4c3730dc3579a1dd1403ee630"
"gitHead": "855864e3f9751366455246790be2bf912d4d0dac"
}

1
node_modules/@jest/core/LICENSE generated vendored
View File

@@ -1,6 +1,7 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Copyright Contributors to the Jest project.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -1,46 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class FailedTestsCache {
_enabledTestsMap;
filterTests(tests) {
const enabledTestsMap = this._enabledTestsMap;
if (!enabledTestsMap) {
return tests;
}
return tests.filter(testResult => enabledTestsMap[testResult.path]);
}
setTestResults(testResults) {
this._enabledTestsMap = (testResults || []).reduce(
(suiteMap, testResult) => {
if (!testResult.numFailingTests) {
return suiteMap;
}
suiteMap[testResult.testFilePath] = testResult.testResults.reduce(
(testMap, test) => {
if (test.status !== 'failed') {
return testMap;
}
testMap[test.fullName] = true;
return testMap;
},
{}
);
return suiteMap;
},
{}
);
this._enabledTestsMap = Object.freeze(this._enabledTestsMap);
}
}
exports.default = FailedTestsCache;

View File

@@ -1,195 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _ansiEscapes() {
const data = _interopRequireDefault(require('ansi-escapes'));
_ansiEscapes = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const {ARROW, CLEAR} = _jestUtil().specialChars;
function describeKey(key, description) {
return `${_chalk().default.dim(
`${ARROW}Press`
)} ${key} ${_chalk().default.dim(description)}`;
}
const TestProgressLabel = _chalk().default.bold('Interactive Test Progress');
class FailedTestsInteractiveMode {
_isActive = false;
_countPaths = 0;
_skippedNum = 0;
_testAssertions = [];
_updateTestRunnerConfig;
constructor(_pipe) {
this._pipe = _pipe;
}
isActive() {
return this._isActive;
}
put(key) {
switch (key) {
case 's':
if (this._skippedNum === this._testAssertions.length) {
break;
}
this._skippedNum += 1;
// move skipped test to the end
this._testAssertions.push(this._testAssertions.shift());
if (this._testAssertions.length - this._skippedNum > 0) {
this._run();
} else {
this._drawUIDoneWithSkipped();
}
break;
case 'q':
case _jestWatcher().KEYS.ESCAPE:
this.abort();
break;
case 'r':
this.restart();
break;
case _jestWatcher().KEYS.ENTER:
if (this._testAssertions.length === 0) {
this.abort();
} else {
this._run();
}
break;
default:
}
}
run(failedTestAssertions, updateConfig) {
if (failedTestAssertions.length === 0) return;
this._testAssertions = [...failedTestAssertions];
this._countPaths = this._testAssertions.length;
this._updateTestRunnerConfig = updateConfig;
this._isActive = true;
this._run();
}
updateWithResults(results) {
if (!results.snapshot.failure && results.numFailedTests > 0) {
return this._drawUIOverlay();
}
this._testAssertions.shift();
if (this._testAssertions.length === 0) {
return this._drawUIOverlay();
}
// Go to the next test
return this._run();
}
_clearTestSummary() {
this._pipe.write(_ansiEscapes().default.cursorUp(6));
this._pipe.write(_ansiEscapes().default.eraseDown);
}
_drawUIDone() {
this._pipe.write(CLEAR);
const messages = [
_chalk().default.bold('Watch Usage'),
describeKey('Enter', 'to return to watch mode.')
];
this._pipe.write(`${messages.join('\n')}\n`);
}
_drawUIDoneWithSkipped() {
this._pipe.write(CLEAR);
let stats = `${(0, _jestUtil().pluralize)(
'test',
this._countPaths
)} reviewed`;
if (this._skippedNum > 0) {
const skippedText = _chalk().default.bold.yellow(
`${(0, _jestUtil().pluralize)('test', this._skippedNum)} skipped`
);
stats = `${stats}, ${skippedText}`;
}
const message = [
TestProgressLabel,
`${ARROW}${stats}`,
'\n',
_chalk().default.bold('Watch Usage'),
describeKey('r', 'to restart Interactive Mode.'),
describeKey('q', 'to quit Interactive Mode.'),
describeKey('Enter', 'to return to watch mode.')
];
this._pipe.write(`\n${message.join('\n')}`);
}
_drawUIProgress() {
this._clearTestSummary();
const numPass = this._countPaths - this._testAssertions.length;
const numRemaining = this._countPaths - numPass - this._skippedNum;
let stats = `${(0, _jestUtil().pluralize)('test', numRemaining)} remaining`;
if (this._skippedNum > 0) {
const skippedText = _chalk().default.bold.yellow(
`${(0, _jestUtil().pluralize)('test', this._skippedNum)} skipped`
);
stats = `${stats}, ${skippedText}`;
}
const message = [
TestProgressLabel,
`${ARROW}${stats}`,
'\n',
_chalk().default.bold('Watch Usage'),
describeKey('s', 'to skip the current test.'),
describeKey('q', 'to quit Interactive Mode.'),
describeKey('Enter', 'to return to watch mode.')
];
this._pipe.write(`\n${message.join('\n')}`);
}
_drawUIOverlay() {
if (this._testAssertions.length === 0) return this._drawUIDone();
return this._drawUIProgress();
}
_run() {
if (this._updateTestRunnerConfig) {
this._updateTestRunnerConfig(this._testAssertions[0]);
}
}
abort() {
this._isActive = false;
this._skippedNum = 0;
if (this._updateTestRunnerConfig) {
this._updateTestRunnerConfig();
}
}
restart() {
this._skippedNum = 0;
this._countPaths = this._testAssertions.length;
this._run();
}
}
exports.default = FailedTestsInteractiveMode;

View File

@@ -1,87 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class ReporterDispatcher {
_reporters;
constructor() {
this._reporters = [];
}
register(reporter) {
this._reporters.push(reporter);
}
unregister(reporterConstructor) {
this._reporters = this._reporters.filter(
reporter => !(reporter instanceof reporterConstructor)
);
}
async onTestFileResult(test, testResult, results) {
for (const reporter of this._reporters) {
if (reporter.onTestFileResult) {
await reporter.onTestFileResult(test, testResult, results);
} else if (reporter.onTestResult) {
await reporter.onTestResult(test, testResult, results);
}
}
// Release memory if unused later.
testResult.coverage = undefined;
testResult.console = undefined;
}
async onTestFileStart(test) {
for (const reporter of this._reporters) {
if (reporter.onTestFileStart) {
await reporter.onTestFileStart(test);
} else if (reporter.onTestStart) {
await reporter.onTestStart(test);
}
}
}
async onRunStart(results, options) {
for (const reporter of this._reporters) {
reporter.onRunStart && (await reporter.onRunStart(results, options));
}
}
async onTestCaseStart(test, testCaseStartInfo) {
for (const reporter of this._reporters) {
if (reporter.onTestCaseStart) {
await reporter.onTestCaseStart(test, testCaseStartInfo);
}
}
}
async onTestCaseResult(test, testCaseResult) {
for (const reporter of this._reporters) {
if (reporter.onTestCaseResult) {
await reporter.onTestCaseResult(test, testCaseResult);
}
}
}
async onRunComplete(testContexts, results) {
for (const reporter of this._reporters) {
if (reporter.onRunComplete) {
await reporter.onRunComplete(testContexts, results);
}
}
}
// Return a list of last errors for every reporter
getErrors() {
return this._reporters.reduce((list, reporter) => {
const error = reporter.getLastError && reporter.getLastError();
return error ? list.concat(error) : list;
}, []);
}
hasErrors() {
return this.getErrors().length !== 0;
}
}
exports.default = ReporterDispatcher;

View File

@@ -1,408 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function os() {
const data = _interopRequireWildcard(require('os'));
os = function () {
return data;
};
return data;
}
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function _micromatch() {
const data = _interopRequireDefault(require('micromatch'));
_micromatch = function () {
return data;
};
return data;
}
function _jestConfig() {
const data = require('jest-config');
_jestConfig = function () {
return data;
};
return data;
}
function _jestRegexUtil() {
const data = require('jest-regex-util');
_jestRegexUtil = function () {
return data;
};
return data;
}
function _jestResolveDependencies() {
const data = require('jest-resolve-dependencies');
_jestResolveDependencies = function () {
return data;
};
return data;
}
function _jestSnapshot() {
const data = require('jest-snapshot');
_jestSnapshot = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const regexToMatcher = testRegex => {
const regexes = testRegex.map(testRegex => new RegExp(testRegex));
return path =>
regexes.some(regex => {
const result = regex.test(path);
// prevent stateful regexes from breaking, just in case
regex.lastIndex = 0;
return result;
});
};
const toTests = (context, tests) =>
tests.map(path => ({
context,
duration: undefined,
path
}));
const hasSCM = changedFilesInfo => {
const {repos} = changedFilesInfo;
// no SCM (git/hg/...) is found in any of the roots.
const noSCM = Object.values(repos).every(scm => scm.size === 0);
return !noSCM;
};
class SearchSource {
_context;
_dependencyResolver;
_testPathCases = [];
constructor(context) {
const {config} = context;
this._context = context;
this._dependencyResolver = null;
const rootPattern = new RegExp(
config.roots
.map(dir => (0, _jestRegexUtil().escapePathForRegex)(dir + path().sep))
.join('|')
);
this._testPathCases.push({
isMatch: path => rootPattern.test(path),
stat: 'roots'
});
if (config.testMatch.length) {
this._testPathCases.push({
isMatch: (0, _jestUtil().globsToMatcher)(config.testMatch),
stat: 'testMatch'
});
}
if (config.testPathIgnorePatterns.length) {
const testIgnorePatternsRegex = new RegExp(
config.testPathIgnorePatterns.join('|')
);
this._testPathCases.push({
isMatch: path => !testIgnorePatternsRegex.test(path),
stat: 'testPathIgnorePatterns'
});
}
if (config.testRegex.length) {
this._testPathCases.push({
isMatch: regexToMatcher(config.testRegex),
stat: 'testRegex'
});
}
}
async _getOrBuildDependencyResolver() {
if (!this._dependencyResolver) {
this._dependencyResolver =
new (_jestResolveDependencies().DependencyResolver)(
this._context.resolver,
this._context.hasteFS,
await (0, _jestSnapshot().buildSnapshotResolver)(this._context.config)
);
}
return this._dependencyResolver;
}
_filterTestPathsWithStats(allPaths, testPathPattern) {
const data = {
stats: {
roots: 0,
testMatch: 0,
testPathIgnorePatterns: 0,
testRegex: 0
},
tests: [],
total: allPaths.length
};
const testCases = Array.from(this._testPathCases); // clone
if (testPathPattern) {
const regex = (0, _jestUtil().testPathPatternToRegExp)(testPathPattern);
testCases.push({
isMatch: path => regex.test(path),
stat: 'testPathPattern'
});
data.stats.testPathPattern = 0;
}
data.tests = allPaths.filter(test => {
let filterResult = true;
for (const {isMatch, stat} of testCases) {
if (isMatch(test.path)) {
data.stats[stat]++;
} else {
filterResult = false;
}
}
return filterResult;
});
return data;
}
_getAllTestPaths(testPathPattern) {
return this._filterTestPathsWithStats(
toTests(this._context, this._context.hasteFS.getAllFiles()),
testPathPattern
);
}
isTestFilePath(path) {
return this._testPathCases.every(testCase => testCase.isMatch(path));
}
findMatchingTests(testPathPattern) {
return this._getAllTestPaths(testPathPattern);
}
async findRelatedTests(allPaths, collectCoverage) {
const dependencyResolver = await this._getOrBuildDependencyResolver();
if (!collectCoverage) {
return {
tests: toTests(
this._context,
dependencyResolver.resolveInverse(
allPaths,
this.isTestFilePath.bind(this),
{
skipNodeResolution: this._context.config.skipNodeResolution
}
)
)
};
}
const testModulesMap = dependencyResolver.resolveInverseModuleMap(
allPaths,
this.isTestFilePath.bind(this),
{
skipNodeResolution: this._context.config.skipNodeResolution
}
);
const allPathsAbsolute = Array.from(allPaths).map(p => path().resolve(p));
const collectCoverageFrom = new Set();
testModulesMap.forEach(testModule => {
if (!testModule.dependencies) {
return;
}
testModule.dependencies.forEach(p => {
if (!allPathsAbsolute.includes(p)) {
return;
}
const filename = (0, _jestConfig().replaceRootDirInPath)(
this._context.config.rootDir,
p
);
collectCoverageFrom.add(
path().isAbsolute(filename)
? path().relative(this._context.config.rootDir, filename)
: filename
);
});
});
return {
collectCoverageFrom,
tests: toTests(
this._context,
testModulesMap.map(testModule => testModule.file)
)
};
}
findTestsByPaths(paths) {
return {
tests: toTests(
this._context,
paths
.map(p => path().resolve(this._context.config.cwd, p))
.filter(this.isTestFilePath.bind(this))
)
};
}
async findRelatedTestsFromPattern(paths, collectCoverage) {
if (Array.isArray(paths) && paths.length) {
const resolvedPaths = paths.map(p =>
path().resolve(this._context.config.cwd, p)
);
return this.findRelatedTests(new Set(resolvedPaths), collectCoverage);
}
return {
tests: []
};
}
async findTestRelatedToChangedFiles(changedFilesInfo, collectCoverage) {
if (!hasSCM(changedFilesInfo)) {
return {
noSCM: true,
tests: []
};
}
const {changedFiles} = changedFilesInfo;
return this.findRelatedTests(changedFiles, collectCoverage);
}
async _getTestPaths(globalConfig, changedFiles) {
if (globalConfig.onlyChanged) {
if (!changedFiles) {
throw new Error('Changed files must be set when running with -o.');
}
return this.findTestRelatedToChangedFiles(
changedFiles,
globalConfig.collectCoverage
);
}
let paths = globalConfig.nonFlagArgs;
if (globalConfig.findRelatedTests && 'win32' === os().platform()) {
paths = this.filterPathsWin32(paths);
}
if (globalConfig.runTestsByPath && paths && paths.length) {
return this.findTestsByPaths(paths);
} else if (globalConfig.findRelatedTests && paths && paths.length) {
return this.findRelatedTestsFromPattern(
paths,
globalConfig.collectCoverage
);
} else if (globalConfig.testPathPattern != null) {
return this.findMatchingTests(globalConfig.testPathPattern);
} else {
return {
tests: []
};
}
}
filterPathsWin32(paths) {
const allFiles = this._context.hasteFS.getAllFiles();
const options = {
nocase: true,
windows: false
};
function normalizePosix(filePath) {
return filePath.replace(/\\/g, '/');
}
paths = paths
.map(p => {
// micromatch works with forward slashes: https://github.com/micromatch/micromatch#backslashes
const normalizedPath = normalizePosix(
path().resolve(this._context.config.cwd, p)
);
const match = (0, _micromatch().default)(
allFiles.map(normalizePosix),
normalizedPath,
options
);
return match[0];
})
.filter(Boolean)
.map(p => path().resolve(p));
return paths;
}
async getTestPaths(globalConfig, changedFiles, filter) {
const searchResult = await this._getTestPaths(globalConfig, changedFiles);
const filterPath = globalConfig.filter;
if (filter) {
const tests = searchResult.tests;
const filterResult = await filter(tests.map(test => test.path));
if (!Array.isArray(filterResult.filtered)) {
throw new Error(
`Filter ${filterPath} did not return a valid test list`
);
}
const filteredSet = new Set(
filterResult.filtered.map(result => result.test)
);
return {
...searchResult,
tests: tests.filter(test => filteredSet.has(test.path))
};
}
return searchResult;
}
async findRelatedSourcesFromTestsInChangedFiles(changedFilesInfo) {
if (!hasSCM(changedFilesInfo)) {
return [];
}
const {changedFiles} = changedFilesInfo;
const dependencyResolver = await this._getOrBuildDependencyResolver();
const relatedSourcesSet = new Set();
changedFiles.forEach(filePath => {
if (this.isTestFilePath(filePath)) {
const sourcePaths = dependencyResolver.resolve(filePath, {
skipNodeResolution: this._context.config.skipNodeResolution
});
sourcePaths.forEach(sourcePath => relatedSourcesSet.add(sourcePath));
}
});
return Array.from(relatedSourcesSet);
}
}
exports.default = SearchSource;

View File

@@ -1,238 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _ansiEscapes() {
const data = _interopRequireDefault(require('ansi-escapes'));
_ansiEscapes = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const {ARROW, CLEAR} = _jestUtil().specialChars;
class SnapshotInteractiveMode {
_pipe;
_isActive;
_updateTestRunnerConfig;
_testAssertions;
_countPaths;
_skippedNum;
constructor(pipe) {
this._pipe = pipe;
this._isActive = false;
this._skippedNum = 0;
}
isActive() {
return this._isActive;
}
getSkippedNum() {
return this._skippedNum;
}
_clearTestSummary() {
this._pipe.write(_ansiEscapes().default.cursorUp(6));
this._pipe.write(_ansiEscapes().default.eraseDown);
}
_drawUIProgress() {
this._clearTestSummary();
const numPass = this._countPaths - this._testAssertions.length;
const numRemaining = this._countPaths - numPass - this._skippedNum;
let stats = _chalk().default.bold.dim(
`${(0, _jestUtil().pluralize)('snapshot', numRemaining)} remaining`
);
if (numPass) {
stats += `, ${_chalk().default.bold.green(
`${(0, _jestUtil().pluralize)('snapshot', numPass)} updated`
)}`;
}
if (this._skippedNum) {
stats += `, ${_chalk().default.bold.yellow(
`${(0, _jestUtil().pluralize)('snapshot', this._skippedNum)} skipped`
)}`;
}
const messages = [
`\n${_chalk().default.bold('Interactive Snapshot Progress')}`,
ARROW + stats,
`\n${_chalk().default.bold('Watch Usage')}`,
`${_chalk().default.dim(`${ARROW}Press `)}u${_chalk().default.dim(
' to update failing snapshots for this test.'
)}`,
`${_chalk().default.dim(`${ARROW}Press `)}s${_chalk().default.dim(
' to skip the current test.'
)}`,
`${_chalk().default.dim(`${ARROW}Press `)}q${_chalk().default.dim(
' to quit Interactive Snapshot Mode.'
)}`,
`${_chalk().default.dim(`${ARROW}Press `)}Enter${_chalk().default.dim(
' to trigger a test run.'
)}`
];
this._pipe.write(`${messages.filter(Boolean).join('\n')}\n`);
}
_drawUIDoneWithSkipped() {
this._pipe.write(CLEAR);
const numPass = this._countPaths - this._testAssertions.length;
let stats = _chalk().default.bold.dim(
`${(0, _jestUtil().pluralize)('snapshot', this._countPaths)} reviewed`
);
if (numPass) {
stats += `, ${_chalk().default.bold.green(
`${(0, _jestUtil().pluralize)('snapshot', numPass)} updated`
)}`;
}
if (this._skippedNum) {
stats += `, ${_chalk().default.bold.yellow(
`${(0, _jestUtil().pluralize)('snapshot', this._skippedNum)} skipped`
)}`;
}
const messages = [
`\n${_chalk().default.bold('Interactive Snapshot Result')}`,
ARROW + stats,
`\n${_chalk().default.bold('Watch Usage')}`,
`${_chalk().default.dim(`${ARROW}Press `)}r${_chalk().default.dim(
' to restart Interactive Snapshot Mode.'
)}`,
`${_chalk().default.dim(`${ARROW}Press `)}q${_chalk().default.dim(
' to quit Interactive Snapshot Mode.'
)}`
];
this._pipe.write(`${messages.filter(Boolean).join('\n')}\n`);
}
_drawUIDone() {
this._pipe.write(CLEAR);
const numPass = this._countPaths - this._testAssertions.length;
let stats = _chalk().default.bold.dim(
`${(0, _jestUtil().pluralize)('snapshot', this._countPaths)} reviewed`
);
if (numPass) {
stats += `, ${_chalk().default.bold.green(
`${(0, _jestUtil().pluralize)('snapshot', numPass)} updated`
)}`;
}
const messages = [
`\n${_chalk().default.bold('Interactive Snapshot Result')}`,
ARROW + stats,
`\n${_chalk().default.bold('Watch Usage')}`,
`${_chalk().default.dim(`${ARROW}Press `)}Enter${_chalk().default.dim(
' to return to watch mode.'
)}`
];
this._pipe.write(`${messages.filter(Boolean).join('\n')}\n`);
}
_drawUIOverlay() {
if (this._testAssertions.length === 0) {
return this._drawUIDone();
}
if (this._testAssertions.length - this._skippedNum === 0) {
return this._drawUIDoneWithSkipped();
}
return this._drawUIProgress();
}
put(key) {
switch (key) {
case 's':
if (this._skippedNum === this._testAssertions.length) break;
this._skippedNum += 1;
// move skipped test to the end
this._testAssertions.push(this._testAssertions.shift());
if (this._testAssertions.length - this._skippedNum > 0) {
this._run(false);
} else {
this._drawUIDoneWithSkipped();
}
break;
case 'u':
this._run(true);
break;
case 'q':
case _jestWatcher().KEYS.ESCAPE:
this.abort();
break;
case 'r':
this.restart();
break;
case _jestWatcher().KEYS.ENTER:
if (this._testAssertions.length === 0) {
this.abort();
} else {
this._run(false);
}
break;
default:
break;
}
}
abort() {
this._isActive = false;
this._skippedNum = 0;
this._updateTestRunnerConfig(null, false);
}
restart() {
this._skippedNum = 0;
this._countPaths = this._testAssertions.length;
this._run(false);
}
updateWithResults(results) {
const hasSnapshotFailure = !!results.snapshot.failure;
if (hasSnapshotFailure) {
this._drawUIOverlay();
return;
}
this._testAssertions.shift();
if (this._testAssertions.length - this._skippedNum === 0) {
this._drawUIOverlay();
return;
}
// Go to the next test
this._run(false);
}
_run(shouldUpdateSnapshot) {
const testAssertion = this._testAssertions[0];
this._updateTestRunnerConfig(testAssertion, shouldUpdateSnapshot);
}
run(failedSnapshotTestAssertions, onConfigChange) {
if (!failedSnapshotTestAssertions.length) {
return;
}
this._testAssertions = [...failedSnapshotTestAssertions];
this._countPaths = this._testAssertions.length;
this._updateTestRunnerConfig = onConfigChange;
this._isActive = true;
this._run(false);
}
}
exports.default = SnapshotInteractiveMode;

View File

@@ -1,39 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class TestNamePatternPrompt extends _jestWatcher().PatternPrompt {
constructor(pipe, prompt) {
super(pipe, prompt, 'tests');
}
_onChange(pattern, options) {
super._onChange(pattern, options);
this._printPrompt(pattern);
}
_printPrompt(pattern) {
const pipe = this._pipe;
(0, _jestWatcher().printPatternCaret)(pattern, pipe);
(0, _jestWatcher().printRestoredPatternCaret)(
pattern,
this._currentUsageRows,
pipe
);
}
}
exports.default = TestNamePatternPrompt;

View File

@@ -1,39 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class TestPathPatternPrompt extends _jestWatcher().PatternPrompt {
constructor(pipe, prompt) {
super(pipe, prompt, 'filenames');
}
_onChange(pattern, options) {
super._onChange(pattern, options);
this._printPrompt(pattern);
}
_printPrompt(pattern) {
const pipe = this._pipe;
(0, _jestWatcher().printPatternCaret)(pattern, pipe);
(0, _jestWatcher().printRestoredPatternCaret)(
pattern,
this._currentUsageRows,
pipe
);
}
}
exports.default = TestPathPatternPrompt;

View File

@@ -1,463 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.createTestScheduler = createTestScheduler;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _ciInfo() {
const data = require('ci-info');
_ciInfo = function () {
return data;
};
return data;
}
function _exit() {
const data = _interopRequireDefault(require('exit'));
_exit = function () {
return data;
};
return data;
}
function _reporters() {
const data = require('@jest/reporters');
_reporters = function () {
return data;
};
return data;
}
function _testResult() {
const data = require('@jest/test-result');
_testResult = function () {
return data;
};
return data;
}
function _transform() {
const data = require('@jest/transform');
_transform = function () {
return data;
};
return data;
}
function _jestMessageUtil() {
const data = require('jest-message-util');
_jestMessageUtil = function () {
return data;
};
return data;
}
function _jestSnapshot() {
const data = require('jest-snapshot');
_jestSnapshot = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
var _ReporterDispatcher = _interopRequireDefault(
require('./ReporterDispatcher')
);
var _testSchedulerHelper = require('./testSchedulerHelper');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
async function createTestScheduler(globalConfig, context) {
const scheduler = new TestScheduler(globalConfig, context);
await scheduler._setupReporters();
return scheduler;
}
class TestScheduler {
_context;
_dispatcher;
_globalConfig;
constructor(globalConfig, context) {
this._context = context;
this._dispatcher = new _ReporterDispatcher.default();
this._globalConfig = globalConfig;
}
addReporter(reporter) {
this._dispatcher.register(reporter);
}
removeReporter(reporterConstructor) {
this._dispatcher.unregister(reporterConstructor);
}
async scheduleTests(tests, watcher) {
const onTestFileStart = this._dispatcher.onTestFileStart.bind(
this._dispatcher
);
const timings = [];
const testContexts = new Set();
tests.forEach(test => {
testContexts.add(test.context);
if (test.duration) {
timings.push(test.duration);
}
});
const aggregatedResults = createAggregatedResults(tests.length);
const estimatedTime = Math.ceil(
getEstimatedTime(timings, this._globalConfig.maxWorkers) / 1000
);
const runInBand = (0, _testSchedulerHelper.shouldRunInBand)(
tests,
timings,
this._globalConfig
);
const onResult = async (test, testResult) => {
if (watcher.isInterrupted()) {
return Promise.resolve();
}
if (testResult.testResults.length === 0) {
const message = 'Your test suite must contain at least one test.';
return onFailure(test, {
message,
stack: new Error(message).stack
});
}
// Throws when the context is leaked after executing a test.
if (testResult.leaks) {
const message =
`${_chalk().default.red.bold(
'EXPERIMENTAL FEATURE!\n'
)}Your test suite is leaking memory. Please ensure all references are cleaned.\n` +
'\n' +
'There is a number of things that can leak memory:\n' +
' - Async operations that have not finished (e.g. fs.readFile).\n' +
' - Timers not properly mocked (e.g. setInterval, setTimeout).\n' +
' - Keeping references to the global scope.';
return onFailure(test, {
message,
stack: new Error(message).stack
});
}
(0, _testResult().addResult)(aggregatedResults, testResult);
await this._dispatcher.onTestFileResult(
test,
testResult,
aggregatedResults
);
return this._bailIfNeeded(testContexts, aggregatedResults, watcher);
};
const onFailure = async (test, error) => {
if (watcher.isInterrupted()) {
return;
}
const testResult = (0, _testResult().buildFailureTestResult)(
test.path,
error
);
testResult.failureMessage = (0, _jestMessageUtil().formatExecError)(
testResult.testExecError,
test.context.config,
this._globalConfig,
test.path
);
(0, _testResult().addResult)(aggregatedResults, testResult);
await this._dispatcher.onTestFileResult(
test,
testResult,
aggregatedResults
);
};
const updateSnapshotState = async () => {
const contextsWithSnapshotResolvers = await Promise.all(
Array.from(testContexts).map(async context => [
context,
await (0, _jestSnapshot().buildSnapshotResolver)(context.config)
])
);
contextsWithSnapshotResolvers.forEach(([context, snapshotResolver]) => {
const status = (0, _jestSnapshot().cleanup)(
context.hasteFS,
this._globalConfig.updateSnapshot,
snapshotResolver,
context.config.testPathIgnorePatterns
);
aggregatedResults.snapshot.filesRemoved += status.filesRemoved;
aggregatedResults.snapshot.filesRemovedList = (
aggregatedResults.snapshot.filesRemovedList || []
).concat(status.filesRemovedList);
});
const updateAll = this._globalConfig.updateSnapshot === 'all';
aggregatedResults.snapshot.didUpdate = updateAll;
aggregatedResults.snapshot.failure = !!(
!updateAll &&
(aggregatedResults.snapshot.unchecked ||
aggregatedResults.snapshot.unmatched ||
aggregatedResults.snapshot.filesRemoved)
);
};
await this._dispatcher.onRunStart(aggregatedResults, {
estimatedTime,
showStatus: !runInBand
});
const testRunners = Object.create(null);
const contextsByTestRunner = new WeakMap();
try {
await Promise.all(
Array.from(testContexts).map(async context => {
const {config} = context;
if (!testRunners[config.runner]) {
const transformer = await (0, _transform().createScriptTransformer)(
config
);
const Runner = await transformer.requireAndTranspileModule(
config.runner
);
const runner = new Runner(this._globalConfig, {
changedFiles: this._context.changedFiles,
sourcesRelatedToTestsInChangedFiles:
this._context.sourcesRelatedToTestsInChangedFiles
});
testRunners[config.runner] = runner;
contextsByTestRunner.set(runner, context);
}
})
);
const testsByRunner = this._partitionTests(testRunners, tests);
if (testsByRunner) {
try {
for (const runner of Object.keys(testRunners)) {
const testRunner = testRunners[runner];
const context = contextsByTestRunner.get(testRunner);
(0, _jestUtil().invariant)(context);
const tests = testsByRunner[runner];
const testRunnerOptions = {
serial: runInBand || Boolean(testRunner.isSerial)
};
if (testRunner.supportsEventEmitters) {
const unsubscribes = [
testRunner.on('test-file-start', ([test]) =>
onTestFileStart(test)
),
testRunner.on('test-file-success', ([test, testResult]) =>
onResult(test, testResult)
),
testRunner.on('test-file-failure', ([test, error]) =>
onFailure(test, error)
),
testRunner.on(
'test-case-start',
([testPath, testCaseStartInfo]) => {
const test = {
context,
path: testPath
};
this._dispatcher.onTestCaseStart(test, testCaseStartInfo);
}
),
testRunner.on(
'test-case-result',
([testPath, testCaseResult]) => {
const test = {
context,
path: testPath
};
this._dispatcher.onTestCaseResult(test, testCaseResult);
}
)
];
await testRunner.runTests(tests, watcher, testRunnerOptions);
unsubscribes.forEach(sub => sub());
} else {
await testRunner.runTests(
tests,
watcher,
onTestFileStart,
onResult,
onFailure,
testRunnerOptions
);
}
}
} catch (error) {
if (!watcher.isInterrupted()) {
throw error;
}
}
}
} catch (error) {
aggregatedResults.runExecError = buildExecError(error);
await this._dispatcher.onRunComplete(testContexts, aggregatedResults);
throw error;
}
await updateSnapshotState();
aggregatedResults.wasInterrupted = watcher.isInterrupted();
await this._dispatcher.onRunComplete(testContexts, aggregatedResults);
const anyTestFailures = !(
aggregatedResults.numFailedTests === 0 &&
aggregatedResults.numRuntimeErrorTestSuites === 0
);
const anyReporterErrors = this._dispatcher.hasErrors();
aggregatedResults.success = !(
anyTestFailures ||
aggregatedResults.snapshot.failure ||
anyReporterErrors
);
return aggregatedResults;
}
_partitionTests(testRunners, tests) {
if (Object.keys(testRunners).length > 1) {
return tests.reduce((testRuns, test) => {
const runner = test.context.config.runner;
if (!testRuns[runner]) {
testRuns[runner] = [];
}
testRuns[runner].push(test);
return testRuns;
}, Object.create(null));
} else if (tests.length > 0 && tests[0] != null) {
// If there is only one runner, don't partition the tests.
return Object.assign(Object.create(null), {
[tests[0].context.config.runner]: tests
});
} else {
return null;
}
}
async _setupReporters() {
const {collectCoverage: coverage, notify, verbose} = this._globalConfig;
const reporters = this._globalConfig.reporters || [['default', {}]];
let summaryOptions = null;
for (const [reporter, options] of reporters) {
switch (reporter) {
case 'default':
summaryOptions = options;
verbose
? this.addReporter(
new (_reporters().VerboseReporter)(this._globalConfig)
)
: this.addReporter(
new (_reporters().DefaultReporter)(this._globalConfig)
);
break;
case 'github-actions':
_ciInfo().GITHUB_ACTIONS &&
this.addReporter(
new (_reporters().GitHubActionsReporter)(
this._globalConfig,
options
)
);
break;
case 'summary':
summaryOptions = options;
break;
default:
await this._addCustomReporter(reporter, options);
}
}
if (notify) {
this.addReporter(
new (_reporters().NotifyReporter)(this._globalConfig, this._context)
);
}
if (coverage) {
this.addReporter(
new (_reporters().CoverageReporter)(this._globalConfig, this._context)
);
}
if (summaryOptions != null) {
this.addReporter(
new (_reporters().SummaryReporter)(this._globalConfig, summaryOptions)
);
}
}
async _addCustomReporter(reporter, options) {
try {
const Reporter = await (0, _jestUtil().requireOrImportModule)(reporter);
this.addReporter(
new Reporter(this._globalConfig, options, this._context)
);
} catch (error) {
error.message = `An error occurred while adding the reporter at path "${_chalk().default.bold(
reporter
)}".\n${error instanceof Error ? error.message : ''}`;
throw error;
}
}
async _bailIfNeeded(testContexts, aggregatedResults, watcher) {
if (
this._globalConfig.bail !== 0 &&
aggregatedResults.numFailedTests >= this._globalConfig.bail
) {
if (watcher.isWatchMode()) {
await watcher.setState({
interrupted: true
});
return;
}
try {
await this._dispatcher.onRunComplete(testContexts, aggregatedResults);
} finally {
const exitCode = this._globalConfig.testFailureExitCode;
(0, _exit().default)(exitCode);
}
}
}
}
const createAggregatedResults = numTotalTestSuites => {
const result = (0, _testResult().makeEmptyAggregatedTestResult)();
result.numTotalTestSuites = numTotalTestSuites;
result.startTime = Date.now();
result.success = false;
return result;
};
const getEstimatedTime = (timings, workers) => {
if (timings.length === 0) {
return 0;
}
const max = Math.max(...timings);
return timings.length <= workers
? max
: Math.max(timings.reduce((sum, time) => sum + time) / workers, max);
};
const strToError = errString => {
const {message, stack} = (0, _jestMessageUtil().separateMessageFromStack)(
errString
);
if (stack.length > 0) {
return {
message,
stack
};
}
const error = new (_jestUtil().ErrorWithStack)(message, buildExecError);
return {
message,
stack: error.stack || ''
};
};
const buildExecError = err => {
if (typeof err === 'string' || err == null) {
return strToError(err || 'Error');
}
const anyErr = err;
if (typeof anyErr.message === 'string') {
if (typeof anyErr.stack === 'string' && anyErr.stack.length > 0) {
return anyErr;
}
return strToError(anyErr.message);
}
return strToError(JSON.stringify(err));
};

View File

@@ -1,417 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.runCLI = runCLI;
function _perf_hooks() {
const data = require('perf_hooks');
_perf_hooks = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _exit() {
const data = _interopRequireDefault(require('exit'));
_exit = function () {
return data;
};
return data;
}
function fs() {
const data = _interopRequireWildcard(require('graceful-fs'));
fs = function () {
return data;
};
return data;
}
function _console() {
const data = require('@jest/console');
_console = function () {
return data;
};
return data;
}
function _jestConfig() {
const data = require('jest-config');
_jestConfig = function () {
return data;
};
return data;
}
function _jestRuntime() {
const data = _interopRequireDefault(require('jest-runtime'));
_jestRuntime = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
var _collectHandles = require('../collectHandles');
var _getChangedFilesPromise = _interopRequireDefault(
require('../getChangedFilesPromise')
);
var _getConfigsOfProjectsToRun = _interopRequireDefault(
require('../getConfigsOfProjectsToRun')
);
var _getProjectNamesMissingWarning = _interopRequireDefault(
require('../getProjectNamesMissingWarning')
);
var _getSelectProjectsMessage = _interopRequireDefault(
require('../getSelectProjectsMessage')
);
var _createContext = _interopRequireDefault(require('../lib/createContext'));
var _handleDeprecationWarnings = _interopRequireDefault(
require('../lib/handleDeprecationWarnings')
);
var _logDebugMessages = _interopRequireDefault(
require('../lib/logDebugMessages')
);
var _runJest = _interopRequireDefault(require('../runJest'));
var _watch = _interopRequireDefault(require('../watch'));
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;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const {print: preRunMessagePrint} = _jestUtil().preRunMessage;
async function runCLI(argv, projects) {
_perf_hooks().performance.mark('jest/runCLI:start');
let results;
// If we output a JSON object, we can't write anything to stdout, since
// it'll break the JSON structure and it won't be valid.
const outputStream =
argv.json || argv.useStderr ? process.stderr : process.stdout;
const {globalConfig, configs, hasDeprecationWarnings} = await (0,
_jestConfig().readConfigs)(argv, projects);
if (argv.debug) {
(0, _logDebugMessages.default)(globalConfig, configs, outputStream);
}
if (argv.showConfig) {
(0, _logDebugMessages.default)(globalConfig, configs, process.stdout);
(0, _exit().default)(0);
}
if (argv.clearCache) {
// stick in a Set to dedupe the deletions
new Set(configs.map(config => config.cacheDirectory)).forEach(
cacheDirectory => {
fs().rmSync(cacheDirectory, {
force: true,
recursive: true
});
process.stdout.write(`Cleared ${cacheDirectory}\n`);
}
);
(0, _exit().default)(0);
}
const configsOfProjectsToRun = (0, _getConfigsOfProjectsToRun.default)(
configs,
{
ignoreProjects: argv.ignoreProjects,
selectProjects: argv.selectProjects
}
);
if (argv.selectProjects || argv.ignoreProjects) {
const namesMissingWarning = (0, _getProjectNamesMissingWarning.default)(
configs,
{
ignoreProjects: argv.ignoreProjects,
selectProjects: argv.selectProjects
}
);
if (namesMissingWarning) {
outputStream.write(namesMissingWarning);
}
outputStream.write(
(0, _getSelectProjectsMessage.default)(configsOfProjectsToRun, {
ignoreProjects: argv.ignoreProjects,
selectProjects: argv.selectProjects
})
);
}
await _run10000(
globalConfig,
configsOfProjectsToRun,
hasDeprecationWarnings,
outputStream,
r => {
results = r;
}
);
if (argv.watch || argv.watchAll) {
// If in watch mode, return the promise that will never resolve.
// If the watch mode is interrupted, watch should handle the process
// shutdown.
// eslint-disable-next-line @typescript-eslint/no-empty-function
return new Promise(() => {});
}
if (!results) {
throw new Error(
'AggregatedResult must be present after test run is complete'
);
}
const {openHandles} = results;
if (openHandles && openHandles.length) {
const formatted = (0, _collectHandles.formatHandleErrors)(
openHandles,
configs[0]
);
const openHandlesString = (0, _jestUtil().pluralize)(
'open handle',
formatted.length,
's'
);
const message =
_chalk().default.red(
`\nJest has detected the following ${openHandlesString} potentially keeping Jest from exiting:\n\n`
) + formatted.join('\n\n');
console.error(message);
}
_perf_hooks().performance.mark('jest/runCLI:end');
return {
globalConfig,
results
};
}
const buildContextsAndHasteMaps = async (
configs,
globalConfig,
outputStream
) => {
const hasteMapInstances = Array(configs.length);
const contexts = await Promise.all(
configs.map(async (config, index) => {
(0, _jestUtil().createDirectory)(config.cacheDirectory);
const hasteMapInstance = await _jestRuntime().default.createHasteMap(
config,
{
console: new (_console().CustomConsole)(outputStream, outputStream),
maxWorkers: Math.max(
1,
Math.floor(globalConfig.maxWorkers / configs.length)
),
resetCache: !config.cache,
watch: globalConfig.watch || globalConfig.watchAll,
watchman: globalConfig.watchman,
workerThreads: globalConfig.workerThreads
}
);
hasteMapInstances[index] = hasteMapInstance;
return (0, _createContext.default)(
config,
await hasteMapInstance.build()
);
})
);
return {
contexts,
hasteMapInstances
};
};
const _run10000 = async (
globalConfig,
configs,
hasDeprecationWarnings,
outputStream,
onComplete
) => {
// Queries to hg/git can take a while, so we need to start the process
// as soon as possible, so by the time we need the result it's already there.
const changedFilesPromise = (0, _getChangedFilesPromise.default)(
globalConfig,
configs
);
if (changedFilesPromise) {
_perf_hooks().performance.mark('jest/getChangedFiles:start');
changedFilesPromise.finally(() => {
_perf_hooks().performance.mark('jest/getChangedFiles:end');
});
}
// Filter may need to do an HTTP call or something similar to setup.
// We will wait on an async response from this before using the filter.
let filter;
if (globalConfig.filter && !globalConfig.skipFilter) {
const rawFilter = require(globalConfig.filter);
let filterSetupPromise;
if (rawFilter.setup) {
// Wrap filter setup Promise to avoid "uncaught Promise" error.
// If an error is returned, we surface it in the return value.
filterSetupPromise = (async () => {
try {
await rawFilter.setup();
} catch (err) {
return err;
}
return undefined;
})();
}
filter = async testPaths => {
if (filterSetupPromise) {
// Expect an undefined return value unless there was an error.
const err = await filterSetupPromise;
if (err) {
throw err;
}
}
return rawFilter(testPaths);
};
}
_perf_hooks().performance.mark('jest/buildContextsAndHasteMaps:start');
const {contexts, hasteMapInstances} = await buildContextsAndHasteMaps(
configs,
globalConfig,
outputStream
);
_perf_hooks().performance.mark('jest/buildContextsAndHasteMaps:end');
globalConfig.watch || globalConfig.watchAll
? await runWatch(
contexts,
configs,
hasDeprecationWarnings,
globalConfig,
outputStream,
hasteMapInstances,
filter
)
: await runWithoutWatch(
globalConfig,
contexts,
outputStream,
onComplete,
changedFilesPromise,
filter
);
};
const runWatch = async (
contexts,
_configs,
hasDeprecationWarnings,
globalConfig,
outputStream,
hasteMapInstances,
filter
) => {
if (hasDeprecationWarnings) {
try {
await (0, _handleDeprecationWarnings.default)(
outputStream,
process.stdin
);
return await (0, _watch.default)(
globalConfig,
contexts,
outputStream,
hasteMapInstances,
undefined,
undefined,
filter
);
} catch {
(0, _exit().default)(0);
}
}
return (0, _watch.default)(
globalConfig,
contexts,
outputStream,
hasteMapInstances,
undefined,
undefined,
filter
);
};
const runWithoutWatch = async (
globalConfig,
contexts,
outputStream,
onComplete,
changedFilesPromise,
filter
) => {
const startRun = async () => {
if (!globalConfig.listTests) {
preRunMessagePrint(outputStream);
}
return (0, _runJest.default)({
changedFilesPromise,
contexts,
failedTestsCache: undefined,
filter,
globalConfig,
onComplete,
outputStream,
startRun,
testWatcher: new (_jestWatcher().TestWatcher)({
isWatchMode: false
})
});
};
return startRun();
};

View File

@@ -1,266 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = collectHandles;
exports.formatHandleErrors = formatHandleErrors;
function asyncHooks() {
const data = _interopRequireWildcard(require('async_hooks'));
asyncHooks = function () {
return data;
};
return data;
}
function _util() {
const data = require('util');
_util = function () {
return data;
};
return data;
}
function v8() {
const data = _interopRequireWildcard(require('v8'));
v8 = function () {
return data;
};
return data;
}
function vm() {
const data = _interopRequireWildcard(require('vm'));
vm = function () {
return data;
};
return data;
}
function _stripAnsi() {
const data = _interopRequireDefault(require('strip-ansi'));
_stripAnsi = function () {
return data;
};
return data;
}
function _jestMessageUtil() {
const data = require('jest-message-util');
_jestMessageUtil = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
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) Meta Platforms, Inc. and affiliates.
*
* 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/ban-types-eventually */
function stackIsFromUser(stack) {
// Either the test file, or something required by it
if (stack.includes('Runtime.requireModule')) {
return true;
}
// jest-jasmine it or describe call
if (stack.includes('asyncJestTest') || stack.includes('asyncJestLifecycle')) {
return true;
}
// An async function call from within circus
if (stack.includes('callAsyncCircusFn')) {
// jest-circus it or describe call
return (
stack.includes('_callCircusTest') || stack.includes('_callCircusHook')
);
}
return false;
}
const alwaysActive = () => true;
// @ts-expect-error: doesn't exist in v12 typings
const hasWeakRef = typeof WeakRef === 'function';
const asyncSleep = (0, _util().promisify)(setTimeout);
let gcFunc = globalThis.gc;
function runGC() {
if (!gcFunc) {
v8().setFlagsFromString('--expose-gc');
gcFunc = vm().runInNewContext('gc');
v8().setFlagsFromString('--no-expose-gc');
if (!gcFunc) {
throw new Error(
'Cannot find `global.gc` function. Please run node with `--expose-gc` and report this issue in jest repo.'
);
}
}
gcFunc();
}
// Inspired by https://github.com/mafintosh/why-is-node-running/blob/master/index.js
// Extracted as we want to format the result ourselves
function collectHandles() {
const activeHandles = new Map();
const hook = asyncHooks().createHook({
destroy(asyncId) {
activeHandles.delete(asyncId);
},
init: function initHook(asyncId, type, triggerAsyncId, resource) {
// Skip resources that should not generally prevent the process from
// exiting, not last a meaningfully long time, or otherwise shouldn't be
// tracked.
if (
type === 'PROMISE' ||
type === 'TIMERWRAP' ||
type === 'ELDHISTOGRAM' ||
type === 'PerformanceObserver' ||
type === 'RANDOMBYTESREQUEST' ||
type === 'DNSCHANNEL' ||
type === 'ZLIB' ||
type === 'SIGNREQUEST'
) {
return;
}
const error = new (_jestUtil().ErrorWithStack)(type, initHook, 100);
let fromUser = stackIsFromUser(error.stack || '');
// If the async resource was not directly created by user code, but was
// triggered by another async resource from user code, track it and use
// the original triggering resource's stack.
if (!fromUser) {
const triggeringHandle = activeHandles.get(triggerAsyncId);
if (triggeringHandle) {
fromUser = true;
error.stack = triggeringHandle.error.stack;
}
}
if (fromUser) {
let isActive;
// Handle that supports hasRef
if ('hasRef' in resource) {
if (hasWeakRef) {
// @ts-expect-error: doesn't exist in v12 typings
const ref = new WeakRef(resource);
isActive = () => {
return ref.deref()?.hasRef() ?? false;
};
} else {
isActive = resource.hasRef.bind(resource);
}
} else {
// Handle that doesn't support hasRef
isActive = alwaysActive;
}
activeHandles.set(asyncId, {
error,
isActive
});
}
}
});
hook.enable();
return async () => {
// Wait briefly for any async resources that have been queued for
// destruction to actually be destroyed.
// For example, Node.js TCP Servers are not destroyed until *after* their
// `close` callback runs. If someone finishes a test from the `close`
// callback, we will not yet have seen the resource be destroyed here.
await asyncSleep(100);
if (activeHandles.size > 0) {
// For some special objects such as `TLSWRAP`.
// Ref: https://github.com/jestjs/jest/issues/11665
runGC();
await asyncSleep(0);
}
hook.disable();
// Get errors for every async resource still referenced at this moment
const result = Array.from(activeHandles.values())
.filter(({isActive}) => isActive())
.map(({error}) => error);
activeHandles.clear();
return result;
};
}
function formatHandleErrors(errors, config) {
const stacks = new Set();
return (
errors
.map(err =>
(0, _jestMessageUtil().formatExecError)(
err,
config,
{
noStackTrace: false
},
undefined,
true
)
)
// E.g. timeouts might give multiple traces to the same line of code
// This hairy filtering tries to remove entries with duplicate stack traces
.filter(handle => {
const ansiFree = (0, _stripAnsi().default)(handle);
const match = ansiFree.match(/\s+at(.*)/);
if (!match || match.length < 2) {
return true;
}
const stack = ansiFree.substr(ansiFree.indexOf(match[1])).trim();
if (stacks.has(stack)) {
return false;
}
stacks.add(stack);
return true;
})
);
}

View File

@@ -1,65 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getChangedFilesPromise;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestChangedFiles() {
const data = require('jest-changed-files');
_jestChangedFiles = function () {
return data;
};
return data;
}
function _jestMessageUtil() {
const data = require('jest-message-util');
_jestMessageUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getChangedFilesPromise(globalConfig, configs) {
if (globalConfig.onlyChanged) {
const allRootsForAllProjects = configs.reduce((roots, config) => {
if (config.roots) {
roots.push(...config.roots);
}
return roots;
}, []);
return (0, _jestChangedFiles().getChangedFilesForRoots)(
allRootsForAllProjects,
{
changedSince: globalConfig.changedSince,
lastCommit: globalConfig.lastCommit,
withAncestor: globalConfig.changedFilesWithAncestor
}
).catch(e => {
const message = (0, _jestMessageUtil().formatExecError)(e, configs[0], {
noStackTrace: true
})
.split('\n')
.filter(line => !line.includes('Command failed:'))
.join('\n');
console.error(_chalk().default.red(`\n\n${message}`));
process.exit(1);
});
}
return undefined;
}

View File

@@ -1,40 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getConfigsOfProjectsToRun;
var _getProjectDisplayName = _interopRequireDefault(
require('./getProjectDisplayName')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getConfigsOfProjectsToRun(projectConfigs, opts) {
const projectFilter = createProjectFilter(opts);
return projectConfigs.filter(config => {
const name = (0, _getProjectDisplayName.default)(config);
return projectFilter(name);
});
}
function createProjectFilter(opts) {
const {selectProjects, ignoreProjects} = opts;
const always = () => true;
const selected = selectProjects
? name => name && selectProjects.includes(name)
: always;
const notIgnore = ignoreProjects
? name => !(name && ignoreProjects.includes(name))
: always;
function test(name) {
return selected(name) && notIgnore(name);
}
return test;
}

View File

@@ -1,80 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getNoTestFound;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getNoTestFound(testRunData, globalConfig, willExitWith0) {
const testFiles = testRunData.reduce(
(current, testRun) => current + (testRun.matches.total || 0),
0
);
let dataMessage;
if (globalConfig.runTestsByPath) {
dataMessage = `Files: ${globalConfig.nonFlagArgs
.map(p => `"${p}"`)
.join(', ')}`;
} else {
dataMessage = `Pattern: ${_chalk().default.yellow(
globalConfig.testPathPattern
)} - 0 matches`;
}
if (willExitWith0) {
return (
`${_chalk().default.bold('No tests found, exiting with code 0')}\n` +
`In ${_chalk().default.bold(globalConfig.rootDir)}` +
'\n' +
` ${(0, _jestUtil().pluralize)(
'file',
testFiles,
's'
)} checked across ${(0, _jestUtil().pluralize)(
'project',
testRunData.length,
's'
)}. Run with \`--verbose\` for more details.` +
`\n${dataMessage}`
);
}
return (
`${_chalk().default.bold('No tests found, exiting with code 1')}\n` +
'Run with `--passWithNoTests` to exit with code 0' +
'\n' +
`In ${_chalk().default.bold(globalConfig.rootDir)}` +
'\n' +
` ${(0, _jestUtil().pluralize)(
'file',
testFiles,
's'
)} checked across ${(0, _jestUtil().pluralize)(
'project',
testRunData.length,
's'
)}. Run with \`--verbose\` for more details.` +
`\n${dataMessage}`
);
}

View File

@@ -1,43 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getNoTestFoundFailed;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getNoTestFoundFailed(globalConfig) {
let msg = _chalk().default.bold('No failed test found.');
if (_jestUtil().isInteractive) {
msg += _chalk().default.dim(
`\n${
globalConfig.watch
? 'Press `f` to quit "only failed tests" mode.'
: 'Run Jest without `--onlyFailures` or with `--all` to run all tests.'
}`
);
}
return msg;
}

View File

@@ -1,26 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getNoTestFoundPassWithNoTests;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getNoTestFoundPassWithNoTests() {
return _chalk().default.bold('No tests found, exiting with code 0');
}

View File

@@ -1,48 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getNoTestFoundRelatedToChangedFiles;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getNoTestFoundRelatedToChangedFiles(globalConfig) {
const ref = globalConfig.changedSince
? `"${globalConfig.changedSince}"`
: 'last commit';
let msg = _chalk().default.bold(
`No tests found related to files changed since ${ref}.`
);
if (_jestUtil().isInteractive) {
msg += _chalk().default.dim(
`\n${
globalConfig.watch
? 'Press `a` to run all tests, or run Jest with `--watchAll`.'
: 'Run Jest without `-o` or with `--all` to run all tests.'
}`
);
}
return msg;
}

View File

@@ -1,91 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getNoTestFoundVerbose;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getNoTestFoundVerbose(testRunData, globalConfig, willExitWith0) {
const individualResults = testRunData.map(testRun => {
const stats = testRun.matches.stats || {};
const config = testRun.context.config;
const statsMessage = Object.keys(stats)
.map(key => {
if (key === 'roots' && config.roots.length === 1) {
return null;
}
const value = config[key];
if (value) {
const valueAsString = Array.isArray(value)
? value.join(', ')
: String(value);
const matches = (0, _jestUtil().pluralize)(
'match',
stats[key] || 0,
'es'
);
return ` ${key}: ${_chalk().default.yellow(
valueAsString
)} - ${matches}`;
}
return null;
})
.filter(line => line)
.join('\n');
return testRun.matches.total
? `In ${_chalk().default.bold(config.rootDir)}\n` +
` ${(0, _jestUtil().pluralize)(
'file',
testRun.matches.total || 0,
's'
)} checked.\n${statsMessage}`
: `No files found in ${config.rootDir}.\n` +
"Make sure Jest's configuration does not exclude this directory." +
'\nTo set up Jest, make sure a package.json file exists.\n' +
'Jest Documentation: ' +
'https://jestjs.io/docs/configuration';
});
let dataMessage;
if (globalConfig.runTestsByPath) {
dataMessage = `Files: ${globalConfig.nonFlagArgs
.map(p => `"${p}"`)
.join(', ')}`;
} else {
dataMessage = `Pattern: ${_chalk().default.yellow(
globalConfig.testPathPattern
)} - 0 matches`;
}
if (willExitWith0) {
return `${_chalk().default.bold(
'No tests found, exiting with code 0'
)}\n${individualResults.join('\n')}\n${dataMessage}`;
}
return (
`${_chalk().default.bold('No tests found, exiting with code 1')}\n` +
'Run with `--passWithNoTests` to exit with code 0' +
`\n${individualResults.join('\n')}\n${dataMessage}`
);
}

View File

@@ -1,64 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getNoTestsFoundMessage;
var _getNoTestFound = _interopRequireDefault(require('./getNoTestFound'));
var _getNoTestFoundFailed = _interopRequireDefault(
require('./getNoTestFoundFailed')
);
var _getNoTestFoundPassWithNoTests = _interopRequireDefault(
require('./getNoTestFoundPassWithNoTests')
);
var _getNoTestFoundRelatedToChangedFiles = _interopRequireDefault(
require('./getNoTestFoundRelatedToChangedFiles')
);
var _getNoTestFoundVerbose = _interopRequireDefault(
require('./getNoTestFoundVerbose')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getNoTestsFoundMessage(testRunData, globalConfig) {
const exitWith0 =
globalConfig.passWithNoTests ||
globalConfig.lastCommit ||
globalConfig.onlyChanged;
if (globalConfig.onlyFailures) {
return {
exitWith0,
message: (0, _getNoTestFoundFailed.default)(globalConfig)
};
}
if (globalConfig.onlyChanged) {
return {
exitWith0,
message: (0, _getNoTestFoundRelatedToChangedFiles.default)(globalConfig)
};
}
if (globalConfig.passWithNoTests) {
return {
exitWith0,
message: (0, _getNoTestFoundPassWithNoTests.default)()
};
}
return {
exitWith0,
message:
testRunData.length === 1 || globalConfig.verbose
? (0, _getNoTestFoundVerbose.default)(
testRunData,
globalConfig,
exitWith0
)
: (0, _getNoTestFound.default)(testRunData, globalConfig, exitWith0)
};
}

View File

@@ -1,16 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getProjectDisplayName;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getProjectDisplayName(projectConfig) {
return projectConfig.displayName?.name || undefined;
}

View File

@@ -1,49 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getProjectNamesMissingWarning;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
var _getProjectDisplayName = _interopRequireDefault(
require('./getProjectDisplayName')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getProjectNamesMissingWarning(projectConfigs, opts) {
const numberOfProjectsWithoutAName = projectConfigs.filter(
config => !(0, _getProjectDisplayName.default)(config)
).length;
if (numberOfProjectsWithoutAName === 0) {
return undefined;
}
const args = [];
if (opts.selectProjects) {
args.push('--selectProjects');
}
if (opts.ignoreProjects) {
args.push('--ignoreProjects');
}
return _chalk().default.yellow(
`You provided values for ${args.join(' and ')} but ${
numberOfProjectsWithoutAName === 1
? 'a project does not have a name'
: `${numberOfProjectsWithoutAName} projects do not have a name`
}.\n` +
'Set displayName in the config of all projects in order to disable this warning.\n'
);
}

View File

@@ -1,71 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getSelectProjectsMessage;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
var _getProjectDisplayName = _interopRequireDefault(
require('./getProjectDisplayName')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getSelectProjectsMessage(projectConfigs, opts) {
if (projectConfigs.length === 0) {
return getNoSelectionWarning(opts);
}
return getProjectsRunningMessage(projectConfigs);
}
function getNoSelectionWarning(opts) {
if (opts.ignoreProjects && opts.selectProjects) {
return _chalk().default.yellow(
'You provided values for --selectProjects and --ignoreProjects, but no projects were found matching the selection.\n' +
'Are you ignoring all the selected projects?\n'
);
} else if (opts.ignoreProjects) {
return _chalk().default.yellow(
'You provided values for --ignoreProjects, but no projects were found matching the selection.\n' +
'Are you ignoring all projects?\n'
);
} else if (opts.selectProjects) {
return _chalk().default.yellow(
'You provided values for --selectProjects but no projects were found matching the selection.\n'
);
} else {
return _chalk().default.yellow('No projects were found.\n');
}
}
function getProjectsRunningMessage(projectConfigs) {
if (projectConfigs.length === 1) {
const name =
(0, _getProjectDisplayName.default)(projectConfigs[0]) ??
'<unnamed project>';
return `Running one project: ${_chalk().default.bold(name)}\n`;
}
const projectsList = projectConfigs
.map(getProjectNameListElement)
.sort()
.join('\n');
return `Running ${projectConfigs.length} projects:\n${projectsList}\n`;
}
function getProjectNameListElement(projectConfig) {
const name = (0, _getProjectDisplayName.default)(projectConfig);
const elementContent = name
? _chalk().default.bold(name)
: '<unnamed project>';
return `- ${elementContent}`;
}

82
node_modules/@jest/core/build/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,82 @@
import { BaseReporter, Reporter, ReporterContext } from "@jest/reporters";
import { AggregatedResult, Test, TestContext } from "@jest/test-result";
import { TestWatcher } from "jest-watcher";
import { ChangedFiles } from "jest-changed-files";
import { TestPathPatternsExecutor } from "@jest/pattern";
import { Config } from "@jest/types";
import { TestRunnerContext } from "jest-runner";
//#region src/types.d.ts
type Stats = {
roots: number;
testMatch: number;
testPathIgnorePatterns: number;
testRegex: number;
testPathPatterns?: number;
};
type Filter = (testPaths: Array<string>) => Promise<{
filtered: Array<string>;
}>;
//#endregion
//#region src/SearchSource.d.ts
type SearchResult = {
noSCM?: boolean;
stats?: Stats;
collectCoverageFrom?: Set<string>;
tests: Array<Test>;
total?: number;
};
declare class SearchSource {
private readonly _context;
private _dependencyResolver;
private readonly _testPathCases;
constructor(context: TestContext);
private _getOrBuildDependencyResolver;
private _filterTestPathsWithStats;
private _getAllTestPaths;
isTestFilePath(path: string): boolean;
findMatchingTests(testPathPatternsExecutor: TestPathPatternsExecutor): SearchResult;
findRelatedTests(allPaths: Set<string>, collectCoverage: boolean): Promise<SearchResult>;
findTestsByPaths(paths: Array<string>): SearchResult;
findRelatedTestsFromPattern(paths: Array<string>, collectCoverage: boolean): Promise<SearchResult>;
findTestRelatedToChangedFiles(changedFilesInfo: ChangedFiles, collectCoverage: boolean): Promise<SearchResult>;
private _getTestPaths;
filterPathsWin32(paths: Array<string>): Array<string>;
getTestPaths(globalConfig: Config.GlobalConfig, projectConfig: Config.ProjectConfig, changedFiles?: ChangedFiles, filter?: Filter): Promise<SearchResult>;
findRelatedSourcesFromTestsInChangedFiles(changedFilesInfo: ChangedFiles): Promise<Array<string>>;
}
//#endregion
//#region src/TestScheduler.d.ts
type ReporterConstructor = new (globalConfig: Config.GlobalConfig, reporterConfig: Record<string, unknown>, reporterContext: ReporterContext) => BaseReporter;
type TestSchedulerContext = ReporterContext & TestRunnerContext;
declare function createTestScheduler(globalConfig: Config.GlobalConfig, context: TestSchedulerContext): Promise<TestScheduler>;
declare class TestScheduler {
private readonly _context;
private readonly _dispatcher;
private readonly _globalConfig;
constructor(globalConfig: Config.GlobalConfig, context: TestSchedulerContext);
addReporter(reporter: Reporter): void;
removeReporter(reporterConstructor: ReporterConstructor): void;
scheduleTests(tests: Array<Test>, watcher: TestWatcher): Promise<AggregatedResult>;
private _partitionTests;
_setupReporters(): Promise<void>;
private _addCustomReporter;
private _bailIfNeeded;
}
//#endregion
//#region src/cli/index.d.ts
declare function runCLI(argv: Config.Argv, projects: Array<string>): Promise<{
results: AggregatedResult;
globalConfig: Config.GlobalConfig;
}>;
//#endregion
//#region src/version.d.ts
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
declare function getVersion(): string;
//#endregion
export { SearchSource, createTestScheduler, getVersion, runCLI };

View File

@@ -4,16 +4,14 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {AggregatedResult} from '@jest/test-result';
import {BaseReporter} from '@jest/reporters';
import type {ChangedFiles} from 'jest-changed-files';
import type {Config} from '@jest/types';
import {Reporter} from '@jest/reporters';
import {ReporterContext} from '@jest/reporters';
import {Test} from '@jest/test-result';
import type {TestContext} from '@jest/test-result';
import type {TestRunnerContext} from 'jest-runner';
import type {TestWatcher} from 'jest-watcher';
import {TestPathPatternsExecutor} from '@jest/pattern';
import {BaseReporter, Reporter, ReporterContext} from '@jest/reporters';
import {AggregatedResult, Test, TestContext} from '@jest/test-result';
import {Config} from '@jest/types';
import {ChangedFiles} from 'jest-changed-files';
import {TestRunnerContext} from 'jest-runner';
import {TestWatcher} from 'jest-watcher';
export declare function createTestScheduler(
globalConfig: Config.GlobalConfig,
@@ -21,14 +19,9 @@ export declare function createTestScheduler(
): Promise<TestScheduler>;
declare type Filter = (testPaths: Array<string>) => Promise<{
filtered: Array<FilterResult>;
filtered: Array<string>;
}>;
declare type FilterResult = {
test: string;
message: string;
};
export declare function getVersion(): string;
declare type ReporterConstructor = new (
@@ -62,7 +55,9 @@ export declare class SearchSource {
private _filterTestPathsWithStats;
private _getAllTestPaths;
isTestFilePath(path: string): boolean;
findMatchingTests(testPathPattern: string): SearchResult;
findMatchingTests(
testPathPatternsExecutor: TestPathPatternsExecutor,
): SearchResult;
findRelatedTests(
allPaths: Set<string>,
collectCoverage: boolean,
@@ -80,6 +75,7 @@ export declare class SearchSource {
filterPathsWin32(paths: Array<string>): Array<string>;
getTestPaths(
globalConfig: Config.GlobalConfig,
projectConfig: Config.ProjectConfig,
changedFiles?: ChangedFiles,
filter?: Filter,
): Promise<SearchResult>;
@@ -93,7 +89,7 @@ declare type Stats = {
testMatch: number;
testPathIgnorePatterns: number;
testRegex: number;
testPathPattern?: number;
testPathPatterns?: number;
};
declare class TestScheduler {

4142
node_modules/@jest/core/build/index.js generated vendored

File diff suppressed because it is too large Load Diff

6
node_modules/@jest/core/build/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import cjsModule from './index.js';
export const SearchSource = cjsModule.SearchSource;
export const createTestScheduler = cjsModule.createTestScheduler;
export const getVersion = cjsModule.getVersion;
export const runCLI = cjsModule.runCLI;

View File

@@ -1,52 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const activeFilters = globalConfig => {
const {testNamePattern, testPathPattern} = globalConfig;
if (testNamePattern || testPathPattern) {
const filters = [
testPathPattern
? _chalk().default.dim('filename ') +
_chalk().default.yellow(`/${testPathPattern}/`)
: null,
testNamePattern
? _chalk().default.dim('test name ') +
_chalk().default.yellow(`/${testNamePattern}/`)
: null
]
.filter(_jestUtil().isNonNullable)
.join(', ');
const messages = `\n${_chalk().default.bold('Active Filters: ')}${filters}`;
return messages;
}
return '';
};
var _default = activeFilters;
exports.default = _default;

View File

@@ -1,31 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = createContext;
function _jestRuntime() {
const data = _interopRequireDefault(require('jest-runtime'));
_jestRuntime = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function createContext(config, {hasteFS, moduleMap}) {
return {
config,
hasteFS,
moduleMap,
resolver: _jestRuntime().default.createResolver(config, moduleMap)
};
}

View File

@@ -1,65 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = handleDeprecationWarnings;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function handleDeprecationWarnings(pipe, stdin = process.stdin) {
return new Promise((resolve, reject) => {
if (typeof stdin.setRawMode === 'function') {
const messages = [
_chalk().default.red('There are deprecation warnings.\n'),
`${_chalk().default.dim(' \u203A Press ')}Enter${_chalk().default.dim(
' to continue.'
)}`,
`${_chalk().default.dim(' \u203A Press ')}Esc${_chalk().default.dim(
' to exit.'
)}`
];
pipe.write(messages.join('\n'));
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
// this is a string since we set encoding above
stdin.on('data', key => {
if (key === _jestWatcher().KEYS.ENTER) {
resolve();
} else if (
[
_jestWatcher().KEYS.ESCAPE,
_jestWatcher().KEYS.CONTROL_C,
_jestWatcher().KEYS.CONTROL_D
].indexOf(key) !== -1
) {
reject();
}
});
} else {
resolve();
}
});
}

View File

@@ -1,26 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = isValidPath;
function _jestSnapshot() {
const data = require('jest-snapshot');
_jestSnapshot = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function isValidPath(globalConfig, filePath) {
return (
!filePath.includes(globalConfig.coverageDirectory) &&
!(0, _jestSnapshot().isSnapshotPath)(filePath)
);
}

View File

@@ -1,24 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = logDebugMessages;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const VERSION = require('../../package.json').version;
// if the output here changes, update `getConfig` in e2e/runJest.ts
function logDebugMessages(globalConfig, configs, outputStream) {
const output = {
configs,
globalConfig,
version: VERSION
};
outputStream.write(`${JSON.stringify(output, null, ' ')}\n`);
}

View File

@@ -1,95 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = updateGlobalConfig;
function _jestRegexUtil() {
const data = require('jest-regex-util');
_jestRegexUtil = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function updateGlobalConfig(globalConfig, options = {}) {
const newConfig = {
...globalConfig
};
if (options.mode === 'watch') {
newConfig.watch = true;
newConfig.watchAll = false;
} else if (options.mode === 'watchAll') {
newConfig.watch = false;
newConfig.watchAll = true;
}
if (options.testNamePattern !== undefined) {
newConfig.testNamePattern = options.testNamePattern || '';
}
if (options.testPathPattern !== undefined) {
newConfig.testPathPattern =
(0, _jestRegexUtil().replacePathSepForRegex)(options.testPathPattern) ||
'';
}
newConfig.onlyChanged =
!newConfig.watchAll &&
!newConfig.testNamePattern &&
!newConfig.testPathPattern;
if (typeof options.bail === 'boolean') {
newConfig.bail = options.bail ? 1 : 0;
} else if (options.bail !== undefined) {
newConfig.bail = options.bail;
}
if (options.changedSince !== undefined) {
newConfig.changedSince = options.changedSince;
}
if (options.collectCoverage !== undefined) {
newConfig.collectCoverage = options.collectCoverage || false;
}
if (options.collectCoverageFrom !== undefined) {
newConfig.collectCoverageFrom = options.collectCoverageFrom;
}
if (options.coverageDirectory !== undefined) {
newConfig.coverageDirectory = options.coverageDirectory;
}
if (options.coverageReporters !== undefined) {
newConfig.coverageReporters = options.coverageReporters;
}
if (options.findRelatedTests !== undefined) {
newConfig.findRelatedTests = options.findRelatedTests;
}
if (options.nonFlagArgs !== undefined) {
newConfig.nonFlagArgs = options.nonFlagArgs;
}
if (options.noSCM) {
newConfig.noSCM = true;
}
if (options.notify !== undefined) {
newConfig.notify = options.notify || false;
}
if (options.notifyMode !== undefined) {
newConfig.notifyMode = options.notifyMode;
}
if (options.onlyFailures !== undefined) {
newConfig.onlyFailures = options.onlyFailures || false;
}
if (options.passWithNoTests !== undefined) {
newConfig.passWithNoTests = true;
}
if (options.reporters !== undefined) {
newConfig.reporters = options.reporters;
}
if (options.updateSnapshot !== undefined) {
newConfig.updateSnapshot = options.updateSnapshot;
}
if (options.verbose !== undefined) {
newConfig.verbose = options.verbose || false;
}
return Object.freeze(newConfig);
}

View File

@@ -1,56 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.getSortedUsageRows = exports.filterInteractivePlugins = void 0;
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const filterInteractivePlugins = (watchPlugins, globalConfig) => {
const usageInfos = watchPlugins.map(
p => p.getUsageInfo && p.getUsageInfo(globalConfig)
);
return watchPlugins.filter((_plugin, i) => {
const usageInfo = usageInfos[i];
if (usageInfo) {
const {key} = usageInfo;
return !usageInfos.slice(i + 1).some(u => !!u && key === u.key);
}
return false;
});
};
exports.filterInteractivePlugins = filterInteractivePlugins;
const getSortedUsageRows = (watchPlugins, globalConfig) =>
filterInteractivePlugins(watchPlugins, globalConfig)
.sort((a, b) => {
if (a.isInternal && b.isInternal) {
// internal plugins in the order we specify them
return 0;
}
if (a.isInternal !== b.isInternal) {
// external plugins afterwards
return a.isInternal ? -1 : 1;
}
const usageInfoA = a.getUsageInfo && a.getUsageInfo(globalConfig);
const usageInfoB = b.getUsageInfo && b.getUsageInfo(globalConfig);
if (usageInfoA && usageInfoB) {
// external plugins in alphabetical order
return usageInfoA.key.localeCompare(usageInfoB.key);
}
return 0;
})
.map(p => p.getUsageInfo && p.getUsageInfo(globalConfig))
.filter(_jestUtil().isNonNullable);
exports.getSortedUsageRows = getSortedUsageRows;

View File

@@ -1,96 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
var _FailedTestsInteractiveMode = _interopRequireDefault(
require('../FailedTestsInteractiveMode')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class FailedTestsInteractivePlugin extends _jestWatcher().BaseWatchPlugin {
_failedTestAssertions;
_manager = new _FailedTestsInteractiveMode.default(this._stdout);
apply(hooks) {
hooks.onTestRunComplete(results => {
this._failedTestAssertions = this.getFailedTestAssertions(results);
if (this._manager.isActive()) this._manager.updateWithResults(results);
});
}
getUsageInfo() {
if (this._failedTestAssertions?.length) {
return {
key: 'i',
prompt: 'run failing tests interactively'
};
}
return null;
}
onKey(key) {
if (this._manager.isActive()) {
this._manager.put(key);
}
}
run(_, updateConfigAndRun) {
return new Promise(resolve => {
if (
!this._failedTestAssertions ||
this._failedTestAssertions.length === 0
) {
resolve();
return;
}
this._manager.run(this._failedTestAssertions, failure => {
updateConfigAndRun({
mode: 'watch',
testNamePattern: failure ? `^${failure.fullName}$` : '',
testPathPattern: failure?.path || ''
});
if (!this._manager.isActive()) {
resolve();
}
});
});
}
getFailedTestAssertions(results) {
const failedTestPaths = [];
if (
// skip if no failed tests
results.numFailedTests === 0 ||
// skip if missing test results
!results.testResults ||
// skip if unmatched snapshots are present
results.snapshot.unmatched
) {
return failedTestPaths;
}
results.testResults.forEach(testResult => {
testResult.testResults.forEach(result => {
if (result.status === 'failed') {
failedTestPaths.push({
fullName: result.fullName,
path: testResult.testFilePath
});
}
});
});
return failedTestPaths;
}
}
exports.default = FailedTestsInteractivePlugin;

View File

@@ -1,42 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class QuitPlugin extends _jestWatcher().BaseWatchPlugin {
isInternal;
constructor(options) {
super(options);
this.isInternal = true;
}
async run() {
if (typeof this._stdin.setRawMode === 'function') {
this._stdin.setRawMode(false);
}
this._stdout.write('\n');
process.exit(0);
}
getUsageInfo() {
return {
key: 'q',
prompt: 'quit watch mode'
};
}
}
var _default = QuitPlugin;
exports.default = _default;

View File

@@ -1,70 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
var _TestNamePatternPrompt = _interopRequireDefault(
require('../TestNamePatternPrompt')
);
var _activeFiltersMessage = _interopRequireDefault(
require('../lib/activeFiltersMessage')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class TestNamePatternPlugin extends _jestWatcher().BaseWatchPlugin {
_prompt;
isInternal;
constructor(options) {
super(options);
this._prompt = new (_jestWatcher().Prompt)();
this.isInternal = true;
}
getUsageInfo() {
return {
key: 't',
prompt: 'filter by a test name regex pattern'
};
}
onKey(key) {
this._prompt.put(key);
}
run(globalConfig, updateConfigAndRun) {
return new Promise((res, rej) => {
const testNamePatternPrompt = new _TestNamePatternPrompt.default(
this._stdout,
this._prompt
);
testNamePatternPrompt.run(
value => {
updateConfigAndRun({
mode: 'watch',
testNamePattern: value
});
res();
},
rej,
{
header: (0, _activeFiltersMessage.default)(globalConfig)
}
);
});
}
}
var _default = TestNamePatternPlugin;
exports.default = _default;

View File

@@ -1,70 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
var _TestPathPatternPrompt = _interopRequireDefault(
require('../TestPathPatternPrompt')
);
var _activeFiltersMessage = _interopRequireDefault(
require('../lib/activeFiltersMessage')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class TestPathPatternPlugin extends _jestWatcher().BaseWatchPlugin {
_prompt;
isInternal;
constructor(options) {
super(options);
this._prompt = new (_jestWatcher().Prompt)();
this.isInternal = true;
}
getUsageInfo() {
return {
key: 'p',
prompt: 'filter by a filename regex pattern'
};
}
onKey(key) {
this._prompt.put(key);
}
run(globalConfig, updateConfigAndRun) {
return new Promise((res, rej) => {
const testPathPatternPrompt = new _TestPathPatternPrompt.default(
this._stdout,
this._prompt
);
testPathPatternPrompt.run(
value => {
updateConfigAndRun({
mode: 'watch',
testPathPattern: value
});
res();
},
rej,
{
header: (0, _activeFiltersMessage.default)(globalConfig)
}
);
});
}
}
var _default = TestPathPatternPlugin;
exports.default = _default;

View File

@@ -1,51 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
class UpdateSnapshotsPlugin extends _jestWatcher().BaseWatchPlugin {
_hasSnapshotFailure;
isInternal;
constructor(options) {
super(options);
this.isInternal = true;
this._hasSnapshotFailure = false;
}
run(_globalConfig, updateConfigAndRun) {
updateConfigAndRun({
updateSnapshot: 'all'
});
return Promise.resolve(false);
}
apply(hooks) {
hooks.onTestRunComplete(results => {
this._hasSnapshotFailure = results.snapshot.failure;
});
}
getUsageInfo() {
if (this._hasSnapshotFailure) {
return {
key: 'u',
prompt: 'update failing snapshots'
};
}
return null;
}
}
var _default = UpdateSnapshotsPlugin;
exports.default = _default;

View File

@@ -1,99 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
var _SnapshotInteractiveMode = _interopRequireDefault(
require('../SnapshotInteractiveMode')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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/ban-types-eventually */
class UpdateSnapshotInteractivePlugin extends _jestWatcher().BaseWatchPlugin {
_snapshotInteractiveMode = new _SnapshotInteractiveMode.default(this._stdout);
_failedSnapshotTestAssertions = [];
isInternal = true;
getFailedSnapshotTestAssertions(testResults) {
const failedTestPaths = [];
if (testResults.numFailedTests === 0 || !testResults.testResults) {
return failedTestPaths;
}
testResults.testResults.forEach(testResult => {
if (testResult.snapshot && testResult.snapshot.unmatched) {
testResult.testResults.forEach(result => {
if (result.status === 'failed') {
failedTestPaths.push({
fullName: result.fullName,
path: testResult.testFilePath
});
}
});
}
});
return failedTestPaths;
}
apply(hooks) {
hooks.onTestRunComplete(results => {
this._failedSnapshotTestAssertions =
this.getFailedSnapshotTestAssertions(results);
if (this._snapshotInteractiveMode.isActive()) {
this._snapshotInteractiveMode.updateWithResults(results);
}
});
}
onKey(key) {
if (this._snapshotInteractiveMode.isActive()) {
this._snapshotInteractiveMode.put(key);
}
}
run(_globalConfig, updateConfigAndRun) {
if (this._failedSnapshotTestAssertions.length) {
return new Promise(res => {
this._snapshotInteractiveMode.run(
this._failedSnapshotTestAssertions,
(assertion, shouldUpdateSnapshot) => {
updateConfigAndRun({
mode: 'watch',
testNamePattern: assertion ? `^${assertion.fullName}$` : '',
testPathPattern: assertion ? assertion.path : '',
updateSnapshot: shouldUpdateSnapshot ? 'all' : 'none'
});
if (!this._snapshotInteractiveMode.isActive()) {
res();
}
}
);
});
} else {
return Promise.resolve();
}
}
getUsageInfo() {
if (this._failedSnapshotTestAssertions?.length > 0) {
return {
key: 'i',
prompt: 'update failing snapshots interactively'
};
}
return null;
}
}
var _default = UpdateSnapshotInteractivePlugin;
exports.default = _default;

View File

@@ -1,133 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = runGlobalHook;
function util() {
const data = _interopRequireWildcard(require('util'));
util = function () {
return data;
};
return data;
}
function _transform() {
const data = require('@jest/transform');
_transform = function () {
return data;
};
return data;
}
function _prettyFormat() {
const data = _interopRequireDefault(require('pretty-format'));
_prettyFormat = function () {
return data;
};
return data;
}
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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
async function runGlobalHook({allTests, globalConfig, moduleName}) {
const globalModulePaths = new Set(
allTests.map(test => test.context.config[moduleName])
);
if (globalConfig[moduleName]) {
globalModulePaths.add(globalConfig[moduleName]);
}
if (globalModulePaths.size > 0) {
for (const modulePath of globalModulePaths) {
if (!modulePath) {
continue;
}
const correctConfig = allTests.find(
t => t.context.config[moduleName] === modulePath
);
const projectConfig = correctConfig
? correctConfig.context.config
: // Fallback to first config
allTests[0].context.config;
const transformer = await (0, _transform().createScriptTransformer)(
projectConfig
);
try {
await transformer.requireAndTranspileModule(
modulePath,
async globalModule => {
if (typeof globalModule !== 'function') {
throw new TypeError(
`${moduleName} file must export a function at ${modulePath}`
);
}
await globalModule(globalConfig, projectConfig);
}
);
} catch (error) {
if (
util().types.isNativeError(error) &&
(Object.getOwnPropertyDescriptor(error, 'message')?.writable ||
Object.getOwnPropertyDescriptor(
Object.getPrototypeOf(error),
'message'
)?.writable)
) {
error.message = `Jest: Got error running ${moduleName} - ${modulePath}, reason: ${error.message}`;
throw error;
}
throw new Error(
`Jest: Got error running ${moduleName} - ${modulePath}, reason: ${(0,
_prettyFormat().default)(error, {
maxDepth: 3
})}`
);
}
}
}
}

View File

@@ -1,391 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = runJest;
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function _perf_hooks() {
const data = require('perf_hooks');
_perf_hooks = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _exit() {
const data = _interopRequireDefault(require('exit'));
_exit = function () {
return data;
};
return data;
}
function fs() {
const data = _interopRequireWildcard(require('graceful-fs'));
fs = function () {
return data;
};
return data;
}
function _console() {
const data = require('@jest/console');
_console = function () {
return data;
};
return data;
}
function _testResult() {
const data = require('@jest/test-result');
_testResult = function () {
return data;
};
return data;
}
function _jestResolve() {
const data = _interopRequireDefault(require('jest-resolve'));
_jestResolve = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
var _SearchSource = _interopRequireDefault(require('./SearchSource'));
var _TestScheduler = require('./TestScheduler');
var _collectHandles = _interopRequireDefault(require('./collectHandles'));
var _getNoTestsFoundMessage = _interopRequireDefault(
require('./getNoTestsFoundMessage')
);
var _runGlobalHook = _interopRequireDefault(require('./runGlobalHook'));
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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const getTestPaths = async (
globalConfig,
source,
outputStream,
changedFiles,
jestHooks,
filter
) => {
const data = await source.getTestPaths(globalConfig, changedFiles, filter);
if (!data.tests.length && globalConfig.onlyChanged && data.noSCM) {
new (_console().CustomConsole)(outputStream, outputStream).log(
'Jest can only find uncommitted changed files in a git or hg ' +
'repository. If you make your project a git or hg ' +
'repository (`git init` or `hg init`), Jest will be able ' +
'to only run tests related to files changed since the last ' +
'commit.'
);
}
const shouldTestArray = await Promise.all(
data.tests.map(test =>
jestHooks.shouldRunTestSuite({
config: test.context.config,
duration: test.duration,
testPath: test.path
})
)
);
const filteredTests = data.tests.filter((_test, i) => shouldTestArray[i]);
return {
...data,
allTests: filteredTests.length,
tests: filteredTests
};
};
const processResults = async (runResults, options) => {
const {
outputFile,
json: isJSON,
onComplete,
outputStream,
testResultsProcessor,
collectHandles
} = options;
if (collectHandles) {
runResults.openHandles = await collectHandles();
} else {
runResults.openHandles = [];
}
if (testResultsProcessor) {
const processor = await (0, _jestUtil().requireOrImportModule)(
testResultsProcessor
);
runResults = await processor(runResults);
}
if (isJSON) {
if (outputFile) {
const cwd = (0, _jestUtil().tryRealpath)(process.cwd());
const filePath = path().resolve(cwd, outputFile);
fs().writeFileSync(
filePath,
`${JSON.stringify((0, _testResult().formatTestResults)(runResults))}\n`
);
outputStream.write(
`Test results written to: ${path().relative(cwd, filePath)}\n`
);
} else {
process.stdout.write(
`${JSON.stringify((0, _testResult().formatTestResults)(runResults))}\n`
);
}
}
onComplete?.(runResults);
};
const testSchedulerContext = {
firstRun: true,
previousSuccess: true
};
async function runJest({
contexts,
globalConfig,
outputStream,
testWatcher,
jestHooks = new (_jestWatcher().JestHook)().getEmitter(),
startRun,
changedFilesPromise,
onComplete,
failedTestsCache,
filter
}) {
// Clear cache for required modules - there might be different resolutions
// from Jest's config loading to running the tests
_jestResolve().default.clearDefaultResolverCache();
const Sequencer = await (0, _jestUtil().requireOrImportModule)(
globalConfig.testSequencer
);
const sequencer = new Sequencer();
let allTests = [];
if (changedFilesPromise && globalConfig.watch) {
const {repos} = await changedFilesPromise;
const noSCM = Object.keys(repos).every(scm => repos[scm].size === 0);
if (noSCM) {
process.stderr.write(
`\n${_chalk().default.bold(
'--watch'
)} is not supported without git/hg, please use --watchAll\n`
);
(0, _exit().default)(1);
}
}
const searchSources = contexts.map(
context => new _SearchSource.default(context)
);
_perf_hooks().performance.mark('jest/getTestPaths:start');
const testRunData = await Promise.all(
contexts.map(async (context, index) => {
const searchSource = searchSources[index];
const matches = await getTestPaths(
globalConfig,
searchSource,
outputStream,
changedFilesPromise && (await changedFilesPromise),
jestHooks,
filter
);
allTests = allTests.concat(matches.tests);
return {
context,
matches
};
})
);
_perf_hooks().performance.mark('jest/getTestPaths:end');
if (globalConfig.shard) {
if (typeof sequencer.shard !== 'function') {
throw new Error(
`Shard ${globalConfig.shard.shardIndex}/${globalConfig.shard.shardCount} requested, but test sequencer ${Sequencer.name} in ${globalConfig.testSequencer} has no shard method.`
);
}
allTests = await sequencer.shard(allTests, globalConfig.shard);
}
allTests = await sequencer.sort(allTests);
if (globalConfig.listTests) {
const testsPaths = Array.from(new Set(allTests.map(test => test.path)));
/* eslint-disable no-console */
if (globalConfig.json) {
console.log(JSON.stringify(testsPaths));
} else {
console.log(testsPaths.join('\n'));
}
/* eslint-enable */
onComplete &&
onComplete((0, _testResult().makeEmptyAggregatedTestResult)());
return;
}
if (globalConfig.onlyFailures) {
if (failedTestsCache) {
allTests = failedTestsCache.filterTests(allTests);
} else {
allTests = await sequencer.allFailedTests(allTests);
}
}
const hasTests = allTests.length > 0;
if (!hasTests) {
const {exitWith0, message: noTestsFoundMessage} = (0,
_getNoTestsFoundMessage.default)(testRunData, globalConfig);
if (exitWith0) {
new (_console().CustomConsole)(outputStream, outputStream).log(
noTestsFoundMessage
);
} else {
new (_console().CustomConsole)(outputStream, outputStream).error(
noTestsFoundMessage
);
(0, _exit().default)(1);
}
} else if (
allTests.length === 1 &&
globalConfig.silent !== true &&
globalConfig.verbose !== false
) {
const newConfig = {
...globalConfig,
verbose: true
};
globalConfig = Object.freeze(newConfig);
}
let collectHandles;
if (globalConfig.detectOpenHandles) {
collectHandles = (0, _collectHandles.default)();
}
if (hasTests) {
_perf_hooks().performance.mark('jest/globalSetup:start');
await (0, _runGlobalHook.default)({
allTests,
globalConfig,
moduleName: 'globalSetup'
});
_perf_hooks().performance.mark('jest/globalSetup:end');
}
if (changedFilesPromise) {
const changedFilesInfo = await changedFilesPromise;
if (changedFilesInfo.changedFiles) {
testSchedulerContext.changedFiles = changedFilesInfo.changedFiles;
const sourcesRelatedToTestsInChangedFilesArray = (
await Promise.all(
contexts.map(async (_, index) => {
const searchSource = searchSources[index];
return searchSource.findRelatedSourcesFromTestsInChangedFiles(
changedFilesInfo
);
})
)
).reduce((total, paths) => total.concat(paths), []);
testSchedulerContext.sourcesRelatedToTestsInChangedFiles = new Set(
sourcesRelatedToTestsInChangedFilesArray
);
}
}
const scheduler = await (0, _TestScheduler.createTestScheduler)(
globalConfig,
{
startRun,
...testSchedulerContext
}
);
// @ts-expect-error - second arg is unsupported (but harmless) in Node 14
_perf_hooks().performance.mark('jest/scheduleAndRun:start', {
detail: {
numTests: allTests.length
}
});
const results = await scheduler.scheduleTests(allTests, testWatcher);
_perf_hooks().performance.mark('jest/scheduleAndRun:end');
_perf_hooks().performance.mark('jest/cacheResults:start');
sequencer.cacheResults(allTests, results);
_perf_hooks().performance.mark('jest/cacheResults:end');
if (hasTests) {
_perf_hooks().performance.mark('jest/globalTeardown:start');
await (0, _runGlobalHook.default)({
allTests,
globalConfig,
moduleName: 'globalTeardown'
});
_perf_hooks().performance.mark('jest/globalTeardown:end');
}
_perf_hooks().performance.mark('jest/processResults:start');
await processResults(results, {
collectHandles,
json: globalConfig.json,
onComplete,
outputFile: globalConfig.outputFile,
outputStream,
testResultsProcessor: globalConfig.testResultsProcessor
});
_perf_hooks().performance.mark('jest/processResults:end');
}

View File

@@ -1,57 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.shouldRunInBand = shouldRunInBand;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const SLOW_TEST_TIME = 1000;
function shouldRunInBand(
tests,
timings,
{
detectOpenHandles,
maxWorkers,
runInBand,
watch,
watchAll,
workerIdleMemoryLimit
}
) {
// If user asked for run in band, respect that.
// detectOpenHandles makes no sense without runInBand, because it cannot detect leaks in workers
if (runInBand || detectOpenHandles) {
return true;
}
/*
* If we are using watch/watchAll mode, don't schedule anything in the main
* thread to keep the TTY responsive and to prevent watch mode crashes caused
* by leaks (improper test teardown).
*/
if (watch || watchAll) {
return false;
}
/*
* Otherwise, run in band if we only have one test or one worker available.
* Also, if we are confident from previous runs that the tests will finish
* quickly we also run in band to reduce the overhead of spawning workers.
*/
const areFastTests = timings.every(timing => timing < SLOW_TEST_TIME);
const oneWorkerOrLess = maxWorkers <= 1;
const oneTestOrLess = tests.length <= 1;
return (
// When specifying a memory limit, workers should be used
!workerIdleMemoryLimit &&
(oneWorkerOrLess ||
oneTestOrLess ||
(tests.length <= 20 && timings.length > 0 && areFastTests))
);
}

View File

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

View File

@@ -1,18 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getVersion;
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Cannot be `import` as it's not under TS root dir
const {version: VERSION} = require('../package.json');
function getVersion() {
return VERSION;
}

View File

@@ -1,666 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = watch;
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function _ansiEscapes() {
const data = _interopRequireDefault(require('ansi-escapes'));
_ansiEscapes = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _exit() {
const data = _interopRequireDefault(require('exit'));
_exit = function () {
return data;
};
return data;
}
function _slash() {
const data = _interopRequireDefault(require('slash'));
_slash = function () {
return data;
};
return data;
}
function _jestMessageUtil() {
const data = require('jest-message-util');
_jestMessageUtil = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _jestValidate() {
const data = require('jest-validate');
_jestValidate = function () {
return data;
};
return data;
}
function _jestWatcher() {
const data = require('jest-watcher');
_jestWatcher = function () {
return data;
};
return data;
}
var _FailedTestsCache = _interopRequireDefault(require('./FailedTestsCache'));
var _SearchSource = _interopRequireDefault(require('./SearchSource'));
var _getChangedFilesPromise = _interopRequireDefault(
require('./getChangedFilesPromise')
);
var _activeFiltersMessage = _interopRequireDefault(
require('./lib/activeFiltersMessage')
);
var _createContext = _interopRequireDefault(require('./lib/createContext'));
var _isValidPath = _interopRequireDefault(require('./lib/isValidPath'));
var _updateGlobalConfig = _interopRequireDefault(
require('./lib/updateGlobalConfig')
);
var _watchPluginsHelpers = require('./lib/watchPluginsHelpers');
var _FailedTestsInteractive = _interopRequireDefault(
require('./plugins/FailedTestsInteractive')
);
var _Quit = _interopRequireDefault(require('./plugins/Quit'));
var _TestNamePattern = _interopRequireDefault(
require('./plugins/TestNamePattern')
);
var _TestPathPattern = _interopRequireDefault(
require('./plugins/TestPathPattern')
);
var _UpdateSnapshots = _interopRequireDefault(
require('./plugins/UpdateSnapshots')
);
var _UpdateSnapshotsInteractive = _interopRequireDefault(
require('./plugins/UpdateSnapshotsInteractive')
);
var _runJest = _interopRequireDefault(require('./runJest'));
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) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const {print: preRunMessagePrint} = _jestUtil().preRunMessage;
let hasExitListener = false;
const INTERNAL_PLUGINS = [
_FailedTestsInteractive.default,
_TestPathPattern.default,
_TestNamePattern.default,
_UpdateSnapshots.default,
_UpdateSnapshotsInteractive.default,
_Quit.default
];
const RESERVED_KEY_PLUGINS = new Map([
[
_UpdateSnapshots.default,
{
forbiddenOverwriteMessage: 'updating snapshots',
key: 'u'
}
],
[
_UpdateSnapshotsInteractive.default,
{
forbiddenOverwriteMessage: 'updating snapshots interactively',
key: 'i'
}
],
[
_Quit.default,
{
forbiddenOverwriteMessage: 'quitting watch mode'
}
]
]);
async function watch(
initialGlobalConfig,
contexts,
outputStream,
hasteMapInstances,
stdin = process.stdin,
hooks = new (_jestWatcher().JestHook)(),
filter
) {
// `globalConfig` will be constantly updated and reassigned as a result of
// watch mode interactions.
let globalConfig = initialGlobalConfig;
let activePlugin;
globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
mode: globalConfig.watch ? 'watch' : 'watchAll',
passWithNoTests: true
});
const updateConfigAndRun = ({
bail,
changedSince,
collectCoverage,
collectCoverageFrom,
coverageDirectory,
coverageReporters,
findRelatedTests,
mode,
nonFlagArgs,
notify,
notifyMode,
onlyFailures,
reporters,
testNamePattern,
testPathPattern,
updateSnapshot,
verbose
} = {}) => {
const previousUpdateSnapshot = globalConfig.updateSnapshot;
globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
bail,
changedSince,
collectCoverage,
collectCoverageFrom,
coverageDirectory,
coverageReporters,
findRelatedTests,
mode,
nonFlagArgs,
notify,
notifyMode,
onlyFailures,
reporters,
testNamePattern,
testPathPattern,
updateSnapshot,
verbose
});
startRun(globalConfig);
globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
// updateSnapshot is not sticky after a run.
updateSnapshot:
previousUpdateSnapshot === 'all' ? 'none' : previousUpdateSnapshot
});
};
const watchPlugins = INTERNAL_PLUGINS.map(
InternalPlugin =>
new InternalPlugin({
stdin,
stdout: outputStream
})
);
watchPlugins.forEach(plugin => {
const hookSubscriber = hooks.getSubscriber();
if (plugin.apply) {
plugin.apply(hookSubscriber);
}
});
if (globalConfig.watchPlugins != null) {
const watchPluginKeys = new Map();
for (const plugin of watchPlugins) {
const reservedInfo = RESERVED_KEY_PLUGINS.get(plugin.constructor) || {};
const key = reservedInfo.key || getPluginKey(plugin, globalConfig);
if (!key) {
continue;
}
const {forbiddenOverwriteMessage} = reservedInfo;
watchPluginKeys.set(key, {
forbiddenOverwriteMessage,
overwritable: forbiddenOverwriteMessage == null,
plugin
});
}
for (const pluginWithConfig of globalConfig.watchPlugins) {
let plugin;
try {
const ThirdPartyPlugin = await (0, _jestUtil().requireOrImportModule)(
pluginWithConfig.path
);
plugin = new ThirdPartyPlugin({
config: pluginWithConfig.config,
stdin,
stdout: outputStream
});
} catch (error) {
const errorWithContext = new Error(
`Failed to initialize watch plugin "${_chalk().default.bold(
(0, _slash().default)(
path().relative(process.cwd(), pluginWithConfig.path)
)
)}":\n\n${(0, _jestMessageUtil().formatExecError)(
error,
contexts[0].config,
{
noStackTrace: false
}
)}`
);
delete errorWithContext.stack;
return Promise.reject(errorWithContext);
}
checkForConflicts(watchPluginKeys, plugin, globalConfig);
const hookSubscriber = hooks.getSubscriber();
if (plugin.apply) {
plugin.apply(hookSubscriber);
}
watchPlugins.push(plugin);
}
}
const failedTestsCache = new _FailedTestsCache.default();
let searchSources = contexts.map(context => ({
context,
searchSource: new _SearchSource.default(context)
}));
let isRunning = false;
let testWatcher;
let shouldDisplayWatchUsage = true;
let isWatchUsageDisplayed = false;
const emitFileChange = () => {
if (hooks.isUsed('onFileChange')) {
const projects = searchSources.map(({context, searchSource}) => ({
config: context.config,
testPaths: searchSource.findMatchingTests('').tests.map(t => t.path)
}));
hooks.getEmitter().onFileChange({
projects
});
}
};
emitFileChange();
hasteMapInstances.forEach((hasteMapInstance, index) => {
hasteMapInstance.on('change', ({eventsQueue, hasteFS, moduleMap}) => {
const validPaths = eventsQueue.filter(({filePath}) =>
(0, _isValidPath.default)(globalConfig, filePath)
);
if (validPaths.length) {
const context = (contexts[index] = (0, _createContext.default)(
contexts[index].config,
{
hasteFS,
moduleMap
}
));
activePlugin = null;
searchSources = searchSources.slice();
searchSources[index] = {
context,
searchSource: new _SearchSource.default(context)
};
emitFileChange();
startRun(globalConfig);
}
});
});
if (!hasExitListener) {
hasExitListener = true;
process.on('exit', () => {
if (activePlugin) {
outputStream.write(_ansiEscapes().default.cursorDown());
outputStream.write(_ansiEscapes().default.eraseDown);
}
});
}
const startRun = globalConfig => {
if (isRunning) {
return Promise.resolve(null);
}
testWatcher = new (_jestWatcher().TestWatcher)({
isWatchMode: true
});
_jestUtil().isInteractive &&
outputStream.write(_jestUtil().specialChars.CLEAR);
preRunMessagePrint(outputStream);
isRunning = true;
const configs = contexts.map(context => context.config);
const changedFilesPromise = (0, _getChangedFilesPromise.default)(
globalConfig,
configs
);
return (0, _runJest.default)({
changedFilesPromise,
contexts,
failedTestsCache,
filter,
globalConfig,
jestHooks: hooks.getEmitter(),
onComplete: results => {
isRunning = false;
hooks.getEmitter().onTestRunComplete(results);
// Create a new testWatcher instance so that re-runs won't be blocked.
// The old instance that was passed to Jest will still be interrupted
// and prevent test runs from the previous run.
testWatcher = new (_jestWatcher().TestWatcher)({
isWatchMode: true
});
// Do not show any Watch Usage related stuff when running in a
// non-interactive environment
if (_jestUtil().isInteractive) {
if (shouldDisplayWatchUsage) {
outputStream.write(usage(globalConfig, watchPlugins));
shouldDisplayWatchUsage = false; // hide Watch Usage after first run
isWatchUsageDisplayed = true;
} else {
outputStream.write(showToggleUsagePrompt());
shouldDisplayWatchUsage = false;
isWatchUsageDisplayed = false;
}
} else {
outputStream.write('\n');
}
failedTestsCache.setTestResults(results.testResults);
},
outputStream,
startRun,
testWatcher
}).catch(error =>
// Errors thrown inside `runJest`, e.g. by resolvers, are caught here for
// continuous watch mode execution. We need to reprint them to the
// terminal and give just a little bit of extra space so they fit below
// `preRunMessagePrint` message nicely.
console.error(
`\n\n${(0, _jestMessageUtil().formatExecError)(
error,
contexts[0].config,
{
noStackTrace: false
}
)}`
)
);
};
const onKeypress = key => {
if (
key === _jestWatcher().KEYS.CONTROL_C ||
key === _jestWatcher().KEYS.CONTROL_D
) {
if (typeof stdin.setRawMode === 'function') {
stdin.setRawMode(false);
}
outputStream.write('\n');
(0, _exit().default)(0);
return;
}
if (activePlugin != null && activePlugin.onKey) {
// if a plugin is activate, Jest should let it handle keystrokes, so ignore
// them here
activePlugin.onKey(key);
return;
}
// Abort test run
const pluginKeys = (0, _watchPluginsHelpers.getSortedUsageRows)(
watchPlugins,
globalConfig
).map(usage => Number(usage.key).toString(16));
if (
isRunning &&
testWatcher &&
['q', _jestWatcher().KEYS.ENTER, 'a', 'o', 'f']
.concat(pluginKeys)
.includes(key)
) {
testWatcher.setState({
interrupted: true
});
return;
}
const matchingWatchPlugin = (0,
_watchPluginsHelpers.filterInteractivePlugins)(
watchPlugins,
globalConfig
).find(plugin => getPluginKey(plugin, globalConfig) === key);
if (matchingWatchPlugin != null) {
if (isRunning) {
testWatcher.setState({
interrupted: true
});
return;
}
// "activate" the plugin, which has jest ignore keystrokes so the plugin
// can handle them
activePlugin = matchingWatchPlugin;
if (activePlugin.run) {
activePlugin.run(globalConfig, updateConfigAndRun).then(
shouldRerun => {
activePlugin = null;
if (shouldRerun) {
updateConfigAndRun();
}
},
() => {
activePlugin = null;
onCancelPatternPrompt();
}
);
} else {
activePlugin = null;
}
}
switch (key) {
case _jestWatcher().KEYS.ENTER:
startRun(globalConfig);
break;
case 'a':
globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
mode: 'watchAll',
testNamePattern: '',
testPathPattern: ''
});
startRun(globalConfig);
break;
case 'c':
updateConfigAndRun({
mode: 'watch',
testNamePattern: '',
testPathPattern: ''
});
break;
case 'f':
globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
onlyFailures: !globalConfig.onlyFailures
});
startRun(globalConfig);
break;
case 'o':
globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
mode: 'watch',
testNamePattern: '',
testPathPattern: ''
});
startRun(globalConfig);
break;
case '?':
break;
case 'w':
if (!shouldDisplayWatchUsage && !isWatchUsageDisplayed) {
outputStream.write(_ansiEscapes().default.cursorUp());
outputStream.write(_ansiEscapes().default.eraseDown);
outputStream.write(usage(globalConfig, watchPlugins));
isWatchUsageDisplayed = true;
shouldDisplayWatchUsage = false;
}
break;
}
};
const onCancelPatternPrompt = () => {
outputStream.write(_ansiEscapes().default.cursorHide);
outputStream.write(_jestUtil().specialChars.CLEAR);
outputStream.write(usage(globalConfig, watchPlugins));
outputStream.write(_ansiEscapes().default.cursorShow);
};
if (typeof stdin.setRawMode === 'function') {
stdin.setRawMode(true);
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', onKeypress);
}
startRun(globalConfig);
return Promise.resolve();
}
const checkForConflicts = (watchPluginKeys, plugin, globalConfig) => {
const key = getPluginKey(plugin, globalConfig);
if (!key) {
return;
}
const conflictor = watchPluginKeys.get(key);
if (!conflictor || conflictor.overwritable) {
watchPluginKeys.set(key, {
overwritable: false,
plugin
});
return;
}
let error;
if (conflictor.forbiddenOverwriteMessage) {
error = `
Watch plugin ${_chalk().default.bold.red(
getPluginIdentifier(plugin)
)} attempted to register key ${_chalk().default.bold.red(`<${key}>`)},
that is reserved internally for ${_chalk().default.bold.red(
conflictor.forbiddenOverwriteMessage
)}.
Please change the configuration key for this plugin.`.trim();
} else {
const plugins = [conflictor.plugin, plugin]
.map(p => _chalk().default.bold.red(getPluginIdentifier(p)))
.join(' and ');
error = `
Watch plugins ${plugins} both attempted to register key ${_chalk().default.bold.red(
`<${key}>`
)}.
Please change the key configuration for one of the conflicting plugins to avoid overlap.`.trim();
}
throw new (_jestValidate().ValidationError)(
'Watch plugin configuration error',
error
);
};
const getPluginIdentifier = plugin =>
// This breaks as `displayName` is not defined as a static, but since
// WatchPlugin is an interface, and it is my understanding interface
// static fields are not definable anymore, no idea how to circumvent
// this :-(
// @ts-expect-error: leave `displayName` be.
plugin.constructor.displayName || plugin.constructor.name;
const getPluginKey = (plugin, globalConfig) => {
if (typeof plugin.getUsageInfo === 'function') {
return (
plugin.getUsageInfo(globalConfig) || {
key: null
}
).key;
}
return null;
};
const usage = (globalConfig, watchPlugins, delimiter = '\n') => {
const messages = [
(0, _activeFiltersMessage.default)(globalConfig),
globalConfig.testPathPattern || globalConfig.testNamePattern
? `${_chalk().default.dim(' \u203A Press ')}c${_chalk().default.dim(
' to clear filters.'
)}`
: null,
`\n${_chalk().default.bold('Watch Usage')}`,
globalConfig.watch
? `${_chalk().default.dim(' \u203A Press ')}a${_chalk().default.dim(
' to run all tests.'
)}`
: null,
globalConfig.onlyFailures
? `${_chalk().default.dim(' \u203A Press ')}f${_chalk().default.dim(
' to quit "only failed tests" mode.'
)}`
: `${_chalk().default.dim(' \u203A Press ')}f${_chalk().default.dim(
' to run only failed tests.'
)}`,
(globalConfig.watchAll ||
globalConfig.testPathPattern ||
globalConfig.testNamePattern) &&
!globalConfig.noSCM
? `${_chalk().default.dim(' \u203A Press ')}o${_chalk().default.dim(
' to only run tests related to changed files.'
)}`
: null,
...(0, _watchPluginsHelpers.getSortedUsageRows)(
watchPlugins,
globalConfig
).map(
plugin =>
`${_chalk().default.dim(' \u203A Press')} ${
plugin.key
} ${_chalk().default.dim(`to ${plugin.prompt}.`)}`
),
`${_chalk().default.dim(' \u203A Press ')}Enter${_chalk().default.dim(
' to trigger a test run.'
)}`
];
return `${messages.filter(message => !!message).join(delimiter)}\n`;
};
const showToggleUsagePrompt = () =>
'\n' +
`${_chalk().default.bold('Watch Usage: ')}${_chalk().default.dim(
'Press '
)}w${_chalk().default.dim(' to show more.')}`;

View File

@@ -0,0 +1,22 @@
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Copyright Contributors to the Jest project.
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 @@
# `@jest/schemas`
Experimental and currently incomplete module for JSON schemas for [Jest's](https://jestjs.io/) configuration.

View File

@@ -0,0 +1,202 @@
import * as _sinclair_typebox0 from "@sinclair/typebox";
import { Static } from "@sinclair/typebox";
//#region src/index.d.ts
declare const SnapshotFormat: _sinclair_typebox0.TObject<{
callToJSON: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
compareKeys: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNull>;
escapeRegex: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
escapeString: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
highlight: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
indent: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
maxDepth: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
maxWidth: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
min: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
printBasicPrototype: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
printFunctionName: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
theme: _sinclair_typebox0.TOptional<_sinclair_typebox0.TObject<{
comment: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
content: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
prop: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
tag: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
value: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
}>>;
}>;
type SnapshotFormat = Static<typeof SnapshotFormat>;
declare const InitialOptions: _sinclair_typebox0.TObject<{
automock: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
bail: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TBoolean, _sinclair_typebox0.TNumber]>>;
cache: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
cacheDirectory: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
ci: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
clearMocks: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
changedFilesWithAncestor: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
changedSince: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
collectCoverage: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
collectCoverageFrom: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
coverageDirectory: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
coveragePathIgnorePatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
coverageProvider: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"babel">, _sinclair_typebox0.TLiteral<"v8">]>>;
coverageReporters: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"clover">, _sinclair_typebox0.TLiteral<"cobertura">, _sinclair_typebox0.TLiteral<"html-spa">, _sinclair_typebox0.TLiteral<"html">, _sinclair_typebox0.TLiteral<"json">, _sinclair_typebox0.TLiteral<"json-summary">, _sinclair_typebox0.TLiteral<"lcov">, _sinclair_typebox0.TLiteral<"lcovonly">, _sinclair_typebox0.TLiteral<"none">, _sinclair_typebox0.TLiteral<"teamcity">, _sinclair_typebox0.TLiteral<"text">, _sinclair_typebox0.TLiteral<"text-lcov">, _sinclair_typebox0.TLiteral<"text-summary">]>, _sinclair_typebox0.TTuple<[_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"clover">, _sinclair_typebox0.TLiteral<"cobertura">, _sinclair_typebox0.TLiteral<"html-spa">, _sinclair_typebox0.TLiteral<"html">, _sinclair_typebox0.TLiteral<"json">, _sinclair_typebox0.TLiteral<"json-summary">, _sinclair_typebox0.TLiteral<"lcov">, _sinclair_typebox0.TLiteral<"lcovonly">, _sinclair_typebox0.TLiteral<"none">, _sinclair_typebox0.TLiteral<"teamcity">, _sinclair_typebox0.TLiteral<"text">, _sinclair_typebox0.TLiteral<"text-lcov">, _sinclair_typebox0.TLiteral<"text-summary">]>, _sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown>]>]>>>;
coverageThreshold: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnsafe<{
[path: string]: {
branches?: number | undefined;
functions?: number | undefined;
lines?: number | undefined;
statements?: number | undefined;
};
global: Static<_sinclair_typebox0.TObject<{
branches: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
functions: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
lines: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
statements: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
}>>;
}>>;
dependencyExtractor: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
detectLeaks: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
detectOpenHandles: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
displayName: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TObject<{
name: _sinclair_typebox0.TString;
color: _sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"black">, _sinclair_typebox0.TLiteral<"red">, _sinclair_typebox0.TLiteral<"green">, _sinclair_typebox0.TLiteral<"yellow">, _sinclair_typebox0.TLiteral<"blue">, _sinclair_typebox0.TLiteral<"magenta">, _sinclair_typebox0.TLiteral<"cyan">, _sinclair_typebox0.TLiteral<"white">, _sinclair_typebox0.TLiteral<"gray">, _sinclair_typebox0.TLiteral<"grey">, _sinclair_typebox0.TLiteral<"blackBright">, _sinclair_typebox0.TLiteral<"redBright">, _sinclair_typebox0.TLiteral<"greenBright">, _sinclair_typebox0.TLiteral<"yellowBright">, _sinclair_typebox0.TLiteral<"blueBright">, _sinclair_typebox0.TLiteral<"magentaBright">, _sinclair_typebox0.TLiteral<"cyanBright">, _sinclair_typebox0.TLiteral<"whiteBright">]>;
}>]>>;
expand: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
extensionsToTreatAsEsm: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
fakeTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TIntersect<[_sinclair_typebox0.TObject<{
enableGlobally: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
}>, _sinclair_typebox0.TUnion<[_sinclair_typebox0.TObject<{
advanceTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TBoolean, _sinclair_typebox0.TNumber]>>;
doNotFake: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"Date">, _sinclair_typebox0.TLiteral<"hrtime">, _sinclair_typebox0.TLiteral<"nextTick">, _sinclair_typebox0.TLiteral<"performance">, _sinclair_typebox0.TLiteral<"queueMicrotask">, _sinclair_typebox0.TLiteral<"requestAnimationFrame">, _sinclair_typebox0.TLiteral<"cancelAnimationFrame">, _sinclair_typebox0.TLiteral<"requestIdleCallback">, _sinclair_typebox0.TLiteral<"cancelIdleCallback">, _sinclair_typebox0.TLiteral<"setImmediate">, _sinclair_typebox0.TLiteral<"clearImmediate">, _sinclair_typebox0.TLiteral<"setInterval">, _sinclair_typebox0.TLiteral<"clearInterval">, _sinclair_typebox0.TLiteral<"setTimeout">, _sinclair_typebox0.TLiteral<"clearTimeout">]>>>;
now: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
timerLimit: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
legacyFakeTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TLiteral<false>>;
}>, _sinclair_typebox0.TObject<{
legacyFakeTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TLiteral<true>>;
}>]>]>>;
filter: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
findRelatedTests: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
forceCoverageMatch: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
forceExit: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
json: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
globals: _sinclair_typebox0.TOptional<_sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown>>;
globalSetup: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
globalTeardown: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
haste: _sinclair_typebox0.TOptional<_sinclair_typebox0.TObject<{
computeSha1: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
defaultPlatform: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
forceNodeFilesystemAPI: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
enableSymlinks: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
hasteImplModulePath: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
platforms: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
throwOnModuleCollision: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
hasteMapModulePath: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
retainAllFiles: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
}>>;
id: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
injectGlobals: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
reporters: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TTuple<[_sinclair_typebox0.TString, _sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown>]>]>>>;
logHeapUsage: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
lastCommit: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
listTests: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
maxConcurrency: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
maxWorkers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TInteger]>>;
moduleDirectories: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
moduleFileExtensions: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
moduleNameMapper: _sinclair_typebox0.TOptional<_sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TArray<_sinclair_typebox0.TString>]>>>;
modulePathIgnorePatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
modulePaths: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
noStackTrace: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
notify: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
notifyMode: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
onlyChanged: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
onlyFailures: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
openHandlesTimeout: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
outputFile: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
passWithNoTests: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
preset: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
prettierPath: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
projects: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown>]>>>;
randomize: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
replname: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
resetMocks: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
resetModules: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
resolver: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TNull]>>;
restoreMocks: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
rootDir: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
roots: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
runner: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
runTestsByPath: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
runtime: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
sandboxInjectedGlobals: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
setupFiles: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
setupFilesAfterEnv: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
showSeed: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
silent: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
skipFilter: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
skipNodeResolution: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
slowTestThreshold: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
snapshotResolver: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
snapshotSerializers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
snapshotFormat: _sinclair_typebox0.TOptional<_sinclair_typebox0.TObject<{
callToJSON: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
compareKeys: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNull>;
escapeRegex: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
escapeString: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
highlight: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
indent: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
maxDepth: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
maxWidth: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
min: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
printBasicPrototype: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
printFunctionName: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
theme: _sinclair_typebox0.TOptional<_sinclair_typebox0.TObject<{
comment: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
content: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
prop: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
tag: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
value: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
}>>;
}>>;
errorOnDeprecated: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
testEnvironment: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
testEnvironmentOptions: _sinclair_typebox0.TOptional<_sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown>>;
testFailureExitCode: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
testLocationInResults: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
testMatch: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
testNamePattern: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
testPathIgnorePatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
testRegex: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TArray<_sinclair_typebox0.TString>]>>;
testResultsProcessor: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
testRunner: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
testSequencer: _sinclair_typebox0.TOptional<_sinclair_typebox0.TString>;
testTimeout: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
transform: _sinclair_typebox0.TOptional<_sinclair_typebox0.TRecord<_sinclair_typebox0.TString, _sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TTuple<[_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown]>]>>>;
transformIgnorePatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
watchPathIgnorePatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
unmockedModulePathPatterns: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TString>>;
updateSnapshot: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
useStderr: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
verbose: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
waitForUnhandledRejections: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
watch: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
watchAll: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
watchman: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
watchPlugins: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TString, _sinclair_typebox0.TTuple<[_sinclair_typebox0.TString, _sinclair_typebox0.TUnknown]>]>>>;
workerIdleMemoryLimit: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TNumber, _sinclair_typebox0.TString]>>;
workerThreads: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
}>;
type InitialOptions = Static<typeof InitialOptions>;
declare const FakeTimers: _sinclair_typebox0.TIntersect<[_sinclair_typebox0.TObject<{
enableGlobally: _sinclair_typebox0.TOptional<_sinclair_typebox0.TBoolean>;
}>, _sinclair_typebox0.TUnion<[_sinclair_typebox0.TObject<{
advanceTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TBoolean, _sinclair_typebox0.TNumber]>>;
doNotFake: _sinclair_typebox0.TOptional<_sinclair_typebox0.TArray<_sinclair_typebox0.TUnion<[_sinclair_typebox0.TLiteral<"Date">, _sinclair_typebox0.TLiteral<"hrtime">, _sinclair_typebox0.TLiteral<"nextTick">, _sinclair_typebox0.TLiteral<"performance">, _sinclair_typebox0.TLiteral<"queueMicrotask">, _sinclair_typebox0.TLiteral<"requestAnimationFrame">, _sinclair_typebox0.TLiteral<"cancelAnimationFrame">, _sinclair_typebox0.TLiteral<"requestIdleCallback">, _sinclair_typebox0.TLiteral<"cancelIdleCallback">, _sinclair_typebox0.TLiteral<"setImmediate">, _sinclair_typebox0.TLiteral<"clearImmediate">, _sinclair_typebox0.TLiteral<"setInterval">, _sinclair_typebox0.TLiteral<"clearInterval">, _sinclair_typebox0.TLiteral<"setTimeout">, _sinclair_typebox0.TLiteral<"clearTimeout">]>>>;
now: _sinclair_typebox0.TOptional<_sinclair_typebox0.TInteger>;
timerLimit: _sinclair_typebox0.TOptional<_sinclair_typebox0.TNumber>;
legacyFakeTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TLiteral<false>>;
}>, _sinclair_typebox0.TObject<{
legacyFakeTimers: _sinclair_typebox0.TOptional<_sinclair_typebox0.TLiteral<true>>;
}>]>]>;
type FakeTimers = Static<typeof FakeTimers>;
//#endregion
export { FakeTimers, InitialOptions, SnapshotFormat };

View File

@@ -0,0 +1,388 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {
Static,
TArray,
TBoolean,
TInteger,
TIntersect,
TLiteral,
TNull,
TNumber,
TObject,
TOptional,
TRecord,
TString,
TTuple,
TUnion,
TUnknown,
TUnsafe,
} from '@sinclair/typebox';
export declare const FakeTimers: TIntersect<
[
TObject<{
enableGlobally: TOptional<TBoolean>;
}>,
TUnion<
[
TObject<{
advanceTimers: TOptional<TUnion<[TBoolean, TNumber]>>;
doNotFake: TOptional<
TArray<
TUnion<
[
TLiteral<'Date'>,
TLiteral<'hrtime'>,
TLiteral<'nextTick'>,
TLiteral<'performance'>,
TLiteral<'queueMicrotask'>,
TLiteral<'requestAnimationFrame'>,
TLiteral<'cancelAnimationFrame'>,
TLiteral<'requestIdleCallback'>,
TLiteral<'cancelIdleCallback'>,
TLiteral<'setImmediate'>,
TLiteral<'clearImmediate'>,
TLiteral<'setInterval'>,
TLiteral<'clearInterval'>,
TLiteral<'setTimeout'>,
TLiteral<'clearTimeout'>,
]
>
>
>;
now: TOptional<TInteger>;
timerLimit: TOptional<TNumber>;
legacyFakeTimers: TOptional<TLiteral<false>>;
}>,
TObject<{
legacyFakeTimers: TOptional<TLiteral<true>>;
}>,
]
>,
]
>;
export declare type FakeTimers = Static<typeof FakeTimers>;
export declare const InitialOptions: TObject<{
automock: TOptional<TBoolean>;
bail: TOptional<TUnion<[TBoolean, TNumber]>>;
cache: TOptional<TBoolean>;
cacheDirectory: TOptional<TString>;
ci: TOptional<TBoolean>;
clearMocks: TOptional<TBoolean>;
changedFilesWithAncestor: TOptional<TBoolean>;
changedSince: TOptional<TString>;
collectCoverage: TOptional<TBoolean>;
collectCoverageFrom: TOptional<TArray<TString>>;
coverageDirectory: TOptional<TString>;
coveragePathIgnorePatterns: TOptional<TArray<TString>>;
coverageProvider: TOptional<TUnion<[TLiteral<'babel'>, TLiteral<'v8'>]>>;
coverageReporters: TOptional<
TArray<
TUnion<
[
TUnion<
[
TLiteral<'clover'>,
TLiteral<'cobertura'>,
TLiteral<'html-spa'>,
TLiteral<'html'>,
TLiteral<'json'>,
TLiteral<'json-summary'>,
TLiteral<'lcov'>,
TLiteral<'lcovonly'>,
TLiteral<'none'>,
TLiteral<'teamcity'>,
TLiteral<'text'>,
TLiteral<'text-lcov'>,
TLiteral<'text-summary'>,
]
>,
TTuple<
[
TUnion<
[
TLiteral<'clover'>,
TLiteral<'cobertura'>,
TLiteral<'html-spa'>,
TLiteral<'html'>,
TLiteral<'json'>,
TLiteral<'json-summary'>,
TLiteral<'lcov'>,
TLiteral<'lcovonly'>,
TLiteral<'none'>,
TLiteral<'teamcity'>,
TLiteral<'text'>,
TLiteral<'text-lcov'>,
TLiteral<'text-summary'>,
]
>,
TRecord<TString, TUnknown>,
]
>,
]
>
>
>;
coverageThreshold: TOptional<
TUnsafe<{
[path: string]: {
branches?: number | undefined;
functions?: number | undefined;
lines?: number | undefined;
statements?: number | undefined;
};
global: Static<
TObject<{
branches: TOptional<TNumber>;
functions: TOptional<TNumber>;
lines: TOptional<TNumber>;
statements: TOptional<TNumber>;
}>
>;
}>
>;
dependencyExtractor: TOptional<TString>;
detectLeaks: TOptional<TBoolean>;
detectOpenHandles: TOptional<TBoolean>;
displayName: TOptional<
TUnion<
[
TString,
TObject<{
name: TString;
color: TUnion<
[
TLiteral<'black'>,
TLiteral<'red'>,
TLiteral<'green'>,
TLiteral<'yellow'>,
TLiteral<'blue'>,
TLiteral<'magenta'>,
TLiteral<'cyan'>,
TLiteral<'white'>,
TLiteral<'gray'>,
TLiteral<'grey'>,
TLiteral<'blackBright'>,
TLiteral<'redBright'>,
TLiteral<'greenBright'>,
TLiteral<'yellowBright'>,
TLiteral<'blueBright'>,
TLiteral<'magentaBright'>,
TLiteral<'cyanBright'>,
TLiteral<'whiteBright'>,
]
>;
}>,
]
>
>;
expand: TOptional<TBoolean>;
extensionsToTreatAsEsm: TOptional<TArray<TString>>;
fakeTimers: TOptional<
TIntersect<
[
TObject<{
enableGlobally: TOptional<TBoolean>;
}>,
TUnion<
[
TObject<{
advanceTimers: TOptional<TUnion<[TBoolean, TNumber]>>;
doNotFake: TOptional<
TArray<
TUnion<
[
TLiteral<'Date'>,
TLiteral<'hrtime'>,
TLiteral<'nextTick'>,
TLiteral<'performance'>,
TLiteral<'queueMicrotask'>,
TLiteral<'requestAnimationFrame'>,
TLiteral<'cancelAnimationFrame'>,
TLiteral<'requestIdleCallback'>,
TLiteral<'cancelIdleCallback'>,
TLiteral<'setImmediate'>,
TLiteral<'clearImmediate'>,
TLiteral<'setInterval'>,
TLiteral<'clearInterval'>,
TLiteral<'setTimeout'>,
TLiteral<'clearTimeout'>,
]
>
>
>;
now: TOptional<TInteger>;
timerLimit: TOptional<TNumber>;
legacyFakeTimers: TOptional<TLiteral<false>>;
}>,
TObject<{
legacyFakeTimers: TOptional<TLiteral<true>>;
}>,
]
>,
]
>
>;
filter: TOptional<TString>;
findRelatedTests: TOptional<TBoolean>;
forceCoverageMatch: TOptional<TArray<TString>>;
forceExit: TOptional<TBoolean>;
json: TOptional<TBoolean>;
globals: TOptional<TRecord<TString, TUnknown>>;
globalSetup: TOptional<TUnion<[TString, TNull]>>;
globalTeardown: TOptional<TUnion<[TString, TNull]>>;
haste: TOptional<
TObject<{
computeSha1: TOptional<TBoolean>;
defaultPlatform: TOptional<TUnion<[TString, TNull]>>;
forceNodeFilesystemAPI: TOptional<TBoolean>;
enableSymlinks: TOptional<TBoolean>;
hasteImplModulePath: TOptional<TString>;
platforms: TOptional<TArray<TString>>;
throwOnModuleCollision: TOptional<TBoolean>;
hasteMapModulePath: TOptional<TString>;
retainAllFiles: TOptional<TBoolean>;
}>
>;
id: TOptional<TString>;
injectGlobals: TOptional<TBoolean>;
reporters: TOptional<
TArray<TUnion<[TString, TTuple<[TString, TRecord<TString, TUnknown>]>]>>
>;
logHeapUsage: TOptional<TBoolean>;
lastCommit: TOptional<TBoolean>;
listTests: TOptional<TBoolean>;
maxConcurrency: TOptional<TInteger>;
maxWorkers: TOptional<TUnion<[TString, TInteger]>>;
moduleDirectories: TOptional<TArray<TString>>;
moduleFileExtensions: TOptional<TArray<TString>>;
moduleNameMapper: TOptional<
TRecord<TString, TUnion<[TString, TArray<TString>]>>
>;
modulePathIgnorePatterns: TOptional<TArray<TString>>;
modulePaths: TOptional<TArray<TString>>;
noStackTrace: TOptional<TBoolean>;
notify: TOptional<TBoolean>;
notifyMode: TOptional<TString>;
onlyChanged: TOptional<TBoolean>;
onlyFailures: TOptional<TBoolean>;
openHandlesTimeout: TOptional<TNumber>;
outputFile: TOptional<TString>;
passWithNoTests: TOptional<TBoolean>;
preset: TOptional<TUnion<[TString, TNull]>>;
prettierPath: TOptional<TUnion<[TString, TNull]>>;
projects: TOptional<TArray<TUnion<[TString, TRecord<TString, TUnknown>]>>>;
randomize: TOptional<TBoolean>;
replname: TOptional<TUnion<[TString, TNull]>>;
resetMocks: TOptional<TBoolean>;
resetModules: TOptional<TBoolean>;
resolver: TOptional<TUnion<[TString, TNull]>>;
restoreMocks: TOptional<TBoolean>;
rootDir: TOptional<TString>;
roots: TOptional<TArray<TString>>;
runner: TOptional<TString>;
runTestsByPath: TOptional<TBoolean>;
runtime: TOptional<TString>;
sandboxInjectedGlobals: TOptional<TArray<TString>>;
setupFiles: TOptional<TArray<TString>>;
setupFilesAfterEnv: TOptional<TArray<TString>>;
showSeed: TOptional<TBoolean>;
silent: TOptional<TBoolean>;
skipFilter: TOptional<TBoolean>;
skipNodeResolution: TOptional<TBoolean>;
slowTestThreshold: TOptional<TNumber>;
snapshotResolver: TOptional<TString>;
snapshotSerializers: TOptional<TArray<TString>>;
snapshotFormat: TOptional<
TObject<{
callToJSON: TOptional<TBoolean>;
compareKeys: TOptional<TNull>;
escapeRegex: TOptional<TBoolean>;
escapeString: TOptional<TBoolean>;
highlight: TOptional<TBoolean>;
indent: TOptional<TInteger>;
maxDepth: TOptional<TInteger>;
maxWidth: TOptional<TInteger>;
min: TOptional<TBoolean>;
printBasicPrototype: TOptional<TBoolean>;
printFunctionName: TOptional<TBoolean>;
theme: TOptional<
TObject<{
comment: TOptional<TString>;
content: TOptional<TString>;
prop: TOptional<TString>;
tag: TOptional<TString>;
value: TOptional<TString>;
}>
>;
}>
>;
errorOnDeprecated: TOptional<TBoolean>;
testEnvironment: TOptional<TString>;
testEnvironmentOptions: TOptional<TRecord<TString, TUnknown>>;
testFailureExitCode: TOptional<TInteger>;
testLocationInResults: TOptional<TBoolean>;
testMatch: TOptional<TUnion<[TString, TArray<TString>]>>;
testNamePattern: TOptional<TString>;
testPathIgnorePatterns: TOptional<TArray<TString>>;
testRegex: TOptional<TUnion<[TString, TArray<TString>]>>;
testResultsProcessor: TOptional<TString>;
testRunner: TOptional<TString>;
testSequencer: TOptional<TString>;
testTimeout: TOptional<TNumber>;
transform: TOptional<
TRecord<TString, TUnion<[TString, TTuple<[TString, TUnknown]>]>>
>;
transformIgnorePatterns: TOptional<TArray<TString>>;
watchPathIgnorePatterns: TOptional<TArray<TString>>;
unmockedModulePathPatterns: TOptional<TArray<TString>>;
updateSnapshot: TOptional<TBoolean>;
useStderr: TOptional<TBoolean>;
verbose: TOptional<TBoolean>;
waitForUnhandledRejections: TOptional<TBoolean>;
watch: TOptional<TBoolean>;
watchAll: TOptional<TBoolean>;
watchman: TOptional<TBoolean>;
watchPlugins: TOptional<
TArray<TUnion<[TString, TTuple<[TString, TUnknown]>]>>
>;
workerIdleMemoryLimit: TOptional<TUnion<[TNumber, TString]>>;
workerThreads: TOptional<TBoolean>;
}>;
export declare type InitialOptions = Static<typeof InitialOptions>;
export declare const SnapshotFormat: TObject<{
callToJSON: TOptional<TBoolean>;
compareKeys: TOptional<TNull>;
escapeRegex: TOptional<TBoolean>;
escapeString: TOptional<TBoolean>;
highlight: TOptional<TBoolean>;
indent: TOptional<TInteger>;
maxDepth: TOptional<TInteger>;
maxWidth: TOptional<TInteger>;
min: TOptional<TBoolean>;
printBasicPrototype: TOptional<TBoolean>;
printFunctionName: TOptional<TBoolean>;
theme: TOptional<
TObject<{
comment: TOptional<TString>;
content: TOptional<TString>;
prop: TOptional<TString>;
tag: TOptional<TString>;
value: TOptional<TString>;
}>
>;
}>;
export declare type SnapshotFormat = Static<typeof SnapshotFormat>;
export {};

View File

@@ -0,0 +1,332 @@
/*!
* /**
* * Copyright (c) Meta Platforms, Inc. and affiliates.
* *
* * This source code is licensed under the MIT license found in the
* * LICENSE file in the root directory of this source tree.
* * /
*/
/******/ (() => { // webpackBootstrap
/******/ "use strict";
/******/ var __webpack_modules__ = ({
/***/ "./src/raw-types.ts":
/***/ ((__unused_webpack_module, exports) => {
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.SnapshotFormat = exports.InitialOptions = exports.FakeTimers = exports.CoverageReporterNames = exports.ChalkForegroundColors = void 0;
function _typebox() {
const data = require("@sinclair/typebox");
_typebox = function () {
return data;
};
return data;
}
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable sort-keys */
const SnapshotFormat = exports.SnapshotFormat = _typebox().Type.Partial(_typebox().Type.Object({
callToJSON: _typebox().Type.Boolean(),
compareKeys: _typebox().Type.Null(),
escapeRegex: _typebox().Type.Boolean(),
escapeString: _typebox().Type.Boolean(),
highlight: _typebox().Type.Boolean(),
indent: _typebox().Type.Integer({
minimum: 0
}),
maxDepth: _typebox().Type.Integer({
minimum: 0
}),
maxWidth: _typebox().Type.Integer({
minimum: 0
}),
min: _typebox().Type.Boolean(),
printBasicPrototype: _typebox().Type.Boolean(),
printFunctionName: _typebox().Type.Boolean(),
theme: _typebox().Type.Partial(_typebox().Type.Object({
comment: _typebox().Type.String(),
content: _typebox().Type.String(),
prop: _typebox().Type.String(),
tag: _typebox().Type.String(),
value: _typebox().Type.String()
}))
}));
const CoverageProvider = _typebox().Type.Union([_typebox().Type.Literal('babel'), _typebox().Type.Literal('v8')]);
const CoverageThresholdValue = _typebox().Type.Partial(_typebox().Type.Object({
branches: _typebox().Type.Number({
minimum: 0,
maximum: 100
}),
functions: _typebox().Type.Number({
minimum: 0,
maximum: 100
}),
lines: _typebox().Type.Number({
minimum: 0,
maximum: 100
}),
statements: _typebox().Type.Number({
minimum: 0,
maximum: 100
})
}));
const CoverageThresholdBase = _typebox().Type.Object({
global: CoverageThresholdValue
}, {
additionalProperties: CoverageThresholdValue
});
const CoverageThreshold = _typebox().Type.Unsafe(CoverageThresholdBase);
// TODO: add type test that these are all the colors available in chalk.ForegroundColor
const ChalkForegroundColors = exports.ChalkForegroundColors = _typebox().Type.Union([_typebox().Type.Literal('black'), _typebox().Type.Literal('red'), _typebox().Type.Literal('green'), _typebox().Type.Literal('yellow'), _typebox().Type.Literal('blue'), _typebox().Type.Literal('magenta'), _typebox().Type.Literal('cyan'), _typebox().Type.Literal('white'), _typebox().Type.Literal('gray'), _typebox().Type.Literal('grey'), _typebox().Type.Literal('blackBright'), _typebox().Type.Literal('redBright'), _typebox().Type.Literal('greenBright'), _typebox().Type.Literal('yellowBright'), _typebox().Type.Literal('blueBright'), _typebox().Type.Literal('magentaBright'), _typebox().Type.Literal('cyanBright'), _typebox().Type.Literal('whiteBright')]);
const DisplayName = _typebox().Type.Object({
name: _typebox().Type.String(),
color: ChalkForegroundColors
});
// TODO: verify these are the names of istanbulReport.ReportOptions
const CoverageReporterNames = exports.CoverageReporterNames = _typebox().Type.Union([_typebox().Type.Literal('clover'), _typebox().Type.Literal('cobertura'), _typebox().Type.Literal('html-spa'), _typebox().Type.Literal('html'), _typebox().Type.Literal('json'), _typebox().Type.Literal('json-summary'), _typebox().Type.Literal('lcov'), _typebox().Type.Literal('lcovonly'), _typebox().Type.Literal('none'), _typebox().Type.Literal('teamcity'), _typebox().Type.Literal('text'), _typebox().Type.Literal('text-lcov'), _typebox().Type.Literal('text-summary')]);
const CoverageReporters = _typebox().Type.Array(_typebox().Type.Union([CoverageReporterNames, _typebox().Type.Tuple([CoverageReporterNames, _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Unknown())])]));
const GlobalFakeTimersConfig = _typebox().Type.Partial(_typebox().Type.Object({
enableGlobally: _typebox().Type.Boolean({
description: 'Whether fake timers should be enabled globally for all test files.',
default: false
})
}));
const FakeableAPI = _typebox().Type.Union([_typebox().Type.Literal('Date'), _typebox().Type.Literal('hrtime'), _typebox().Type.Literal('nextTick'), _typebox().Type.Literal('performance'), _typebox().Type.Literal('queueMicrotask'), _typebox().Type.Literal('requestAnimationFrame'), _typebox().Type.Literal('cancelAnimationFrame'), _typebox().Type.Literal('requestIdleCallback'), _typebox().Type.Literal('cancelIdleCallback'), _typebox().Type.Literal('setImmediate'), _typebox().Type.Literal('clearImmediate'), _typebox().Type.Literal('setInterval'), _typebox().Type.Literal('clearInterval'), _typebox().Type.Literal('setTimeout'), _typebox().Type.Literal('clearTimeout')]);
const FakeTimersConfig = _typebox().Type.Partial(_typebox().Type.Object({
advanceTimers: _typebox().Type.Union([_typebox().Type.Boolean(), _typebox().Type.Number({
minimum: 0
})], {
description: 'If set to `true` all timers will be advanced automatically by 20 milliseconds every 20 milliseconds. A custom ' + 'time delta may be provided by passing a number.',
default: false
}),
doNotFake: _typebox().Type.Array(FakeableAPI, {
description: 'List of names of APIs (e.g. `Date`, `nextTick()`, `setImmediate()`, `setTimeout()`) that should not be faked.' + '\n\nThe default is `[]`, meaning all APIs are faked.',
default: []
}),
now: _typebox().Type.Integer({
minimum: 0,
description: 'Sets current system time to be used by fake timers.\n\nThe default is `Date.now()`.'
}),
timerLimit: _typebox().Type.Number({
description: 'The maximum number of recursive timers that will be run when calling `jest.runAllTimers()`.',
default: 100_000,
minimum: 0
}),
legacyFakeTimers: _typebox().Type.Literal(false, {
description: 'Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.',
default: false
})
}));
const LegacyFakeTimersConfig = _typebox().Type.Partial(_typebox().Type.Object({
legacyFakeTimers: _typebox().Type.Literal(true, {
description: 'Use the old fake timers implementation instead of one backed by `@sinonjs/fake-timers`.',
default: true
})
}));
const FakeTimers = exports.FakeTimers = _typebox().Type.Intersect([GlobalFakeTimersConfig, _typebox().Type.Union([FakeTimersConfig, LegacyFakeTimersConfig])]);
const HasteConfig = _typebox().Type.Partial(_typebox().Type.Object({
computeSha1: _typebox().Type.Boolean({
description: 'Whether to hash files using SHA-1.'
}),
defaultPlatform: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()], {
description: 'The platform to use as the default, e.g. `ios`.'
}),
forceNodeFilesystemAPI: _typebox().Type.Boolean({
description: "Whether to force the use of Node's `fs` API when reading files rather than shelling out to `find`."
}),
enableSymlinks: _typebox().Type.Boolean({
description: 'Whether to follow symlinks when crawling for files.' + '\n\tThis options cannot be used in projects which use watchman.' + '\n\tProjects with `watchman` set to true will error if this option is set to true.'
}),
hasteImplModulePath: _typebox().Type.String({
description: 'Path to a custom implementation of Haste.'
}),
platforms: _typebox().Type.Array(_typebox().Type.String(), {
description: "All platforms to target, e.g ['ios', 'android']."
}),
throwOnModuleCollision: _typebox().Type.Boolean({
description: 'Whether to throw an error on module collision.'
}),
hasteMapModulePath: _typebox().Type.String({
description: 'Custom HasteMap module'
}),
retainAllFiles: _typebox().Type.Boolean({
description: 'Whether to retain all files, allowing e.g. search for tests in `node_modules`.'
})
}));
const InitialOptions = exports.InitialOptions = _typebox().Type.Partial(_typebox().Type.Object({
automock: _typebox().Type.Boolean(),
bail: _typebox().Type.Union([_typebox().Type.Boolean(), _typebox().Type.Number()]),
cache: _typebox().Type.Boolean(),
cacheDirectory: _typebox().Type.String(),
ci: _typebox().Type.Boolean(),
clearMocks: _typebox().Type.Boolean(),
changedFilesWithAncestor: _typebox().Type.Boolean(),
changedSince: _typebox().Type.String(),
collectCoverage: _typebox().Type.Boolean(),
collectCoverageFrom: _typebox().Type.Array(_typebox().Type.String()),
coverageDirectory: _typebox().Type.String(),
coveragePathIgnorePatterns: _typebox().Type.Array(_typebox().Type.String()),
coverageProvider: CoverageProvider,
coverageReporters: CoverageReporters,
coverageThreshold: CoverageThreshold,
dependencyExtractor: _typebox().Type.String(),
detectLeaks: _typebox().Type.Boolean(),
detectOpenHandles: _typebox().Type.Boolean(),
displayName: _typebox().Type.Union([_typebox().Type.String(), DisplayName]),
expand: _typebox().Type.Boolean(),
extensionsToTreatAsEsm: _typebox().Type.Array(_typebox().Type.String()),
fakeTimers: FakeTimers,
filter: _typebox().Type.String(),
findRelatedTests: _typebox().Type.Boolean(),
forceCoverageMatch: _typebox().Type.Array(_typebox().Type.String()),
forceExit: _typebox().Type.Boolean(),
json: _typebox().Type.Boolean(),
globals: _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Unknown()),
globalSetup: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
globalTeardown: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
haste: HasteConfig,
id: _typebox().Type.String(),
injectGlobals: _typebox().Type.Boolean(),
reporters: _typebox().Type.Array(_typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Tuple([_typebox().Type.String(), _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Unknown())])])),
logHeapUsage: _typebox().Type.Boolean(),
lastCommit: _typebox().Type.Boolean(),
listTests: _typebox().Type.Boolean(),
maxConcurrency: _typebox().Type.Integer(),
maxWorkers: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Integer()]),
moduleDirectories: _typebox().Type.Array(_typebox().Type.String()),
moduleFileExtensions: _typebox().Type.Array(_typebox().Type.String()),
moduleNameMapper: _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Array(_typebox().Type.String())])),
modulePathIgnorePatterns: _typebox().Type.Array(_typebox().Type.String()),
modulePaths: _typebox().Type.Array(_typebox().Type.String()),
noStackTrace: _typebox().Type.Boolean(),
notify: _typebox().Type.Boolean(),
notifyMode: _typebox().Type.String(),
onlyChanged: _typebox().Type.Boolean(),
onlyFailures: _typebox().Type.Boolean(),
openHandlesTimeout: _typebox().Type.Number(),
outputFile: _typebox().Type.String(),
passWithNoTests: _typebox().Type.Boolean(),
preset: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
prettierPath: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
projects: _typebox().Type.Array(_typebox().Type.Union([_typebox().Type.String(),
// TODO: Make sure to type these correctly
_typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Unknown())])),
randomize: _typebox().Type.Boolean(),
replname: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
resetMocks: _typebox().Type.Boolean(),
resetModules: _typebox().Type.Boolean(),
resolver: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Null()]),
restoreMocks: _typebox().Type.Boolean(),
rootDir: _typebox().Type.String(),
roots: _typebox().Type.Array(_typebox().Type.String()),
runner: _typebox().Type.String(),
runTestsByPath: _typebox().Type.Boolean(),
runtime: _typebox().Type.String(),
sandboxInjectedGlobals: _typebox().Type.Array(_typebox().Type.String()),
setupFiles: _typebox().Type.Array(_typebox().Type.String()),
setupFilesAfterEnv: _typebox().Type.Array(_typebox().Type.String()),
showSeed: _typebox().Type.Boolean(),
silent: _typebox().Type.Boolean(),
skipFilter: _typebox().Type.Boolean(),
skipNodeResolution: _typebox().Type.Boolean(),
slowTestThreshold: _typebox().Type.Number(),
snapshotResolver: _typebox().Type.String(),
snapshotSerializers: _typebox().Type.Array(_typebox().Type.String()),
snapshotFormat: SnapshotFormat,
errorOnDeprecated: _typebox().Type.Boolean(),
testEnvironment: _typebox().Type.String(),
testEnvironmentOptions: _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Unknown()),
testFailureExitCode: _typebox().Type.Integer(),
testLocationInResults: _typebox().Type.Boolean(),
testMatch: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Array(_typebox().Type.String())]),
testNamePattern: _typebox().Type.String(),
testPathIgnorePatterns: _typebox().Type.Array(_typebox().Type.String()),
testRegex: _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Array(_typebox().Type.String())]),
testResultsProcessor: _typebox().Type.String(),
testRunner: _typebox().Type.String(),
testSequencer: _typebox().Type.String(),
testTimeout: _typebox().Type.Number(),
transform: _typebox().Type.Record(_typebox().Type.String(), _typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Tuple([_typebox().Type.String(), _typebox().Type.Unknown()])])),
transformIgnorePatterns: _typebox().Type.Array(_typebox().Type.String()),
watchPathIgnorePatterns: _typebox().Type.Array(_typebox().Type.String()),
unmockedModulePathPatterns: _typebox().Type.Array(_typebox().Type.String()),
updateSnapshot: _typebox().Type.Boolean(),
useStderr: _typebox().Type.Boolean(),
verbose: _typebox().Type.Boolean(),
waitForUnhandledRejections: _typebox().Type.Boolean(),
watch: _typebox().Type.Boolean(),
watchAll: _typebox().Type.Boolean(),
watchman: _typebox().Type.Boolean(),
watchPlugins: _typebox().Type.Array(_typebox().Type.Union([_typebox().Type.String(), _typebox().Type.Tuple([_typebox().Type.String(), _typebox().Type.Unknown()])])),
workerIdleMemoryLimit: _typebox().Type.Union([_typebox().Type.Number(), _typebox().Type.String()]),
workerThreads: _typebox().Type.Boolean()
}));
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
(() => {
var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({
value: true
}));
exports.SnapshotFormat = exports.InitialOptions = exports.FakeTimers = void 0;
var types = _interopRequireWildcard(__webpack_require__("./src/raw-types.ts"));
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const SnapshotFormat = exports.SnapshotFormat = types.SnapshotFormat;
const InitialOptions = exports.InitialOptions = types.InitialOptions;
const FakeTimers = exports.FakeTimers = types.FakeTimers;
})();
module.exports = __webpack_exports__;
/******/ })()
;

View File

@@ -0,0 +1,5 @@
import cjsModule from './index.js';
export const FakeTimers = cjsModule.FakeTimers;
export const InitialOptions = cjsModule.InitialOptions;
export const SnapshotFormat = cjsModule.SnapshotFormat;

View File

@@ -0,0 +1,31 @@
{
"name": "@jest/schemas",
"version": "30.0.5",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-schemas"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"require": "./build/index.js",
"import": "./build/index.mjs",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@sinclair/typebox": "^0.34.0"
},
"engines": {
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "22236cf58b66039f81893537c90dee290bab427f"
}

View File

@@ -0,0 +1,55 @@
import { ValueErrorIterator } from '../errors/index';
import { TypeBoxError } from '../type/error/index';
import type { TSchema } from '../type/schema/index';
import type { Static, StaticDecode, StaticEncode } from '../type/static/index';
export type CheckFunction = (value: unknown) => boolean;
export declare class TypeCheck<T extends TSchema> {
private readonly schema;
private readonly references;
private readonly checkFunc;
private readonly code;
private readonly hasTransform;
constructor(schema: T, references: TSchema[], checkFunc: CheckFunction, code: string);
/** Returns the generated assertion code used to validate this type. */
Code(): string;
/** Returns the schema type used to validate */
Schema(): T;
/** Returns reference types used to validate */
References(): TSchema[];
/** Returns an iterator for each error in this value. */
Errors(value: unknown): ValueErrorIterator;
/** Returns true if the value matches the compiled type. */
Check(value: unknown): value is Static<T>;
/** Decodes a value or throws if error */
Decode<Static = StaticDecode<T>, Result extends Static = Static>(value: unknown): Result;
/** Encodes a value or throws if error */
Encode<Static = StaticEncode<T>, Result extends Static = Static>(value: unknown): Result;
}
export declare class TypeCompilerUnknownTypeError extends TypeBoxError {
readonly schema: TSchema;
constructor(schema: TSchema);
}
export declare class TypeCompilerTypeGuardError extends TypeBoxError {
readonly schema: TSchema;
constructor(schema: TSchema);
}
export declare namespace Policy {
function IsExactOptionalProperty(value: string, key: string, expression: string): string;
function IsObjectLike(value: string): string;
function IsRecordLike(value: string): string;
function IsNumberLike(value: string): string;
function IsVoidLike(value: string): string;
}
export type TypeCompilerLanguageOption = 'typescript' | 'javascript';
export interface TypeCompilerCodegenOptions {
language?: TypeCompilerLanguageOption;
}
/** Compiles Types for Runtime Type Checking */
export declare namespace TypeCompiler {
/** Generates the code used to assert this type and returns it as a string */
function Code<T extends TSchema>(schema: T, references: TSchema[], options?: TypeCompilerCodegenOptions): string;
/** Generates the code used to assert this type and returns it as a string */
function Code<T extends TSchema>(schema: T, options?: TypeCompilerCodegenOptions): string;
/** Compiles a TypeBox type for optimal runtime type checking. Types must be valid TypeBox types of TSchema */
function Compile<T extends TSchema>(schema: T, references?: TSchema[]): TypeCheck<T>;
}

View File

@@ -0,0 +1,669 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeCompiler = exports.Policy = exports.TypeCompilerTypeGuardError = exports.TypeCompilerUnknownTypeError = exports.TypeCheck = void 0;
const index_1 = require("../value/transform/index");
const index_2 = require("../errors/index");
const index_3 = require("../system/index");
const index_4 = require("../type/error/index");
const index_5 = require("../value/deref/index");
const index_6 = require("../value/hash/index");
const index_7 = require("../type/symbols/index");
const index_8 = require("../type/registry/index");
const index_9 = require("../type/keyof/index");
const extends_undefined_1 = require("../type/extends/extends-undefined");
const index_10 = require("../type/never/index");
const index_11 = require("../type/ref/index");
// ------------------------------------------------------------------
// ValueGuard
// ------------------------------------------------------------------
const index_12 = require("../value/guard/index");
// ------------------------------------------------------------------
// TypeGuard
// ------------------------------------------------------------------
const type_1 = require("../type/guard/type");
// ------------------------------------------------------------------
// TypeCheck
// ------------------------------------------------------------------
class TypeCheck {
constructor(schema, references, checkFunc, code) {
this.schema = schema;
this.references = references;
this.checkFunc = checkFunc;
this.code = code;
this.hasTransform = (0, index_1.HasTransform)(schema, references);
}
/** Returns the generated assertion code used to validate this type. */
Code() {
return this.code;
}
/** Returns the schema type used to validate */
Schema() {
return this.schema;
}
/** Returns reference types used to validate */
References() {
return this.references;
}
/** Returns an iterator for each error in this value. */
Errors(value) {
return (0, index_2.Errors)(this.schema, this.references, value);
}
/** Returns true if the value matches the compiled type. */
Check(value) {
return this.checkFunc(value);
}
/** Decodes a value or throws if error */
Decode(value) {
if (!this.checkFunc(value))
throw new index_1.TransformDecodeCheckError(this.schema, value, this.Errors(value).First());
return (this.hasTransform ? (0, index_1.TransformDecode)(this.schema, this.references, value) : value);
}
/** Encodes a value or throws if error */
Encode(value) {
const encoded = this.hasTransform ? (0, index_1.TransformEncode)(this.schema, this.references, value) : value;
if (!this.checkFunc(encoded))
throw new index_1.TransformEncodeCheckError(this.schema, value, this.Errors(value).First());
return encoded;
}
}
exports.TypeCheck = TypeCheck;
// ------------------------------------------------------------------
// Character
// ------------------------------------------------------------------
var Character;
(function (Character) {
function DollarSign(code) {
return code === 36;
}
Character.DollarSign = DollarSign;
function IsUnderscore(code) {
return code === 95;
}
Character.IsUnderscore = IsUnderscore;
function IsAlpha(code) {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
Character.IsAlpha = IsAlpha;
function IsNumeric(code) {
return code >= 48 && code <= 57;
}
Character.IsNumeric = IsNumeric;
})(Character || (Character = {}));
// ------------------------------------------------------------------
// MemberExpression
// ------------------------------------------------------------------
var MemberExpression;
(function (MemberExpression) {
function IsFirstCharacterNumeric(value) {
if (value.length === 0)
return false;
return Character.IsNumeric(value.charCodeAt(0));
}
function IsAccessor(value) {
if (IsFirstCharacterNumeric(value))
return false;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
const check = Character.IsAlpha(code) || Character.IsNumeric(code) || Character.DollarSign(code) || Character.IsUnderscore(code);
if (!check)
return false;
}
return true;
}
function EscapeHyphen(key) {
return key.replace(/'/g, "\\'");
}
function Encode(object, key) {
return IsAccessor(key) ? `${object}.${key}` : `${object}['${EscapeHyphen(key)}']`;
}
MemberExpression.Encode = Encode;
})(MemberExpression || (MemberExpression = {}));
// ------------------------------------------------------------------
// Identifier
// ------------------------------------------------------------------
var Identifier;
(function (Identifier) {
function Encode($id) {
const buffer = [];
for (let i = 0; i < $id.length; i++) {
const code = $id.charCodeAt(i);
if (Character.IsNumeric(code) || Character.IsAlpha(code)) {
buffer.push($id.charAt(i));
}
else {
buffer.push(`_${code}_`);
}
}
return buffer.join('').replace(/__/g, '_');
}
Identifier.Encode = Encode;
})(Identifier || (Identifier = {}));
// ------------------------------------------------------------------
// LiteralString
// ------------------------------------------------------------------
var LiteralString;
(function (LiteralString) {
function Escape(content) {
return content.replace(/'/g, "\\'");
}
LiteralString.Escape = Escape;
})(LiteralString || (LiteralString = {}));
// ------------------------------------------------------------------
// Errors
// ------------------------------------------------------------------
class TypeCompilerUnknownTypeError extends index_4.TypeBoxError {
constructor(schema) {
super('Unknown type');
this.schema = schema;
}
}
exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
class TypeCompilerTypeGuardError extends index_4.TypeBoxError {
constructor(schema) {
super('Preflight validation check failed to guard for the given schema');
this.schema = schema;
}
}
exports.TypeCompilerTypeGuardError = TypeCompilerTypeGuardError;
// ------------------------------------------------------------------
// Policy
// ------------------------------------------------------------------
var Policy;
(function (Policy) {
function IsExactOptionalProperty(value, key, expression) {
return index_3.TypeSystemPolicy.ExactOptionalPropertyTypes ? `('${key}' in ${value} ? ${expression} : true)` : `(${MemberExpression.Encode(value, key)} !== undefined ? ${expression} : true)`;
}
Policy.IsExactOptionalProperty = IsExactOptionalProperty;
function IsObjectLike(value) {
return !index_3.TypeSystemPolicy.AllowArrayObject ? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))` : `(typeof ${value} === 'object' && ${value} !== null)`;
}
Policy.IsObjectLike = IsObjectLike;
function IsRecordLike(value) {
return !index_3.TypeSystemPolicy.AllowArrayObject
? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}) && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`
: `(typeof ${value} === 'object' && ${value} !== null && !(${value} instanceof Date) && !(${value} instanceof Uint8Array))`;
}
Policy.IsRecordLike = IsRecordLike;
function IsNumberLike(value) {
return index_3.TypeSystemPolicy.AllowNaN ? `typeof ${value} === 'number'` : `Number.isFinite(${value})`;
}
Policy.IsNumberLike = IsNumberLike;
function IsVoidLike(value) {
return index_3.TypeSystemPolicy.AllowNullVoid ? `(${value} === undefined || ${value} === null)` : `${value} === undefined`;
}
Policy.IsVoidLike = IsVoidLike;
})(Policy || (exports.Policy = Policy = {}));
/** Compiles Types for Runtime Type Checking */
var TypeCompiler;
(function (TypeCompiler) {
// ----------------------------------------------------------------
// Guards
// ----------------------------------------------------------------
function IsAnyOrUnknown(schema) {
return schema[index_7.Kind] === 'Any' || schema[index_7.Kind] === 'Unknown';
}
// ----------------------------------------------------------------
// Types
// ----------------------------------------------------------------
function* FromAny(schema, references, value) {
yield 'true';
}
function* FromArgument(schema, references, value) {
yield 'true';
}
function* FromArray(schema, references, value) {
yield `Array.isArray(${value})`;
const [parameter, accumulator] = [CreateParameter('value', 'any'), CreateParameter('acc', 'number')];
if ((0, index_12.IsNumber)(schema.maxItems))
yield `${value}.length <= ${schema.maxItems}`;
if ((0, index_12.IsNumber)(schema.minItems))
yield `${value}.length >= ${schema.minItems}`;
const elementExpression = CreateExpression(schema.items, references, 'value');
yield `${value}.every((${parameter}) => ${elementExpression})`;
if ((0, type_1.IsSchema)(schema.contains) || (0, index_12.IsNumber)(schema.minContains) || (0, index_12.IsNumber)(schema.maxContains)) {
const containsSchema = (0, type_1.IsSchema)(schema.contains) ? schema.contains : (0, index_10.Never)();
const checkExpression = CreateExpression(containsSchema, references, 'value');
const checkMinContains = (0, index_12.IsNumber)(schema.minContains) ? [`(count >= ${schema.minContains})`] : [];
const checkMaxContains = (0, index_12.IsNumber)(schema.maxContains) ? [`(count <= ${schema.maxContains})`] : [];
const checkCount = `const count = value.reduce((${accumulator}, ${parameter}) => ${checkExpression} ? acc + 1 : acc, 0)`;
const check = [`(count > 0)`, ...checkMinContains, ...checkMaxContains].join(' && ');
yield `((${parameter}) => { ${checkCount}; return ${check}})(${value})`;
}
if (schema.uniqueItems === true) {
const check = `const hashed = hash(element); if(set.has(hashed)) { return false } else { set.add(hashed) } } return true`;
const block = `const set = new Set(); for(const element of value) { ${check} }`;
yield `((${parameter}) => { ${block} )(${value})`;
}
}
function* FromAsyncIterator(schema, references, value) {
yield `(typeof value === 'object' && Symbol.asyncIterator in ${value})`;
}
function* FromBigInt(schema, references, value) {
yield `(typeof ${value} === 'bigint')`;
if ((0, index_12.IsBigInt)(schema.exclusiveMaximum))
yield `${value} < BigInt(${schema.exclusiveMaximum})`;
if ((0, index_12.IsBigInt)(schema.exclusiveMinimum))
yield `${value} > BigInt(${schema.exclusiveMinimum})`;
if ((0, index_12.IsBigInt)(schema.maximum))
yield `${value} <= BigInt(${schema.maximum})`;
if ((0, index_12.IsBigInt)(schema.minimum))
yield `${value} >= BigInt(${schema.minimum})`;
if ((0, index_12.IsBigInt)(schema.multipleOf))
yield `(${value} % BigInt(${schema.multipleOf})) === 0`;
}
function* FromBoolean(schema, references, value) {
yield `(typeof ${value} === 'boolean')`;
}
function* FromConstructor(schema, references, value) {
yield* Visit(schema.returns, references, `${value}.prototype`);
}
function* FromDate(schema, references, value) {
yield `(${value} instanceof Date) && Number.isFinite(${value}.getTime())`;
if ((0, index_12.IsNumber)(schema.exclusiveMaximumTimestamp))
yield `${value}.getTime() < ${schema.exclusiveMaximumTimestamp}`;
if ((0, index_12.IsNumber)(schema.exclusiveMinimumTimestamp))
yield `${value}.getTime() > ${schema.exclusiveMinimumTimestamp}`;
if ((0, index_12.IsNumber)(schema.maximumTimestamp))
yield `${value}.getTime() <= ${schema.maximumTimestamp}`;
if ((0, index_12.IsNumber)(schema.minimumTimestamp))
yield `${value}.getTime() >= ${schema.minimumTimestamp}`;
if ((0, index_12.IsNumber)(schema.multipleOfTimestamp))
yield `(${value}.getTime() % ${schema.multipleOfTimestamp}) === 0`;
}
function* FromFunction(schema, references, value) {
yield `(typeof ${value} === 'function')`;
}
function* FromImport(schema, references, value) {
const members = globalThis.Object.getOwnPropertyNames(schema.$defs).reduce((result, key) => {
return [...result, schema.$defs[key]];
}, []);
yield* Visit((0, index_11.Ref)(schema.$ref), [...references, ...members], value);
}
function* FromInteger(schema, references, value) {
yield `Number.isInteger(${value})`;
if ((0, index_12.IsNumber)(schema.exclusiveMaximum))
yield `${value} < ${schema.exclusiveMaximum}`;
if ((0, index_12.IsNumber)(schema.exclusiveMinimum))
yield `${value} > ${schema.exclusiveMinimum}`;
if ((0, index_12.IsNumber)(schema.maximum))
yield `${value} <= ${schema.maximum}`;
if ((0, index_12.IsNumber)(schema.minimum))
yield `${value} >= ${schema.minimum}`;
if ((0, index_12.IsNumber)(schema.multipleOf))
yield `(${value} % ${schema.multipleOf}) === 0`;
}
function* FromIntersect(schema, references, value) {
const check1 = schema.allOf.map((schema) => CreateExpression(schema, references, value)).join(' && ');
if (schema.unevaluatedProperties === false) {
const keyCheck = CreateVariable(`${new RegExp((0, index_9.KeyOfPattern)(schema))};`);
const check2 = `Object.getOwnPropertyNames(${value}).every(key => ${keyCheck}.test(key))`;
yield `(${check1} && ${check2})`;
}
else if ((0, type_1.IsSchema)(schema.unevaluatedProperties)) {
const keyCheck = CreateVariable(`${new RegExp((0, index_9.KeyOfPattern)(schema))};`);
const check2 = `Object.getOwnPropertyNames(${value}).every(key => ${keyCheck}.test(key) || ${CreateExpression(schema.unevaluatedProperties, references, `${value}[key]`)})`;
yield `(${check1} && ${check2})`;
}
else {
yield `(${check1})`;
}
}
function* FromIterator(schema, references, value) {
yield `(typeof value === 'object' && Symbol.iterator in ${value})`;
}
function* FromLiteral(schema, references, value) {
if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
yield `(${value} === ${schema.const})`;
}
else {
yield `(${value} === '${LiteralString.Escape(schema.const)}')`;
}
}
function* FromNever(schema, references, value) {
yield `false`;
}
function* FromNot(schema, references, value) {
const expression = CreateExpression(schema.not, references, value);
yield `(!${expression})`;
}
function* FromNull(schema, references, value) {
yield `(${value} === null)`;
}
function* FromNumber(schema, references, value) {
yield Policy.IsNumberLike(value);
if ((0, index_12.IsNumber)(schema.exclusiveMaximum))
yield `${value} < ${schema.exclusiveMaximum}`;
if ((0, index_12.IsNumber)(schema.exclusiveMinimum))
yield `${value} > ${schema.exclusiveMinimum}`;
if ((0, index_12.IsNumber)(schema.maximum))
yield `${value} <= ${schema.maximum}`;
if ((0, index_12.IsNumber)(schema.minimum))
yield `${value} >= ${schema.minimum}`;
if ((0, index_12.IsNumber)(schema.multipleOf))
yield `(${value} % ${schema.multipleOf}) === 0`;
}
function* FromObject(schema, references, value) {
yield Policy.IsObjectLike(value);
if ((0, index_12.IsNumber)(schema.minProperties))
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
if ((0, index_12.IsNumber)(schema.maxProperties))
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
const knownKeys = Object.getOwnPropertyNames(schema.properties);
for (const knownKey of knownKeys) {
const memberExpression = MemberExpression.Encode(value, knownKey);
const property = schema.properties[knownKey];
if (schema.required && schema.required.includes(knownKey)) {
yield* Visit(property, references, memberExpression);
if ((0, extends_undefined_1.ExtendsUndefinedCheck)(property) || IsAnyOrUnknown(property))
yield `('${knownKey}' in ${value})`;
}
else {
const expression = CreateExpression(property, references, memberExpression);
yield Policy.IsExactOptionalProperty(value, knownKey, expression);
}
}
if (schema.additionalProperties === false) {
if (schema.required && schema.required.length === knownKeys.length) {
yield `Object.getOwnPropertyNames(${value}).length === ${knownKeys.length}`;
}
else {
const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key))`;
}
}
if (typeof schema.additionalProperties === 'object') {
const expression = CreateExpression(schema.additionalProperties, references, `${value}[key]`);
const keys = `[${knownKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `(Object.getOwnPropertyNames(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
}
}
function* FromPromise(schema, references, value) {
yield `${value} instanceof Promise`;
}
function* FromRecord(schema, references, value) {
yield Policy.IsRecordLike(value);
if ((0, index_12.IsNumber)(schema.minProperties))
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
if ((0, index_12.IsNumber)(schema.maxProperties))
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
const [patternKey, patternSchema] = Object.entries(schema.patternProperties)[0];
const variable = CreateVariable(`${new RegExp(patternKey)}`);
const check1 = CreateExpression(patternSchema, references, 'value');
const check2 = (0, type_1.IsSchema)(schema.additionalProperties) ? CreateExpression(schema.additionalProperties, references, value) : schema.additionalProperties === false ? 'false' : 'true';
const expression = `(${variable}.test(key) ? ${check1} : ${check2})`;
yield `(Object.entries(${value}).every(([key, value]) => ${expression}))`;
}
function* FromRef(schema, references, value) {
const target = (0, index_5.Deref)(schema, references);
// Reference: If we have seen this reference before we can just yield and return the function call.
// If this isn't the case we defer to visit to generate and set the function for subsequent passes.
if (state.functions.has(schema.$ref))
return yield `${CreateFunctionName(schema.$ref)}(${value})`;
yield* Visit(target, references, value);
}
function* FromRegExp(schema, references, value) {
const variable = CreateVariable(`${new RegExp(schema.source, schema.flags)};`);
yield `(typeof ${value} === 'string')`;
if ((0, index_12.IsNumber)(schema.maxLength))
yield `${value}.length <= ${schema.maxLength}`;
if ((0, index_12.IsNumber)(schema.minLength))
yield `${value}.length >= ${schema.minLength}`;
yield `${variable}.test(${value})`;
}
function* FromString(schema, references, value) {
yield `(typeof ${value} === 'string')`;
if ((0, index_12.IsNumber)(schema.maxLength))
yield `${value}.length <= ${schema.maxLength}`;
if ((0, index_12.IsNumber)(schema.minLength))
yield `${value}.length >= ${schema.minLength}`;
if (schema.pattern !== undefined) {
const variable = CreateVariable(`${new RegExp(schema.pattern)};`);
yield `${variable}.test(${value})`;
}
if (schema.format !== undefined) {
yield `format('${schema.format}', ${value})`;
}
}
function* FromSymbol(schema, references, value) {
yield `(typeof ${value} === 'symbol')`;
}
function* FromTemplateLiteral(schema, references, value) {
yield `(typeof ${value} === 'string')`;
const variable = CreateVariable(`${new RegExp(schema.pattern)};`);
yield `${variable}.test(${value})`;
}
function* FromThis(schema, references, value) {
// Note: This types are assured to be hoisted prior to this call. Just yield the function.
yield `${CreateFunctionName(schema.$ref)}(${value})`;
}
function* FromTuple(schema, references, value) {
yield `Array.isArray(${value})`;
if (schema.items === undefined)
return yield `${value}.length === 0`;
yield `(${value}.length === ${schema.maxItems})`;
for (let i = 0; i < schema.items.length; i++) {
const expression = CreateExpression(schema.items[i], references, `${value}[${i}]`);
yield `${expression}`;
}
}
function* FromUndefined(schema, references, value) {
yield `${value} === undefined`;
}
function* FromUnion(schema, references, value) {
const expressions = schema.anyOf.map((schema) => CreateExpression(schema, references, value));
yield `(${expressions.join(' || ')})`;
}
function* FromUint8Array(schema, references, value) {
yield `${value} instanceof Uint8Array`;
if ((0, index_12.IsNumber)(schema.maxByteLength))
yield `(${value}.length <= ${schema.maxByteLength})`;
if ((0, index_12.IsNumber)(schema.minByteLength))
yield `(${value}.length >= ${schema.minByteLength})`;
}
function* FromUnknown(schema, references, value) {
yield 'true';
}
function* FromVoid(schema, references, value) {
yield Policy.IsVoidLike(value);
}
function* FromKind(schema, references, value) {
const instance = state.instances.size;
state.instances.set(instance, schema);
yield `kind('${schema[index_7.Kind]}', ${instance}, ${value})`;
}
function* Visit(schema, references, value, useHoisting = true) {
const references_ = (0, index_12.IsString)(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
// --------------------------------------------------------------
// Hoisting
// --------------------------------------------------------------
if (useHoisting && (0, index_12.IsString)(schema.$id)) {
const functionName = CreateFunctionName(schema.$id);
if (state.functions.has(functionName)) {
return yield `${functionName}(${value})`;
}
else {
// Note: In the case of cyclic types, we need to create a 'functions' record
// to prevent infinitely re-visiting the CreateFunction. Subsequent attempts
// to visit will be caught by the above condition.
state.functions.set(functionName, '<deferred>');
const functionCode = CreateFunction(functionName, schema, references, 'value', false);
state.functions.set(functionName, functionCode);
return yield `${functionName}(${value})`;
}
}
switch (schema_[index_7.Kind]) {
case 'Any':
return yield* FromAny(schema_, references_, value);
case 'Argument':
return yield* FromArgument(schema_, references_, value);
case 'Array':
return yield* FromArray(schema_, references_, value);
case 'AsyncIterator':
return yield* FromAsyncIterator(schema_, references_, value);
case 'BigInt':
return yield* FromBigInt(schema_, references_, value);
case 'Boolean':
return yield* FromBoolean(schema_, references_, value);
case 'Constructor':
return yield* FromConstructor(schema_, references_, value);
case 'Date':
return yield* FromDate(schema_, references_, value);
case 'Function':
return yield* FromFunction(schema_, references_, value);
case 'Import':
return yield* FromImport(schema_, references_, value);
case 'Integer':
return yield* FromInteger(schema_, references_, value);
case 'Intersect':
return yield* FromIntersect(schema_, references_, value);
case 'Iterator':
return yield* FromIterator(schema_, references_, value);
case 'Literal':
return yield* FromLiteral(schema_, references_, value);
case 'Never':
return yield* FromNever(schema_, references_, value);
case 'Not':
return yield* FromNot(schema_, references_, value);
case 'Null':
return yield* FromNull(schema_, references_, value);
case 'Number':
return yield* FromNumber(schema_, references_, value);
case 'Object':
return yield* FromObject(schema_, references_, value);
case 'Promise':
return yield* FromPromise(schema_, references_, value);
case 'Record':
return yield* FromRecord(schema_, references_, value);
case 'Ref':
return yield* FromRef(schema_, references_, value);
case 'RegExp':
return yield* FromRegExp(schema_, references_, value);
case 'String':
return yield* FromString(schema_, references_, value);
case 'Symbol':
return yield* FromSymbol(schema_, references_, value);
case 'TemplateLiteral':
return yield* FromTemplateLiteral(schema_, references_, value);
case 'This':
return yield* FromThis(schema_, references_, value);
case 'Tuple':
return yield* FromTuple(schema_, references_, value);
case 'Undefined':
return yield* FromUndefined(schema_, references_, value);
case 'Union':
return yield* FromUnion(schema_, references_, value);
case 'Uint8Array':
return yield* FromUint8Array(schema_, references_, value);
case 'Unknown':
return yield* FromUnknown(schema_, references_, value);
case 'Void':
return yield* FromVoid(schema_, references_, value);
default:
if (!index_8.TypeRegistry.Has(schema_[index_7.Kind]))
throw new TypeCompilerUnknownTypeError(schema);
return yield* FromKind(schema_, references_, value);
}
}
// ----------------------------------------------------------------
// Compiler State
// ----------------------------------------------------------------
// prettier-ignore
const state = {
language: 'javascript', // target language
functions: new Map(), // local functions
variables: new Map(), // local variables
instances: new Map() // exterior kind instances
};
// ----------------------------------------------------------------
// Compiler Factory
// ----------------------------------------------------------------
function CreateExpression(schema, references, value, useHoisting = true) {
return `(${[...Visit(schema, references, value, useHoisting)].join(' && ')})`;
}
function CreateFunctionName($id) {
return `check_${Identifier.Encode($id)}`;
}
function CreateVariable(expression) {
const variableName = `local_${state.variables.size}`;
state.variables.set(variableName, `const ${variableName} = ${expression}`);
return variableName;
}
function CreateFunction(name, schema, references, value, useHoisting = true) {
const [newline, pad] = ['\n', (length) => ''.padStart(length, ' ')];
const parameter = CreateParameter('value', 'any');
const returns = CreateReturns('boolean');
const expression = [...Visit(schema, references, value, useHoisting)].map((expression) => `${pad(4)}${expression}`).join(` &&${newline}`);
return `function ${name}(${parameter})${returns} {${newline}${pad(2)}return (${newline}${expression}${newline}${pad(2)})\n}`;
}
function CreateParameter(name, type) {
const annotation = state.language === 'typescript' ? `: ${type}` : '';
return `${name}${annotation}`;
}
function CreateReturns(type) {
return state.language === 'typescript' ? `: ${type}` : '';
}
// ----------------------------------------------------------------
// Compile
// ----------------------------------------------------------------
function Build(schema, references, options) {
const functionCode = CreateFunction('check', schema, references, 'value'); // will populate functions and variables
const parameter = CreateParameter('value', 'any');
const returns = CreateReturns('boolean');
const functions = [...state.functions.values()];
const variables = [...state.variables.values()];
// prettier-ignore
const checkFunction = (0, index_12.IsString)(schema.$id) // ensure top level schemas with $id's are hoisted
? `return function check(${parameter})${returns} {\n return ${CreateFunctionName(schema.$id)}(value)\n}`
: `return ${functionCode}`;
return [...variables, ...functions, checkFunction].join('\n');
}
/** Generates the code used to assert this type and returns it as a string */
function Code(...args) {
const defaults = { language: 'javascript' };
// prettier-ignore
const [schema, references, options] = (args.length === 2 && (0, index_12.IsArray)(args[1]) ? [args[0], args[1], defaults] :
args.length === 2 && !(0, index_12.IsArray)(args[1]) ? [args[0], [], args[1]] :
args.length === 3 ? [args[0], args[1], args[2]] :
args.length === 1 ? [args[0], [], defaults] :
[null, [], defaults]);
// compiler-reset
state.language = options.language;
state.variables.clear();
state.functions.clear();
state.instances.clear();
if (!(0, type_1.IsSchema)(schema))
throw new TypeCompilerTypeGuardError(schema);
for (const schema of references)
if (!(0, type_1.IsSchema)(schema))
throw new TypeCompilerTypeGuardError(schema);
return Build(schema, references, options);
}
TypeCompiler.Code = Code;
/** Compiles a TypeBox type for optimal runtime type checking. Types must be valid TypeBox types of TSchema */
function Compile(schema, references = []) {
const generatedCode = Code(schema, references, { language: 'javascript' });
const compiledFunction = globalThis.Function('kind', 'format', 'hash', generatedCode);
const instances = new Map(state.instances);
function typeRegistryFunction(kind, instance, value) {
if (!index_8.TypeRegistry.Has(kind) || !instances.has(instance))
return false;
const checkFunc = index_8.TypeRegistry.Get(kind);
const schema = instances.get(instance);
return checkFunc(schema, value);
}
function formatRegistryFunction(format, value) {
if (!index_8.FormatRegistry.Has(format))
return false;
const checkFunc = index_8.FormatRegistry.Get(format);
return checkFunc(value);
}
function hashFunction(value) {
return (0, index_6.Hash)(value);
}
const checkFunction = compiledFunction(typeRegistryFunction, formatRegistryFunction, hashFunction);
return new TypeCheck(schema, references, checkFunction, generatedCode);
}
TypeCompiler.Compile = Compile;
})(TypeCompiler || (exports.TypeCompiler = TypeCompiler = {}));

View File

@@ -0,0 +1,2 @@
export { ValueError, ValueErrorType, ValueErrorIterator } from '../errors/index';
export * from './compiler';

View File

@@ -0,0 +1,22 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueErrorIterator = exports.ValueErrorType = void 0;
var index_1 = require("../errors/index");
Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } });
Object.defineProperty(exports, "ValueErrorIterator", { enumerable: true, get: function () { return index_1.ValueErrorIterator; } });
__exportStar(require("./compiler"), exports);

View File

@@ -0,0 +1,91 @@
import { TypeBoxError } from '../type/error/index';
import type { TSchema } from '../type/schema/index';
export declare enum ValueErrorType {
ArrayContains = 0,
ArrayMaxContains = 1,
ArrayMaxItems = 2,
ArrayMinContains = 3,
ArrayMinItems = 4,
ArrayUniqueItems = 5,
Array = 6,
AsyncIterator = 7,
BigIntExclusiveMaximum = 8,
BigIntExclusiveMinimum = 9,
BigIntMaximum = 10,
BigIntMinimum = 11,
BigIntMultipleOf = 12,
BigInt = 13,
Boolean = 14,
DateExclusiveMaximumTimestamp = 15,
DateExclusiveMinimumTimestamp = 16,
DateMaximumTimestamp = 17,
DateMinimumTimestamp = 18,
DateMultipleOfTimestamp = 19,
Date = 20,
Function = 21,
IntegerExclusiveMaximum = 22,
IntegerExclusiveMinimum = 23,
IntegerMaximum = 24,
IntegerMinimum = 25,
IntegerMultipleOf = 26,
Integer = 27,
IntersectUnevaluatedProperties = 28,
Intersect = 29,
Iterator = 30,
Kind = 31,
Literal = 32,
Never = 33,
Not = 34,
Null = 35,
NumberExclusiveMaximum = 36,
NumberExclusiveMinimum = 37,
NumberMaximum = 38,
NumberMinimum = 39,
NumberMultipleOf = 40,
Number = 41,
ObjectAdditionalProperties = 42,
ObjectMaxProperties = 43,
ObjectMinProperties = 44,
ObjectRequiredProperty = 45,
Object = 46,
Promise = 47,
RegExp = 48,
StringFormatUnknown = 49,
StringFormat = 50,
StringMaxLength = 51,
StringMinLength = 52,
StringPattern = 53,
String = 54,
Symbol = 55,
TupleLength = 56,
Tuple = 57,
Uint8ArrayMaxByteLength = 58,
Uint8ArrayMinByteLength = 59,
Uint8Array = 60,
Undefined = 61,
Union = 62,
Void = 63
}
export interface ValueError {
type: ValueErrorType;
schema: TSchema;
path: string;
value: unknown;
message: string;
errors: ValueErrorIterator[];
}
export declare class ValueErrorsUnknownTypeError extends TypeBoxError {
readonly schema: TSchema;
constructor(schema: TSchema);
}
export declare class ValueErrorIterator {
private readonly iterator;
constructor(iterator: IterableIterator<ValueError>);
[Symbol.iterator](): IterableIterator<ValueError>;
/** Returns the first value error or undefined if no errors */
First(): ValueError | undefined;
}
/** Returns an iterator for each error in this value. */
export declare function Errors<T extends TSchema>(schema: T, references: TSchema[], value: unknown): ValueErrorIterator;
/** Returns an iterator for each error in this value. */
export declare function Errors<T extends TSchema>(schema: T, value: unknown): ValueErrorIterator;

View File

@@ -0,0 +1,599 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueErrorIterator = exports.ValueErrorsUnknownTypeError = exports.ValueErrorType = void 0;
exports.Errors = Errors;
const index_1 = require("../system/index");
const index_2 = require("../type/keyof/index");
const index_3 = require("../type/registry/index");
const extends_undefined_1 = require("../type/extends/extends-undefined");
const function_1 = require("./function");
const index_4 = require("../type/error/index");
const index_5 = require("../value/deref/index");
const index_6 = require("../value/hash/index");
const index_7 = require("../value/check/index");
const index_8 = require("../type/symbols/index");
const index_9 = require("../type/never/index");
// ------------------------------------------------------------------
// ValueGuard
// ------------------------------------------------------------------
// prettier-ignore
const index_10 = require("../value/guard/index");
// ------------------------------------------------------------------
// ValueErrorType
// ------------------------------------------------------------------
var ValueErrorType;
(function (ValueErrorType) {
ValueErrorType[ValueErrorType["ArrayContains"] = 0] = "ArrayContains";
ValueErrorType[ValueErrorType["ArrayMaxContains"] = 1] = "ArrayMaxContains";
ValueErrorType[ValueErrorType["ArrayMaxItems"] = 2] = "ArrayMaxItems";
ValueErrorType[ValueErrorType["ArrayMinContains"] = 3] = "ArrayMinContains";
ValueErrorType[ValueErrorType["ArrayMinItems"] = 4] = "ArrayMinItems";
ValueErrorType[ValueErrorType["ArrayUniqueItems"] = 5] = "ArrayUniqueItems";
ValueErrorType[ValueErrorType["Array"] = 6] = "Array";
ValueErrorType[ValueErrorType["AsyncIterator"] = 7] = "AsyncIterator";
ValueErrorType[ValueErrorType["BigIntExclusiveMaximum"] = 8] = "BigIntExclusiveMaximum";
ValueErrorType[ValueErrorType["BigIntExclusiveMinimum"] = 9] = "BigIntExclusiveMinimum";
ValueErrorType[ValueErrorType["BigIntMaximum"] = 10] = "BigIntMaximum";
ValueErrorType[ValueErrorType["BigIntMinimum"] = 11] = "BigIntMinimum";
ValueErrorType[ValueErrorType["BigIntMultipleOf"] = 12] = "BigIntMultipleOf";
ValueErrorType[ValueErrorType["BigInt"] = 13] = "BigInt";
ValueErrorType[ValueErrorType["Boolean"] = 14] = "Boolean";
ValueErrorType[ValueErrorType["DateExclusiveMaximumTimestamp"] = 15] = "DateExclusiveMaximumTimestamp";
ValueErrorType[ValueErrorType["DateExclusiveMinimumTimestamp"] = 16] = "DateExclusiveMinimumTimestamp";
ValueErrorType[ValueErrorType["DateMaximumTimestamp"] = 17] = "DateMaximumTimestamp";
ValueErrorType[ValueErrorType["DateMinimumTimestamp"] = 18] = "DateMinimumTimestamp";
ValueErrorType[ValueErrorType["DateMultipleOfTimestamp"] = 19] = "DateMultipleOfTimestamp";
ValueErrorType[ValueErrorType["Date"] = 20] = "Date";
ValueErrorType[ValueErrorType["Function"] = 21] = "Function";
ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 22] = "IntegerExclusiveMaximum";
ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 23] = "IntegerExclusiveMinimum";
ValueErrorType[ValueErrorType["IntegerMaximum"] = 24] = "IntegerMaximum";
ValueErrorType[ValueErrorType["IntegerMinimum"] = 25] = "IntegerMinimum";
ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 26] = "IntegerMultipleOf";
ValueErrorType[ValueErrorType["Integer"] = 27] = "Integer";
ValueErrorType[ValueErrorType["IntersectUnevaluatedProperties"] = 28] = "IntersectUnevaluatedProperties";
ValueErrorType[ValueErrorType["Intersect"] = 29] = "Intersect";
ValueErrorType[ValueErrorType["Iterator"] = 30] = "Iterator";
ValueErrorType[ValueErrorType["Kind"] = 31] = "Kind";
ValueErrorType[ValueErrorType["Literal"] = 32] = "Literal";
ValueErrorType[ValueErrorType["Never"] = 33] = "Never";
ValueErrorType[ValueErrorType["Not"] = 34] = "Not";
ValueErrorType[ValueErrorType["Null"] = 35] = "Null";
ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 36] = "NumberExclusiveMaximum";
ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 37] = "NumberExclusiveMinimum";
ValueErrorType[ValueErrorType["NumberMaximum"] = 38] = "NumberMaximum";
ValueErrorType[ValueErrorType["NumberMinimum"] = 39] = "NumberMinimum";
ValueErrorType[ValueErrorType["NumberMultipleOf"] = 40] = "NumberMultipleOf";
ValueErrorType[ValueErrorType["Number"] = 41] = "Number";
ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 42] = "ObjectAdditionalProperties";
ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 43] = "ObjectMaxProperties";
ValueErrorType[ValueErrorType["ObjectMinProperties"] = 44] = "ObjectMinProperties";
ValueErrorType[ValueErrorType["ObjectRequiredProperty"] = 45] = "ObjectRequiredProperty";
ValueErrorType[ValueErrorType["Object"] = 46] = "Object";
ValueErrorType[ValueErrorType["Promise"] = 47] = "Promise";
ValueErrorType[ValueErrorType["RegExp"] = 48] = "RegExp";
ValueErrorType[ValueErrorType["StringFormatUnknown"] = 49] = "StringFormatUnknown";
ValueErrorType[ValueErrorType["StringFormat"] = 50] = "StringFormat";
ValueErrorType[ValueErrorType["StringMaxLength"] = 51] = "StringMaxLength";
ValueErrorType[ValueErrorType["StringMinLength"] = 52] = "StringMinLength";
ValueErrorType[ValueErrorType["StringPattern"] = 53] = "StringPattern";
ValueErrorType[ValueErrorType["String"] = 54] = "String";
ValueErrorType[ValueErrorType["Symbol"] = 55] = "Symbol";
ValueErrorType[ValueErrorType["TupleLength"] = 56] = "TupleLength";
ValueErrorType[ValueErrorType["Tuple"] = 57] = "Tuple";
ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 58] = "Uint8ArrayMaxByteLength";
ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 59] = "Uint8ArrayMinByteLength";
ValueErrorType[ValueErrorType["Uint8Array"] = 60] = "Uint8Array";
ValueErrorType[ValueErrorType["Undefined"] = 61] = "Undefined";
ValueErrorType[ValueErrorType["Union"] = 62] = "Union";
ValueErrorType[ValueErrorType["Void"] = 63] = "Void";
})(ValueErrorType || (exports.ValueErrorType = ValueErrorType = {}));
// ------------------------------------------------------------------
// ValueErrors
// ------------------------------------------------------------------
class ValueErrorsUnknownTypeError extends index_4.TypeBoxError {
constructor(schema) {
super('Unknown type');
this.schema = schema;
}
}
exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError;
// ------------------------------------------------------------------
// EscapeKey
// ------------------------------------------------------------------
function EscapeKey(key) {
return key.replace(/~/g, '~0').replace(/\//g, '~1'); // RFC6901 Path
}
// ------------------------------------------------------------------
// Guards
// ------------------------------------------------------------------
function IsDefined(value) {
return value !== undefined;
}
// ------------------------------------------------------------------
// ValueErrorIterator
// ------------------------------------------------------------------
class ValueErrorIterator {
constructor(iterator) {
this.iterator = iterator;
}
[Symbol.iterator]() {
return this.iterator;
}
/** Returns the first value error or undefined if no errors */
First() {
const next = this.iterator.next();
return next.done ? undefined : next.value;
}
}
exports.ValueErrorIterator = ValueErrorIterator;
// --------------------------------------------------------------------------
// Create
// --------------------------------------------------------------------------
function Create(errorType, schema, path, value, errors = []) {
return {
type: errorType,
schema,
path,
value,
message: (0, function_1.GetErrorFunction)()({ errorType, path, schema, value, errors }),
errors,
};
}
// --------------------------------------------------------------------------
// Types
// --------------------------------------------------------------------------
function* FromAny(schema, references, path, value) { }
function* FromArgument(schema, references, path, value) { }
function* FromArray(schema, references, path, value) {
if (!(0, index_10.IsArray)(value)) {
return yield Create(ValueErrorType.Array, schema, path, value);
}
if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {
yield Create(ValueErrorType.ArrayMinItems, schema, path, value);
}
if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {
yield Create(ValueErrorType.ArrayMaxItems, schema, path, value);
}
for (let i = 0; i < value.length; i++) {
yield* Visit(schema.items, references, `${path}/${i}`, value[i]);
}
// prettier-ignore
if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {
const hashed = (0, index_6.Hash)(element);
if (set.has(hashed)) {
return false;
}
else {
set.add(hashed);
}
} return true; })())) {
yield Create(ValueErrorType.ArrayUniqueItems, schema, path, value);
}
// contains
if (!(IsDefined(schema.contains) || IsDefined(schema.minContains) || IsDefined(schema.maxContains))) {
return;
}
const containsSchema = IsDefined(schema.contains) ? schema.contains : (0, index_9.Never)();
const containsCount = value.reduce((acc, value, index) => (Visit(containsSchema, references, `${path}${index}`, value).next().done === true ? acc + 1 : acc), 0);
if (containsCount === 0) {
yield Create(ValueErrorType.ArrayContains, schema, path, value);
}
if ((0, index_10.IsNumber)(schema.minContains) && containsCount < schema.minContains) {
yield Create(ValueErrorType.ArrayMinContains, schema, path, value);
}
if ((0, index_10.IsNumber)(schema.maxContains) && containsCount > schema.maxContains) {
yield Create(ValueErrorType.ArrayMaxContains, schema, path, value);
}
}
function* FromAsyncIterator(schema, references, path, value) {
if (!(0, index_10.IsAsyncIterator)(value))
yield Create(ValueErrorType.AsyncIterator, schema, path, value);
}
function* FromBigInt(schema, references, path, value) {
if (!(0, index_10.IsBigInt)(value))
return yield Create(ValueErrorType.BigInt, schema, path, value);
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield Create(ValueErrorType.BigIntExclusiveMaximum, schema, path, value);
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield Create(ValueErrorType.BigIntExclusiveMinimum, schema, path, value);
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield Create(ValueErrorType.BigIntMaximum, schema, path, value);
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield Create(ValueErrorType.BigIntMinimum, schema, path, value);
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === BigInt(0))) {
yield Create(ValueErrorType.BigIntMultipleOf, schema, path, value);
}
}
function* FromBoolean(schema, references, path, value) {
if (!(0, index_10.IsBoolean)(value))
yield Create(ValueErrorType.Boolean, schema, path, value);
}
function* FromConstructor(schema, references, path, value) {
yield* Visit(schema.returns, references, path, value.prototype);
}
function* FromDate(schema, references, path, value) {
if (!(0, index_10.IsDate)(value))
return yield Create(ValueErrorType.Date, schema, path, value);
if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {
yield Create(ValueErrorType.DateExclusiveMaximumTimestamp, schema, path, value);
}
if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {
yield Create(ValueErrorType.DateExclusiveMinimumTimestamp, schema, path, value);
}
if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {
yield Create(ValueErrorType.DateMaximumTimestamp, schema, path, value);
}
if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {
yield Create(ValueErrorType.DateMinimumTimestamp, schema, path, value);
}
if (IsDefined(schema.multipleOfTimestamp) && !(value.getTime() % schema.multipleOfTimestamp === 0)) {
yield Create(ValueErrorType.DateMultipleOfTimestamp, schema, path, value);
}
}
function* FromFunction(schema, references, path, value) {
if (!(0, index_10.IsFunction)(value))
yield Create(ValueErrorType.Function, schema, path, value);
}
function* FromImport(schema, references, path, value) {
const definitions = globalThis.Object.values(schema.$defs);
const target = schema.$defs[schema.$ref];
yield* Visit(target, [...references, ...definitions], path, value);
}
function* FromInteger(schema, references, path, value) {
if (!(0, index_10.IsInteger)(value))
return yield Create(ValueErrorType.Integer, schema, path, value);
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield Create(ValueErrorType.IntegerExclusiveMaximum, schema, path, value);
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield Create(ValueErrorType.IntegerExclusiveMinimum, schema, path, value);
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield Create(ValueErrorType.IntegerMaximum, schema, path, value);
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield Create(ValueErrorType.IntegerMinimum, schema, path, value);
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
yield Create(ValueErrorType.IntegerMultipleOf, schema, path, value);
}
}
function* FromIntersect(schema, references, path, value) {
let hasError = false;
for (const inner of schema.allOf) {
for (const error of Visit(inner, references, path, value)) {
hasError = true;
yield error;
}
}
if (hasError) {
return yield Create(ValueErrorType.Intersect, schema, path, value);
}
if (schema.unevaluatedProperties === false) {
const keyCheck = new RegExp((0, index_2.KeyOfPattern)(schema));
for (const valueKey of Object.getOwnPropertyNames(value)) {
if (!keyCheck.test(valueKey)) {
yield Create(ValueErrorType.IntersectUnevaluatedProperties, schema, `${path}/${valueKey}`, value);
}
}
}
if (typeof schema.unevaluatedProperties === 'object') {
const keyCheck = new RegExp((0, index_2.KeyOfPattern)(schema));
for (const valueKey of Object.getOwnPropertyNames(value)) {
if (!keyCheck.test(valueKey)) {
const next = Visit(schema.unevaluatedProperties, references, `${path}/${valueKey}`, value[valueKey]).next();
if (!next.done)
yield next.value; // yield interior
}
}
}
}
function* FromIterator(schema, references, path, value) {
if (!(0, index_10.IsIterator)(value))
yield Create(ValueErrorType.Iterator, schema, path, value);
}
function* FromLiteral(schema, references, path, value) {
if (!(value === schema.const))
yield Create(ValueErrorType.Literal, schema, path, value);
}
function* FromNever(schema, references, path, value) {
yield Create(ValueErrorType.Never, schema, path, value);
}
function* FromNot(schema, references, path, value) {
if (Visit(schema.not, references, path, value).next().done === true)
yield Create(ValueErrorType.Not, schema, path, value);
}
function* FromNull(schema, references, path, value) {
if (!(0, index_10.IsNull)(value))
yield Create(ValueErrorType.Null, schema, path, value);
}
function* FromNumber(schema, references, path, value) {
if (!index_1.TypeSystemPolicy.IsNumberLike(value))
return yield Create(ValueErrorType.Number, schema, path, value);
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield Create(ValueErrorType.NumberExclusiveMaximum, schema, path, value);
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield Create(ValueErrorType.NumberExclusiveMinimum, schema, path, value);
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield Create(ValueErrorType.NumberMaximum, schema, path, value);
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield Create(ValueErrorType.NumberMinimum, schema, path, value);
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
yield Create(ValueErrorType.NumberMultipleOf, schema, path, value);
}
}
function* FromObject(schema, references, path, value) {
if (!index_1.TypeSystemPolicy.IsObjectLike(value))
return yield Create(ValueErrorType.Object, schema, path, value);
if (IsDefined(schema.minProperties) && !(Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
yield Create(ValueErrorType.ObjectMinProperties, schema, path, value);
}
if (IsDefined(schema.maxProperties) && !(Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
yield Create(ValueErrorType.ObjectMaxProperties, schema, path, value);
}
const requiredKeys = Array.isArray(schema.required) ? schema.required : [];
const knownKeys = Object.getOwnPropertyNames(schema.properties);
const unknownKeys = Object.getOwnPropertyNames(value);
for (const requiredKey of requiredKeys) {
if (unknownKeys.includes(requiredKey))
continue;
yield Create(ValueErrorType.ObjectRequiredProperty, schema.properties[requiredKey], `${path}/${EscapeKey(requiredKey)}`, undefined);
}
if (schema.additionalProperties === false) {
for (const valueKey of unknownKeys) {
if (!knownKeys.includes(valueKey)) {
yield Create(ValueErrorType.ObjectAdditionalProperties, schema, `${path}/${EscapeKey(valueKey)}`, value[valueKey]);
}
}
}
if (typeof schema.additionalProperties === 'object') {
for (const valueKey of unknownKeys) {
if (knownKeys.includes(valueKey))
continue;
yield* Visit(schema.additionalProperties, references, `${path}/${EscapeKey(valueKey)}`, value[valueKey]);
}
}
for (const knownKey of knownKeys) {
const property = schema.properties[knownKey];
if (schema.required && schema.required.includes(knownKey)) {
yield* Visit(property, references, `${path}/${EscapeKey(knownKey)}`, value[knownKey]);
if ((0, extends_undefined_1.ExtendsUndefinedCheck)(schema) && !(knownKey in value)) {
yield Create(ValueErrorType.ObjectRequiredProperty, property, `${path}/${EscapeKey(knownKey)}`, undefined);
}
}
else {
if (index_1.TypeSystemPolicy.IsExactOptionalProperty(value, knownKey)) {
yield* Visit(property, references, `${path}/${EscapeKey(knownKey)}`, value[knownKey]);
}
}
}
}
function* FromPromise(schema, references, path, value) {
if (!(0, index_10.IsPromise)(value))
yield Create(ValueErrorType.Promise, schema, path, value);
}
function* FromRecord(schema, references, path, value) {
if (!index_1.TypeSystemPolicy.IsRecordLike(value))
return yield Create(ValueErrorType.Object, schema, path, value);
if (IsDefined(schema.minProperties) && !(Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
yield Create(ValueErrorType.ObjectMinProperties, schema, path, value);
}
if (IsDefined(schema.maxProperties) && !(Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
yield Create(ValueErrorType.ObjectMaxProperties, schema, path, value);
}
const [patternKey, patternSchema] = Object.entries(schema.patternProperties)[0];
const regex = new RegExp(patternKey);
for (const [propertyKey, propertyValue] of Object.entries(value)) {
if (regex.test(propertyKey))
yield* Visit(patternSchema, references, `${path}/${EscapeKey(propertyKey)}`, propertyValue);
}
if (typeof schema.additionalProperties === 'object') {
for (const [propertyKey, propertyValue] of Object.entries(value)) {
if (!regex.test(propertyKey))
yield* Visit(schema.additionalProperties, references, `${path}/${EscapeKey(propertyKey)}`, propertyValue);
}
}
if (schema.additionalProperties === false) {
for (const [propertyKey, propertyValue] of Object.entries(value)) {
if (regex.test(propertyKey))
continue;
return yield Create(ValueErrorType.ObjectAdditionalProperties, schema, `${path}/${EscapeKey(propertyKey)}`, propertyValue);
}
}
}
function* FromRef(schema, references, path, value) {
yield* Visit((0, index_5.Deref)(schema, references), references, path, value);
}
function* FromRegExp(schema, references, path, value) {
if (!(0, index_10.IsString)(value))
return yield Create(ValueErrorType.String, schema, path, value);
if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) {
yield Create(ValueErrorType.StringMinLength, schema, path, value);
}
if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) {
yield Create(ValueErrorType.StringMaxLength, schema, path, value);
}
const regex = new RegExp(schema.source, schema.flags);
if (!regex.test(value)) {
return yield Create(ValueErrorType.RegExp, schema, path, value);
}
}
function* FromString(schema, references, path, value) {
if (!(0, index_10.IsString)(value))
return yield Create(ValueErrorType.String, schema, path, value);
if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) {
yield Create(ValueErrorType.StringMinLength, schema, path, value);
}
if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) {
yield Create(ValueErrorType.StringMaxLength, schema, path, value);
}
if ((0, index_10.IsString)(schema.pattern)) {
const regex = new RegExp(schema.pattern);
if (!regex.test(value)) {
yield Create(ValueErrorType.StringPattern, schema, path, value);
}
}
if ((0, index_10.IsString)(schema.format)) {
if (!index_3.FormatRegistry.Has(schema.format)) {
yield Create(ValueErrorType.StringFormatUnknown, schema, path, value);
}
else {
const format = index_3.FormatRegistry.Get(schema.format);
if (!format(value)) {
yield Create(ValueErrorType.StringFormat, schema, path, value);
}
}
}
}
function* FromSymbol(schema, references, path, value) {
if (!(0, index_10.IsSymbol)(value))
yield Create(ValueErrorType.Symbol, schema, path, value);
}
function* FromTemplateLiteral(schema, references, path, value) {
if (!(0, index_10.IsString)(value))
return yield Create(ValueErrorType.String, schema, path, value);
const regex = new RegExp(schema.pattern);
if (!regex.test(value)) {
yield Create(ValueErrorType.StringPattern, schema, path, value);
}
}
function* FromThis(schema, references, path, value) {
yield* Visit((0, index_5.Deref)(schema, references), references, path, value);
}
function* FromTuple(schema, references, path, value) {
if (!(0, index_10.IsArray)(value))
return yield Create(ValueErrorType.Tuple, schema, path, value);
if (schema.items === undefined && !(value.length === 0)) {
return yield Create(ValueErrorType.TupleLength, schema, path, value);
}
if (!(value.length === schema.maxItems)) {
return yield Create(ValueErrorType.TupleLength, schema, path, value);
}
if (!schema.items) {
return;
}
for (let i = 0; i < schema.items.length; i++) {
yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]);
}
}
function* FromUndefined(schema, references, path, value) {
if (!(0, index_10.IsUndefined)(value))
yield Create(ValueErrorType.Undefined, schema, path, value);
}
function* FromUnion(schema, references, path, value) {
if ((0, index_7.Check)(schema, references, value))
return;
const errors = schema.anyOf.map((variant) => new ValueErrorIterator(Visit(variant, references, path, value)));
yield Create(ValueErrorType.Union, schema, path, value, errors);
}
function* FromUint8Array(schema, references, path, value) {
if (!(0, index_10.IsUint8Array)(value))
return yield Create(ValueErrorType.Uint8Array, schema, path, value);
if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {
yield Create(ValueErrorType.Uint8ArrayMaxByteLength, schema, path, value);
}
if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {
yield Create(ValueErrorType.Uint8ArrayMinByteLength, schema, path, value);
}
}
function* FromUnknown(schema, references, path, value) { }
function* FromVoid(schema, references, path, value) {
if (!index_1.TypeSystemPolicy.IsVoidLike(value))
yield Create(ValueErrorType.Void, schema, path, value);
}
function* FromKind(schema, references, path, value) {
const check = index_3.TypeRegistry.Get(schema[index_8.Kind]);
if (!check(schema, value))
yield Create(ValueErrorType.Kind, schema, path, value);
}
function* Visit(schema, references, path, value) {
const references_ = IsDefined(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema_[index_8.Kind]) {
case 'Any':
return yield* FromAny(schema_, references_, path, value);
case 'Argument':
return yield* FromArgument(schema_, references_, path, value);
case 'Array':
return yield* FromArray(schema_, references_, path, value);
case 'AsyncIterator':
return yield* FromAsyncIterator(schema_, references_, path, value);
case 'BigInt':
return yield* FromBigInt(schema_, references_, path, value);
case 'Boolean':
return yield* FromBoolean(schema_, references_, path, value);
case 'Constructor':
return yield* FromConstructor(schema_, references_, path, value);
case 'Date':
return yield* FromDate(schema_, references_, path, value);
case 'Function':
return yield* FromFunction(schema_, references_, path, value);
case 'Import':
return yield* FromImport(schema_, references_, path, value);
case 'Integer':
return yield* FromInteger(schema_, references_, path, value);
case 'Intersect':
return yield* FromIntersect(schema_, references_, path, value);
case 'Iterator':
return yield* FromIterator(schema_, references_, path, value);
case 'Literal':
return yield* FromLiteral(schema_, references_, path, value);
case 'Never':
return yield* FromNever(schema_, references_, path, value);
case 'Not':
return yield* FromNot(schema_, references_, path, value);
case 'Null':
return yield* FromNull(schema_, references_, path, value);
case 'Number':
return yield* FromNumber(schema_, references_, path, value);
case 'Object':
return yield* FromObject(schema_, references_, path, value);
case 'Promise':
return yield* FromPromise(schema_, references_, path, value);
case 'Record':
return yield* FromRecord(schema_, references_, path, value);
case 'Ref':
return yield* FromRef(schema_, references_, path, value);
case 'RegExp':
return yield* FromRegExp(schema_, references_, path, value);
case 'String':
return yield* FromString(schema_, references_, path, value);
case 'Symbol':
return yield* FromSymbol(schema_, references_, path, value);
case 'TemplateLiteral':
return yield* FromTemplateLiteral(schema_, references_, path, value);
case 'This':
return yield* FromThis(schema_, references_, path, value);
case 'Tuple':
return yield* FromTuple(schema_, references_, path, value);
case 'Undefined':
return yield* FromUndefined(schema_, references_, path, value);
case 'Union':
return yield* FromUnion(schema_, references_, path, value);
case 'Uint8Array':
return yield* FromUint8Array(schema_, references_, path, value);
case 'Unknown':
return yield* FromUnknown(schema_, references_, path, value);
case 'Void':
return yield* FromVoid(schema_, references_, path, value);
default:
if (!index_3.TypeRegistry.Has(schema_[index_8.Kind]))
throw new ValueErrorsUnknownTypeError(schema);
return yield* FromKind(schema_, references_, path, value);
}
}
/** Returns an iterator for each error in this value. */
function Errors(...args) {
const iterator = args.length === 3 ? Visit(args[0], args[1], '', args[2]) : Visit(args[0], [], '', args[1]);
return new ValueErrorIterator(iterator);
}

View File

@@ -0,0 +1,21 @@
import { TSchema } from '../type/schema/index';
import { ValueErrorIterator, ValueErrorType } from './errors';
/** Creates an error message using en-US as the default locale */
export declare function DefaultErrorFunction(error: ErrorFunctionParameter): string;
export type ErrorFunctionParameter = {
/** The type of validation error */
errorType: ValueErrorType;
/** The path of the error */
path: string;
/** The schema associated with the error */
schema: TSchema;
/** The value associated with the error */
value: unknown;
/** Interior errors for this error */
errors: ValueErrorIterator[];
};
export type ErrorFunction = (parameter: ErrorFunctionParameter) => string;
/** Sets the error function used to generate error messages. */
export declare function SetErrorFunction(callback: ErrorFunction): void;
/** Gets the error function used to generate error messages */
export declare function GetErrorFunction(): ErrorFunction;

View File

@@ -0,0 +1,153 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultErrorFunction = DefaultErrorFunction;
exports.SetErrorFunction = SetErrorFunction;
exports.GetErrorFunction = GetErrorFunction;
const index_1 = require("../type/symbols/index");
const errors_1 = require("./errors");
/** Creates an error message using en-US as the default locale */
function DefaultErrorFunction(error) {
switch (error.errorType) {
case errors_1.ValueErrorType.ArrayContains:
return 'Expected array to contain at least one matching value';
case errors_1.ValueErrorType.ArrayMaxContains:
return `Expected array to contain no more than ${error.schema.maxContains} matching values`;
case errors_1.ValueErrorType.ArrayMinContains:
return `Expected array to contain at least ${error.schema.minContains} matching values`;
case errors_1.ValueErrorType.ArrayMaxItems:
return `Expected array length to be less or equal to ${error.schema.maxItems}`;
case errors_1.ValueErrorType.ArrayMinItems:
return `Expected array length to be greater or equal to ${error.schema.minItems}`;
case errors_1.ValueErrorType.ArrayUniqueItems:
return 'Expected array elements to be unique';
case errors_1.ValueErrorType.Array:
return 'Expected array';
case errors_1.ValueErrorType.AsyncIterator:
return 'Expected AsyncIterator';
case errors_1.ValueErrorType.BigIntExclusiveMaximum:
return `Expected bigint to be less than ${error.schema.exclusiveMaximum}`;
case errors_1.ValueErrorType.BigIntExclusiveMinimum:
return `Expected bigint to be greater than ${error.schema.exclusiveMinimum}`;
case errors_1.ValueErrorType.BigIntMaximum:
return `Expected bigint to be less or equal to ${error.schema.maximum}`;
case errors_1.ValueErrorType.BigIntMinimum:
return `Expected bigint to be greater or equal to ${error.schema.minimum}`;
case errors_1.ValueErrorType.BigIntMultipleOf:
return `Expected bigint to be a multiple of ${error.schema.multipleOf}`;
case errors_1.ValueErrorType.BigInt:
return 'Expected bigint';
case errors_1.ValueErrorType.Boolean:
return 'Expected boolean';
case errors_1.ValueErrorType.DateExclusiveMinimumTimestamp:
return `Expected Date timestamp to be greater than ${error.schema.exclusiveMinimumTimestamp}`;
case errors_1.ValueErrorType.DateExclusiveMaximumTimestamp:
return `Expected Date timestamp to be less than ${error.schema.exclusiveMaximumTimestamp}`;
case errors_1.ValueErrorType.DateMinimumTimestamp:
return `Expected Date timestamp to be greater or equal to ${error.schema.minimumTimestamp}`;
case errors_1.ValueErrorType.DateMaximumTimestamp:
return `Expected Date timestamp to be less or equal to ${error.schema.maximumTimestamp}`;
case errors_1.ValueErrorType.DateMultipleOfTimestamp:
return `Expected Date timestamp to be a multiple of ${error.schema.multipleOfTimestamp}`;
case errors_1.ValueErrorType.Date:
return 'Expected Date';
case errors_1.ValueErrorType.Function:
return 'Expected function';
case errors_1.ValueErrorType.IntegerExclusiveMaximum:
return `Expected integer to be less than ${error.schema.exclusiveMaximum}`;
case errors_1.ValueErrorType.IntegerExclusiveMinimum:
return `Expected integer to be greater than ${error.schema.exclusiveMinimum}`;
case errors_1.ValueErrorType.IntegerMaximum:
return `Expected integer to be less or equal to ${error.schema.maximum}`;
case errors_1.ValueErrorType.IntegerMinimum:
return `Expected integer to be greater or equal to ${error.schema.minimum}`;
case errors_1.ValueErrorType.IntegerMultipleOf:
return `Expected integer to be a multiple of ${error.schema.multipleOf}`;
case errors_1.ValueErrorType.Integer:
return 'Expected integer';
case errors_1.ValueErrorType.IntersectUnevaluatedProperties:
return 'Unexpected property';
case errors_1.ValueErrorType.Intersect:
return 'Expected all values to match';
case errors_1.ValueErrorType.Iterator:
return 'Expected Iterator';
case errors_1.ValueErrorType.Literal:
return `Expected ${typeof error.schema.const === 'string' ? `'${error.schema.const}'` : error.schema.const}`;
case errors_1.ValueErrorType.Never:
return 'Never';
case errors_1.ValueErrorType.Not:
return 'Value should not match';
case errors_1.ValueErrorType.Null:
return 'Expected null';
case errors_1.ValueErrorType.NumberExclusiveMaximum:
return `Expected number to be less than ${error.schema.exclusiveMaximum}`;
case errors_1.ValueErrorType.NumberExclusiveMinimum:
return `Expected number to be greater than ${error.schema.exclusiveMinimum}`;
case errors_1.ValueErrorType.NumberMaximum:
return `Expected number to be less or equal to ${error.schema.maximum}`;
case errors_1.ValueErrorType.NumberMinimum:
return `Expected number to be greater or equal to ${error.schema.minimum}`;
case errors_1.ValueErrorType.NumberMultipleOf:
return `Expected number to be a multiple of ${error.schema.multipleOf}`;
case errors_1.ValueErrorType.Number:
return 'Expected number';
case errors_1.ValueErrorType.Object:
return 'Expected object';
case errors_1.ValueErrorType.ObjectAdditionalProperties:
return 'Unexpected property';
case errors_1.ValueErrorType.ObjectMaxProperties:
return `Expected object to have no more than ${error.schema.maxProperties} properties`;
case errors_1.ValueErrorType.ObjectMinProperties:
return `Expected object to have at least ${error.schema.minProperties} properties`;
case errors_1.ValueErrorType.ObjectRequiredProperty:
return 'Expected required property';
case errors_1.ValueErrorType.Promise:
return 'Expected Promise';
case errors_1.ValueErrorType.RegExp:
return 'Expected string to match regular expression';
case errors_1.ValueErrorType.StringFormatUnknown:
return `Unknown format '${error.schema.format}'`;
case errors_1.ValueErrorType.StringFormat:
return `Expected string to match '${error.schema.format}' format`;
case errors_1.ValueErrorType.StringMaxLength:
return `Expected string length less or equal to ${error.schema.maxLength}`;
case errors_1.ValueErrorType.StringMinLength:
return `Expected string length greater or equal to ${error.schema.minLength}`;
case errors_1.ValueErrorType.StringPattern:
return `Expected string to match '${error.schema.pattern}'`;
case errors_1.ValueErrorType.String:
return 'Expected string';
case errors_1.ValueErrorType.Symbol:
return 'Expected symbol';
case errors_1.ValueErrorType.TupleLength:
return `Expected tuple to have ${error.schema.maxItems || 0} elements`;
case errors_1.ValueErrorType.Tuple:
return 'Expected tuple';
case errors_1.ValueErrorType.Uint8ArrayMaxByteLength:
return `Expected byte length less or equal to ${error.schema.maxByteLength}`;
case errors_1.ValueErrorType.Uint8ArrayMinByteLength:
return `Expected byte length greater or equal to ${error.schema.minByteLength}`;
case errors_1.ValueErrorType.Uint8Array:
return 'Expected Uint8Array';
case errors_1.ValueErrorType.Undefined:
return 'Expected undefined';
case errors_1.ValueErrorType.Union:
return 'Expected union value';
case errors_1.ValueErrorType.Void:
return 'Expected void';
case errors_1.ValueErrorType.Kind:
return `Expected kind '${error.schema[index_1.Kind]}'`;
default:
return 'Unknown error type';
}
}
/** Manages error message providers */
let errorFunction = DefaultErrorFunction;
/** Sets the error function used to generate error messages. */
function SetErrorFunction(callback) {
errorFunction = callback;
}
/** Gets the error function used to generate error messages */
function GetErrorFunction() {
return errorFunction;
}

View File

@@ -0,0 +1,2 @@
export * from './errors';
export * from './function';

View File

@@ -0,0 +1,19 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./errors"), exports);
__exportStar(require("./function"), exports);

View File

@@ -0,0 +1,71 @@
export * from './type/clone/index';
export * from './type/create/index';
export * from './type/error/index';
export * from './type/guard/index';
export * from './type/helpers/index';
export * from './type/patterns/index';
export * from './type/registry/index';
export * from './type/sets/index';
export * from './type/symbols/index';
export * from './type/any/index';
export * from './type/array/index';
export * from './type/argument/index';
export * from './type/async-iterator/index';
export * from './type/awaited/index';
export * from './type/bigint/index';
export * from './type/boolean/index';
export * from './type/composite/index';
export * from './type/const/index';
export * from './type/constructor/index';
export * from './type/constructor-parameters/index';
export * from './type/date/index';
export * from './type/enum/index';
export * from './type/exclude/index';
export * from './type/extends/index';
export * from './type/extract/index';
export * from './type/function/index';
export * from './type/indexed/index';
export * from './type/instance-type/index';
export * from './type/instantiate/index';
export * from './type/integer/index';
export * from './type/intersect/index';
export * from './type/iterator/index';
export * from './type/intrinsic/index';
export * from './type/keyof/index';
export * from './type/literal/index';
export * from './type/module/index';
export * from './type/mapped/index';
export * from './type/never/index';
export * from './type/not/index';
export * from './type/null/index';
export * from './type/number/index';
export * from './type/object/index';
export * from './type/omit/index';
export * from './type/optional/index';
export * from './type/parameters/index';
export * from './type/partial/index';
export * from './type/pick/index';
export * from './type/promise/index';
export * from './type/readonly/index';
export * from './type/readonly-optional/index';
export * from './type/record/index';
export * from './type/recursive/index';
export * from './type/ref/index';
export * from './type/regexp/index';
export * from './type/required/index';
export * from './type/rest/index';
export * from './type/return-type/index';
export * from './type/schema/index';
export * from './type/static/index';
export * from './type/string/index';
export * from './type/symbol/index';
export * from './type/template-literal/index';
export * from './type/transform/index';
export * from './type/tuple/index';
export * from './type/uint8array/index';
export * from './type/undefined/index';
export * from './type/union/index';
export * from './type/unknown/index';
export * from './type/unsafe/index';
export * from './type/void/index';
export * from './type/type/index';

View File

@@ -0,0 +1,97 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
// ------------------------------------------------------------------
// Infrastructure
// ------------------------------------------------------------------
__exportStar(require("./type/clone/index"), exports);
__exportStar(require("./type/create/index"), exports);
__exportStar(require("./type/error/index"), exports);
__exportStar(require("./type/guard/index"), exports);
__exportStar(require("./type/helpers/index"), exports);
__exportStar(require("./type/patterns/index"), exports);
__exportStar(require("./type/registry/index"), exports);
__exportStar(require("./type/sets/index"), exports);
__exportStar(require("./type/symbols/index"), exports);
// ------------------------------------------------------------------
// Types
// ------------------------------------------------------------------
__exportStar(require("./type/any/index"), exports);
__exportStar(require("./type/array/index"), exports);
__exportStar(require("./type/argument/index"), exports);
__exportStar(require("./type/async-iterator/index"), exports);
__exportStar(require("./type/awaited/index"), exports);
__exportStar(require("./type/bigint/index"), exports);
__exportStar(require("./type/boolean/index"), exports);
__exportStar(require("./type/composite/index"), exports);
__exportStar(require("./type/const/index"), exports);
__exportStar(require("./type/constructor/index"), exports);
__exportStar(require("./type/constructor-parameters/index"), exports);
__exportStar(require("./type/date/index"), exports);
__exportStar(require("./type/enum/index"), exports);
__exportStar(require("./type/exclude/index"), exports);
__exportStar(require("./type/extends/index"), exports);
__exportStar(require("./type/extract/index"), exports);
__exportStar(require("./type/function/index"), exports);
__exportStar(require("./type/indexed/index"), exports);
__exportStar(require("./type/instance-type/index"), exports);
__exportStar(require("./type/instantiate/index"), exports);
__exportStar(require("./type/integer/index"), exports);
__exportStar(require("./type/intersect/index"), exports);
__exportStar(require("./type/iterator/index"), exports);
__exportStar(require("./type/intrinsic/index"), exports);
__exportStar(require("./type/keyof/index"), exports);
__exportStar(require("./type/literal/index"), exports);
__exportStar(require("./type/module/index"), exports);
__exportStar(require("./type/mapped/index"), exports);
__exportStar(require("./type/never/index"), exports);
__exportStar(require("./type/not/index"), exports);
__exportStar(require("./type/null/index"), exports);
__exportStar(require("./type/number/index"), exports);
__exportStar(require("./type/object/index"), exports);
__exportStar(require("./type/omit/index"), exports);
__exportStar(require("./type/optional/index"), exports);
__exportStar(require("./type/parameters/index"), exports);
__exportStar(require("./type/partial/index"), exports);
__exportStar(require("./type/pick/index"), exports);
__exportStar(require("./type/promise/index"), exports);
__exportStar(require("./type/readonly/index"), exports);
__exportStar(require("./type/readonly-optional/index"), exports);
__exportStar(require("./type/record/index"), exports);
__exportStar(require("./type/recursive/index"), exports);
__exportStar(require("./type/ref/index"), exports);
__exportStar(require("./type/regexp/index"), exports);
__exportStar(require("./type/required/index"), exports);
__exportStar(require("./type/rest/index"), exports);
__exportStar(require("./type/return-type/index"), exports);
__exportStar(require("./type/schema/index"), exports);
__exportStar(require("./type/static/index"), exports);
__exportStar(require("./type/string/index"), exports);
__exportStar(require("./type/symbol/index"), exports);
__exportStar(require("./type/template-literal/index"), exports);
__exportStar(require("./type/transform/index"), exports);
__exportStar(require("./type/tuple/index"), exports);
__exportStar(require("./type/uint8array/index"), exports);
__exportStar(require("./type/undefined/index"), exports);
__exportStar(require("./type/union/index"), exports);
__exportStar(require("./type/unknown/index"), exports);
__exportStar(require("./type/unsafe/index"), exports);
__exportStar(require("./type/void/index"), exports);
// ------------------------------------------------------------------
// Type.*
// ------------------------------------------------------------------
__exportStar(require("./type/type/index"), exports);

View File

@@ -0,0 +1,2 @@
export * as Runtime from './runtime/index';
export * as Static from './static/index';

View File

@@ -0,0 +1,39 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Static = exports.Runtime = void 0;
exports.Runtime = __importStar(require("./runtime/index"));
exports.Static = __importStar(require("./static/index"));

View File

@@ -0,0 +1,23 @@
import { IArray, IConst, IContext, IIdent, INumber, IOptional, IRef, IString, ITuple, IUnion } from './types';
/** Returns true if the value is a Array Parser */
export declare function IsArray(value: unknown): value is IArray;
/** Returns true if the value is a Const Parser */
export declare function IsConst(value: unknown): value is IConst;
/** Returns true if the value is a Context Parser */
export declare function IsContext(value: unknown): value is IContext;
/** Returns true if the value is a Ident Parser */
export declare function IsIdent(value: unknown): value is IIdent;
/** Returns true if the value is a Number Parser */
export declare function IsNumber(value: unknown): value is INumber;
/** Returns true if the value is a Optional Parser */
export declare function IsOptional(value: unknown): value is IOptional;
/** Returns true if the value is a Ref Parser */
export declare function IsRef(value: unknown): value is IRef;
/** Returns true if the value is a String Parser */
export declare function IsString(value: unknown): value is IString;
/** Returns true if the value is a Tuple Parser */
export declare function IsTuple(value: unknown): value is ITuple;
/** Returns true if the value is a Union Parser */
export declare function IsUnion(value: unknown): value is IUnion;
/** Returns true if the value is a Parser */
export declare function IsParser(value: unknown): value is IContext<unknown> | IUnion<unknown> | IArray<unknown> | IConst<unknown> | IIdent<unknown> | INumber<unknown> | IOptional<unknown> | IRef<unknown> | IString<unknown> | ITuple<unknown>;

View File

@@ -0,0 +1,86 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.IsArray = IsArray;
exports.IsConst = IsConst;
exports.IsContext = IsContext;
exports.IsIdent = IsIdent;
exports.IsNumber = IsNumber;
exports.IsOptional = IsOptional;
exports.IsRef = IsRef;
exports.IsString = IsString;
exports.IsTuple = IsTuple;
exports.IsUnion = IsUnion;
exports.IsParser = IsParser;
// ------------------------------------------------------------------
// Value Guard
// ------------------------------------------------------------------
// prettier-ignore
function HasPropertyKey(value, key) {
return key in value;
}
// prettier-ignore
function IsObjectValue(value) {
return typeof value === 'object' && value !== null;
}
// prettier-ignore
function IsArrayValue(value) {
return globalThis.Array.isArray(value);
}
// ------------------------------------------------------------------
// Parser Guard
// ------------------------------------------------------------------
/** Returns true if the value is a Array Parser */
function IsArray(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Array' && HasPropertyKey(value, 'parser') && IsObjectValue(value.parser);
}
/** Returns true if the value is a Const Parser */
function IsConst(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Const' && HasPropertyKey(value, 'value') && typeof value.value === 'string';
}
/** Returns true if the value is a Context Parser */
function IsContext(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Context' && HasPropertyKey(value, 'left') && IsParser(value.left) && HasPropertyKey(value, 'right') && IsParser(value.right);
}
/** Returns true if the value is a Ident Parser */
function IsIdent(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Ident';
}
/** Returns true if the value is a Number Parser */
function IsNumber(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Number';
}
/** Returns true if the value is a Optional Parser */
function IsOptional(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Optional' && HasPropertyKey(value, 'parser') && IsObjectValue(value.parser);
}
/** Returns true if the value is a Ref Parser */
function IsRef(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Ref' && HasPropertyKey(value, 'ref') && typeof value.ref === 'string';
}
/** Returns true if the value is a String Parser */
function IsString(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'String' && HasPropertyKey(value, 'options') && IsArrayValue(value.options);
}
/** Returns true if the value is a Tuple Parser */
function IsTuple(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Tuple' && HasPropertyKey(value, 'parsers') && IsArrayValue(value.parsers);
}
/** Returns true if the value is a Union Parser */
function IsUnion(value) {
return IsObjectValue(value) && HasPropertyKey(value, 'type') && value.type === 'Union' && HasPropertyKey(value, 'parsers') && IsArrayValue(value.parsers);
}
/** Returns true if the value is a Parser */
function IsParser(value) {
// prettier-ignore
return (IsArray(value) ||
IsConst(value) ||
IsContext(value) ||
IsIdent(value) ||
IsNumber(value) ||
IsOptional(value) ||
IsRef(value) ||
IsString(value) ||
IsTuple(value) ||
IsUnion(value));
}

View File

@@ -0,0 +1,5 @@
export * as Guard from './guard';
export * as Token from './token';
export * from './types';
export * from './module';
export * from './parse';

View File

@@ -0,0 +1,45 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Token = exports.Guard = void 0;
exports.Guard = __importStar(require("./guard"));
exports.Token = __importStar(require("./token"));
__exportStar(require("./types"), exports);
__exportStar(require("./module"), exports);
__exportStar(require("./parse"), exports);

View File

@@ -0,0 +1,9 @@
import * as Types from './types';
export declare class Module<Properties extends Types.IModuleProperties = Types.IModuleProperties> {
private readonly properties;
constructor(properties: Properties);
/** Parses using one of the parsers defined on this instance */
Parse<Key extends keyof Properties>(key: Key, content: string, context: unknown): [] | [Types.StaticParser<Properties[Key]>, string];
/** Parses using one of the parsers defined on this instance */
Parse<Key extends keyof Properties>(key: Key, content: string): [] | [Types.StaticParser<Properties[Key]>, string];
}

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Module = void 0;
const parse_1 = require("./parse");
// ------------------------------------------------------------------
// Module
// ------------------------------------------------------------------
class Module {
constructor(properties) {
this.properties = properties;
}
/** Parses using one of the parsers defined on this instance */
Parse(...args) {
// prettier-ignore
const [key, content, context] = (args.length === 3 ? [args[0], args[1], args[2]] :
args.length === 2 ? [args[0], args[1], undefined] :
(() => { throw Error('Invalid parse arguments'); })());
return (0, parse_1.Parse)(this.properties, this.properties[key], content, context);
}
}
exports.Module = Module;

View File

@@ -0,0 +1,9 @@
import * as Types from './types';
/** Parses content using the given Parser */
export declare function Parse<Parser extends Types.IParser>(moduleProperties: Types.IModuleProperties, parser: Parser, code: string, context: unknown): [] | [Types.StaticParser<Parser>, string];
/** Parses content using the given Parser */
export declare function Parse<Parser extends Types.IParser>(moduleProperties: Types.IModuleProperties, parser: Parser, code: string): [] | [Types.StaticParser<Parser>, string];
/** Parses content using the given Parser */
export declare function Parse<Parser extends Types.IParser>(parser: Parser, content: string, context: unknown): [] | [Types.StaticParser<Parser>, string];
/** Parses content using the given Parser */
export declare function Parse<Parser extends Types.IParser>(parser: Parser, content: string): [] | [Types.StaticParser<Parser>, string];

View File

@@ -0,0 +1,160 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.Parse = Parse;
const Guard = __importStar(require("./guard"));
const Token = __importStar(require("./token"));
// ------------------------------------------------------------------
// Context
// ------------------------------------------------------------------
function ParseContext(moduleProperties, left, right, code, context) {
const result = ParseParser(moduleProperties, left, code, context);
return result.length === 2 ? ParseParser(moduleProperties, right, result[1], result[0]) : [];
}
// ------------------------------------------------------------------
// Array
// ------------------------------------------------------------------
function ParseArray(moduleProperties, parser, code, context) {
const buffer = [];
let rest = code;
while (rest.length > 0) {
const result = ParseParser(moduleProperties, parser, rest, context);
if (result.length === 0)
return [buffer, rest];
buffer.push(result[0]);
rest = result[1];
}
return [buffer, rest];
}
// ------------------------------------------------------------------
// Const
// ------------------------------------------------------------------
function ParseConst(value, code, context) {
return Token.Const(value, code);
}
// ------------------------------------------------------------------
// Ident
// ------------------------------------------------------------------
function ParseIdent(code, _context) {
return Token.Ident(code);
}
// ------------------------------------------------------------------
// Number
// ------------------------------------------------------------------
// prettier-ignore
function ParseNumber(code, _context) {
return Token.Number(code);
}
// ------------------------------------------------------------------
// Optional
// ------------------------------------------------------------------
function ParseOptional(moduleProperties, parser, code, context) {
const result = ParseParser(moduleProperties, parser, code, context);
return (result.length === 2 ? [[result[0]], result[1]] : [[], code]);
}
// ------------------------------------------------------------------
// Ref
// ------------------------------------------------------------------
function ParseRef(moduleProperties, ref, code, context) {
const parser = moduleProperties[ref];
if (!Guard.IsParser(parser))
throw Error(`Cannot dereference Parser '${ref}'`);
return ParseParser(moduleProperties, parser, code, context);
}
// ------------------------------------------------------------------
// String
// ------------------------------------------------------------------
// prettier-ignore
function ParseString(options, code, _context) {
return Token.String(options, code);
}
// ------------------------------------------------------------------
// Tuple
// ------------------------------------------------------------------
function ParseTuple(moduleProperties, parsers, code, context) {
const buffer = [];
let rest = code;
for (const parser of parsers) {
const result = ParseParser(moduleProperties, parser, rest, context);
if (result.length === 0)
return [];
buffer.push(result[0]);
rest = result[1];
}
return [buffer, rest];
}
// ------------------------------------------------------------------
// Union
// ------------------------------------------------------------------
// prettier-ignore
function ParseUnion(moduleProperties, parsers, code, context) {
for (const parser of parsers) {
const result = ParseParser(moduleProperties, parser, code, context);
if (result.length === 0)
continue;
return result;
}
return [];
}
// ------------------------------------------------------------------
// Parser
// ------------------------------------------------------------------
// prettier-ignore
function ParseParser(moduleProperties, parser, code, context) {
const result = (Guard.IsContext(parser) ? ParseContext(moduleProperties, parser.left, parser.right, code, context) :
Guard.IsArray(parser) ? ParseArray(moduleProperties, parser.parser, code, context) :
Guard.IsConst(parser) ? ParseConst(parser.value, code, context) :
Guard.IsIdent(parser) ? ParseIdent(code, context) :
Guard.IsNumber(parser) ? ParseNumber(code, context) :
Guard.IsOptional(parser) ? ParseOptional(moduleProperties, parser.parser, code, context) :
Guard.IsRef(parser) ? ParseRef(moduleProperties, parser.ref, code, context) :
Guard.IsString(parser) ? ParseString(parser.options, code, context) :
Guard.IsTuple(parser) ? ParseTuple(moduleProperties, parser.parsers, code, context) :
Guard.IsUnion(parser) ? ParseUnion(moduleProperties, parser.parsers, code, context) :
[]);
return (result.length === 2
? [parser.mapping(result[0], context), result[1]]
: result);
}
/** Parses content using the given parser */
// prettier-ignore
function Parse(...args) {
const withModuleProperties = typeof args[1] === 'string' ? false : true;
const [moduleProperties, parser, content, context] = withModuleProperties
? [args[0], args[1], args[2], args[3]]
: [{}, args[0], args[1], args[2]];
return ParseParser(moduleProperties, parser, content, context);
}

View File

@@ -0,0 +1,8 @@
/** Takes the next constant string value skipping any whitespace */
export declare function Const(value: string, code: string): [] | [string, string];
/** Scans for the next Ident token */
export declare function Ident(code: string): [] | [string, string];
/** Scans for the next number token */
export declare function Number(code: string): [string, string] | [];
/** Scans the next Literal String value */
export declare function String(options: string[], code: string): [string, string] | [];

View File

@@ -0,0 +1,230 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Const = Const;
exports.Ident = Ident;
exports.Number = Number;
exports.String = String;
// ------------------------------------------------------------------
// Chars
// ------------------------------------------------------------------
// prettier-ignore
var Chars;
(function (Chars) {
/** Returns true if the char code is a whitespace */
function IsWhitespace(value) {
return value === 32;
}
Chars.IsWhitespace = IsWhitespace;
/** Returns true if the char code is a newline */
function IsNewline(value) {
return value === 10;
}
Chars.IsNewline = IsNewline;
/** Returns true if the char code is a alpha */
function IsAlpha(value) {
return ((value >= 65 && value <= 90) || // A-Z
(value >= 97 && value <= 122) // a-z
);
}
Chars.IsAlpha = IsAlpha;
/** Returns true if the char code is zero */
function IsZero(value) {
return value === 48;
}
Chars.IsZero = IsZero;
/** Returns true if the char code is non-zero */
function IsNonZero(value) {
return value >= 49 && value <= 57;
}
Chars.IsNonZero = IsNonZero;
/** Returns true if the char code is a digit */
function IsDigit(value) {
return (IsNonZero(value) ||
IsZero(value));
}
Chars.IsDigit = IsDigit;
/** Returns true if the char code is a dot */
function IsDot(value) {
return value === 46;
}
Chars.IsDot = IsDot;
/** Returns true if this char code is a underscore */
function IsUnderscore(value) {
return value === 95;
}
Chars.IsUnderscore = IsUnderscore;
/** Returns true if this char code is a dollar sign */
function IsDollarSign(value) {
return value === 36;
}
Chars.IsDollarSign = IsDollarSign;
})(Chars || (Chars = {}));
// ------------------------------------------------------------------
// Trim
// ------------------------------------------------------------------
// prettier-ignore
var Trim;
(function (Trim) {
/** Trims Whitespace and retains Newline, Tabspaces, etc. */
function TrimWhitespaceOnly(code) {
for (let i = 0; i < code.length; i++) {
if (Chars.IsWhitespace(code.charCodeAt(i)))
continue;
return code.slice(i);
}
return code;
}
Trim.TrimWhitespaceOnly = TrimWhitespaceOnly;
/** Trims Whitespace including Newline, Tabspaces, etc. */
function TrimAll(code) {
return code.trimStart();
}
Trim.TrimAll = TrimAll;
})(Trim || (Trim = {}));
// ------------------------------------------------------------------
// Const
// ------------------------------------------------------------------
/** Checks the value matches the next string */
// prettier-ignore
function NextTokenCheck(value, code) {
if (value.length > code.length)
return false;
for (let i = 0; i < value.length; i++) {
if (value.charCodeAt(i) !== code.charCodeAt(i))
return false;
}
return true;
}
/** Gets the next constant string value or empty if no match */
// prettier-ignore
function NextConst(value, code) {
return NextTokenCheck(value, code)
? [code.slice(0, value.length), code.slice(value.length)]
: [];
}
/** Takes the next constant string value skipping any whitespace */
// prettier-ignore
function Const(value, code) {
if (value.length === 0)
return ['', code];
const char_0 = value.charCodeAt(0);
return (Chars.IsNewline(char_0) ? NextConst(value, Trim.TrimWhitespaceOnly(code)) :
Chars.IsWhitespace(char_0) ? NextConst(value, code) :
NextConst(value, Trim.TrimAll(code)));
}
// ------------------------------------------------------------------
// Ident
// ------------------------------------------------------------------
// prettier-ignore
function IdentIsFirst(char) {
return (Chars.IsAlpha(char) ||
Chars.IsDollarSign(char) ||
Chars.IsUnderscore(char));
}
// prettier-ignore
function IdentIsRest(char) {
return (Chars.IsAlpha(char) ||
Chars.IsDigit(char) ||
Chars.IsDollarSign(char) ||
Chars.IsUnderscore(char));
}
// prettier-ignore
function NextIdent(code) {
if (!IdentIsFirst(code.charCodeAt(0)))
return [];
for (let i = 1; i < code.length; i++) {
const char = code.charCodeAt(i);
if (IdentIsRest(char))
continue;
const slice = code.slice(0, i);
const rest = code.slice(i);
return [slice, rest];
}
return [code, ''];
}
/** Scans for the next Ident token */
// prettier-ignore
function Ident(code) {
return NextIdent(Trim.TrimAll(code));
}
// ------------------------------------------------------------------
// Number
// ------------------------------------------------------------------
/** Checks that the next number is not a leading zero */
// prettier-ignore
function NumberLeadingZeroCheck(code, index) {
const char_0 = code.charCodeAt(index + 0);
const char_1 = code.charCodeAt(index + 1);
return ((
// 1-9
Chars.IsNonZero(char_0)) || (
// 0
Chars.IsZero(char_0) &&
!Chars.IsDigit(char_1)) || (
// 0.
Chars.IsZero(char_0) &&
Chars.IsDot(char_1)) || (
// .0
Chars.IsDot(char_0) &&
Chars.IsDigit(char_1)));
}
/** Gets the next number token */
// prettier-ignore
function NextNumber(code) {
const negated = code.charAt(0) === '-';
const index = negated ? 1 : 0;
if (!NumberLeadingZeroCheck(code, index)) {
return [];
}
const dash = negated ? '-' : '';
let hasDot = false;
for (let i = index; i < code.length; i++) {
const char_i = code.charCodeAt(i);
if (Chars.IsDigit(char_i)) {
continue;
}
if (Chars.IsDot(char_i)) {
if (hasDot) {
const slice = code.slice(index, i);
const rest = code.slice(i);
return [`${dash}${slice}`, rest];
}
hasDot = true;
continue;
}
const slice = code.slice(index, i);
const rest = code.slice(i);
return [`${dash}${slice}`, rest];
}
return [code, ''];
}
/** Scans for the next number token */
// prettier-ignore
function Number(code) {
return NextNumber(Trim.TrimAll(code));
}
// ------------------------------------------------------------------
// String
// ------------------------------------------------------------------
// prettier-ignore
function NextString(options, code) {
const first = code.charAt(0);
if (!options.includes(first))
return [];
const quote = first;
for (let i = 1; i < code.length; i++) {
const char = code.charAt(i);
if (char === quote) {
const slice = code.slice(1, i);
const rest = code.slice(i + 1);
return [slice, rest];
}
}
return [];
}
/** Scans the next Literal String value */
// prettier-ignore
function String(options, code) {
return NextString(options, Trim.TrimAll(code));
}

View File

@@ -0,0 +1,98 @@
export type IModuleProperties = Record<PropertyKey, IParser>;
/** Force output static type evaluation for Arrays */
export type StaticEnsure<T> = T extends infer R ? R : never;
/** Infers the Output Parameter for a Parser */
export type StaticParser<Parser extends IParser> = Parser extends IParser<infer Output extends unknown> ? Output : unknown;
export type IMapping<Input extends unknown = any, Output extends unknown = unknown> = (input: Input, context: any) => Output;
/** Maps input to output. This is the default Mapping */
export declare const Identity: (value: unknown) => unknown;
/** Maps the output as the given parameter T */
export declare const As: <T>(mapping: T) => ((value: unknown) => T);
export interface IParser<Output extends unknown = unknown> {
type: string;
mapping: IMapping<any, Output>;
}
export type ContextParameter<_Left extends IParser, Right extends IParser> = (StaticParser<Right>);
export interface IContext<Output extends unknown = unknown> extends IParser<Output> {
type: 'Context';
left: IParser;
right: IParser;
}
/** `[Context]` Creates a Context Parser */
export declare function Context<Left extends IParser, Right extends IParser, Mapping extends IMapping = IMapping<ContextParameter<Left, Right>>>(left: Left, right: Right, mapping: Mapping): IContext<ReturnType<Mapping>>;
/** `[Context]` Creates a Context Parser */
export declare function Context<Left extends IParser, Right extends IParser>(left: Left, right: Right): IContext<ContextParameter<Left, Right>>;
export type ArrayParameter<Parser extends IParser> = StaticEnsure<StaticParser<Parser>[]>;
export interface IArray<Output extends unknown = unknown> extends IParser<Output> {
type: 'Array';
parser: IParser;
}
/** `[EBNF]` Creates an Array Parser */
export declare function Array<Parser extends IParser, Mapping extends IMapping = IMapping<ArrayParameter<Parser>>>(parser: Parser, mapping: Mapping): IArray<ReturnType<Mapping>>;
/** `[EBNF]` Creates an Array Parser */
export declare function Array<Parser extends IParser>(parser: Parser): IArray<ArrayParameter<Parser>>;
export interface IConst<Output extends unknown = unknown> extends IParser<Output> {
type: 'Const';
value: string;
}
/** `[TERM]` Creates a Const Parser */
export declare function Const<Value extends string, Mapping extends IMapping<Value>>(value: Value, mapping: Mapping): IConst<ReturnType<Mapping>>;
/** `[TERM]` Creates a Const Parser */
export declare function Const<Value extends string>(value: Value): IConst<Value>;
export interface IRef<Output extends unknown = unknown> extends IParser<Output> {
type: 'Ref';
ref: string;
}
/** `[BNF]` Creates a Ref Parser. This Parser can only be used in the context of a Module */
export declare function Ref<Type extends unknown, Mapping extends IMapping<Type>>(ref: string, mapping: Mapping): IRef<ReturnType<Mapping>>;
/** `[BNF]` Creates a Ref Parser. This Parser can only be used in the context of a Module */
export declare function Ref<Type extends unknown>(ref: string): IRef<Type>;
export interface IString<Output extends unknown = unknown> extends IParser<Output> {
type: 'String';
options: string[];
}
/** `[TERM]` Creates a String Parser. Options are an array of permissable quote characters */
export declare function String<Mapping extends IMapping<string>>(options: string[], mapping: Mapping): IString<ReturnType<Mapping>>;
/** `[TERM]` Creates a String Parser. Options are an array of permissable quote characters */
export declare function String(options: string[]): IString<string>;
export interface IIdent<Output extends unknown = unknown> extends IParser<Output> {
type: 'Ident';
}
/** `[TERM]` Creates an Ident Parser where Ident matches any valid JavaScript identifier */
export declare function Ident<Mapping extends IMapping<string>>(mapping: Mapping): IIdent<ReturnType<Mapping>>;
/** `[TERM]` Creates an Ident Parser where Ident matches any valid JavaScript identifier */
export declare function Ident(): IIdent<string>;
export interface INumber<Output extends unknown = unknown> extends IParser<Output> {
type: 'Number';
}
/** `[TERM]` Creates an Number Parser */
export declare function Number<Mapping extends IMapping<string>>(mapping: Mapping): INumber<ReturnType<Mapping>>;
/** `[TERM]` Creates an Number Parser */
export declare function Number(): INumber<string>;
export type OptionalParameter<Parser extends IParser, Result extends unknown = [StaticParser<Parser>] | []> = (Result);
export interface IOptional<Output extends unknown = unknown> extends IParser<Output> {
type: 'Optional';
parser: IParser;
}
/** `[EBNF]` Creates an Optional Parser */
export declare function Optional<Parser extends IParser, Mapping extends IMapping = IMapping<OptionalParameter<Parser>>>(parser: Parser, mapping: Mapping): IOptional<ReturnType<Mapping>>;
/** `[EBNF]` Creates an Optional Parser */
export declare function Optional<Parser extends IParser>(parser: Parser): IOptional<OptionalParameter<Parser>>;
export type TupleParameter<Parsers extends IParser[], Result extends unknown[] = []> = StaticEnsure<Parsers extends [infer Left extends IParser, ...infer Right extends IParser[]] ? TupleParameter<Right, [...Result, StaticEnsure<StaticParser<Left>>]> : Result>;
export interface ITuple<Output extends unknown = unknown> extends IParser<Output> {
type: 'Tuple';
parsers: IParser[];
}
/** `[BNF]` Creates a Tuple Parser */
export declare function Tuple<Parsers extends IParser[], Mapping extends IMapping = IMapping<TupleParameter<Parsers>>>(parsers: [...Parsers], mapping: Mapping): ITuple<ReturnType<Mapping>>;
/** `[BNF]` Creates a Tuple Parser */
export declare function Tuple<Parsers extends IParser[]>(parsers: [...Parsers]): ITuple<TupleParameter<Parsers>>;
export type UnionParameter<Parsers extends IParser[], Result extends unknown = never> = StaticEnsure<Parsers extends [infer Left extends IParser, ...infer Right extends IParser[]] ? UnionParameter<Right, Result | StaticParser<Left>> : Result>;
export interface IUnion<Output extends unknown = unknown> extends IParser<Output> {
type: 'Union';
parsers: IParser[];
}
/** `[BNF]` Creates a Union parser */
export declare function Union<Parsers extends IParser[], Mapping extends IMapping = IMapping<UnionParameter<Parsers>>>(parsers: [...Parsers], mapping: Mapping): IUnion<ReturnType<Mapping>>;
/** `[BNF]` Creates a Union parser */
export declare function Union<Parsers extends IParser[]>(parsers: [...Parsers]): IUnion<UnionParameter<Parsers>>;

View File

@@ -0,0 +1,71 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.As = exports.Identity = void 0;
exports.Context = Context;
exports.Array = Array;
exports.Const = Const;
exports.Ref = Ref;
exports.String = String;
exports.Ident = Ident;
exports.Number = Number;
exports.Optional = Optional;
exports.Tuple = Tuple;
exports.Union = Union;
/** Maps input to output. This is the default Mapping */
const Identity = (value) => value;
exports.Identity = Identity;
/** Maps the output as the given parameter T */
// prettier-ignore
const As = (mapping) => (_) => mapping;
exports.As = As;
/** `[Context]` Creates a Context Parser */
function Context(...args) {
const [left, right, mapping] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], args[1], exports.Identity];
return { type: 'Context', left, right, mapping };
}
/** `[EBNF]` Creates an Array Parser */
function Array(...args) {
const [parser, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Array', parser, mapping };
}
/** `[TERM]` Creates a Const Parser */
function Const(...args) {
const [value, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Const', value, mapping };
}
/** `[BNF]` Creates a Ref Parser. This Parser can only be used in the context of a Module */
function Ref(...args) {
const [ref, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Ref', ref, mapping };
}
/** `[TERM]` Creates a String Parser. Options are an array of permissable quote characters */
function String(...params) {
const [options, mapping] = params.length === 2 ? [params[0], params[1]] : [params[0], exports.Identity];
return { type: 'String', options, mapping };
}
/** `[TERM]` Creates an Ident Parser where Ident matches any valid JavaScript identifier */
function Ident(...params) {
const mapping = params.length === 1 ? params[0] : exports.Identity;
return { type: 'Ident', mapping };
}
/** `[TERM]` Creates an Number Parser */
function Number(...params) {
const mapping = params.length === 1 ? params[0] : exports.Identity;
return { type: 'Number', mapping };
}
/** `[EBNF]` Creates an Optional Parser */
function Optional(...args) {
const [parser, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Optional', parser, mapping };
}
/** `[BNF]` Creates a Tuple Parser */
function Tuple(...args) {
const [parsers, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Tuple', parsers, mapping };
}
/** `[BNF]` Creates a Union parser */
function Union(...args) {
const [parsers, mapping] = args.length === 2 ? [args[0], args[1]] : [args[0], exports.Identity];
return { type: 'Union', parsers, mapping };
}

View File

@@ -0,0 +1,3 @@
export * as Token from './token';
export * from './parse';
export * from './types';

View File

@@ -0,0 +1,43 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Token = void 0;
exports.Token = __importStar(require("./token"));
__exportStar(require("./parse"), exports);
__exportStar(require("./types"), exports);

View File

@@ -0,0 +1,20 @@
import * as Tokens from './token';
import * as Types from './types';
type ContextParser<Left extends Types.IParser, Right extends Types.IParser, Code extends string, Context extends unknown> = (Parse<Left, Code, Context> extends [infer Context extends unknown, infer Rest extends string] ? Parse<Right, Rest, Context> : []);
type ArrayParser<Parser extends Types.IParser, Code extends string, Context extends unknown, Result extends unknown[] = []> = (Parse<Parser, Code, Context> extends [infer Value1 extends unknown, infer Rest extends string] ? ArrayParser<Parser, Rest, Context, [...Result, Value1]> : [Result, Code]);
type ConstParser<Value extends string, Code extends string, _Context extends unknown> = (Tokens.Const<Value, Code> extends [infer Match extends Value, infer Rest extends string] ? [Match, Rest] : []);
type IdentParser<Code extends string, _Context extends unknown> = (Tokens.Ident<Code> extends [infer Match extends string, infer Rest extends string] ? [Match, Rest] : []);
type NumberParser<Code extends string, _Context extends unknown> = (Tokens.Number<Code> extends [infer Match extends string, infer Rest extends string] ? [Match, Rest] : []);
type OptionalParser<Parser extends Types.IParser, Code extends string, Context extends unknown> = (Parse<Parser, Code, Context> extends [infer Value extends unknown, infer Rest extends string] ? [[Value], Rest] : [[], Code]);
type StringParser<Options extends string[], Code extends string, _Context extends unknown> = (Tokens.String<Options, Code> extends [infer Match extends string, infer Rest extends string] ? [Match, Rest] : []);
type TupleParser<Parsers extends Types.IParser[], Code extends string, Context extends unknown, Result extends unknown[] = []> = (Parsers extends [infer Left extends Types.IParser, ...infer Right extends Types.IParser[]] ? Parse<Left, Code, Context> extends [infer Value extends unknown, infer Rest extends string] ? TupleParser<Right, Rest, Context, [...Result, Value]> : [] : [Result, Code]);
type UnionParser<Parsers extends Types.IParser[], Code extends string, Context extends unknown> = (Parsers extends [infer Left extends Types.IParser, ...infer Right extends Types.IParser[]] ? Parse<Left, Code, Context> extends [infer Value extends unknown, infer Rest extends string] ? [Value, Rest] : UnionParser<Right, Code, Context> : []);
type ParseCode<Type extends Types.IParser, Code extends string, Context extends unknown = unknown> = (Type extends Types.Context<infer Left extends Types.IParser, infer Right extends Types.IParser> ? ContextParser<Left, Right, Code, Context> : Type extends Types.Array<infer Parser extends Types.IParser> ? ArrayParser<Parser, Code, Context> : Type extends Types.Const<infer Value extends string> ? ConstParser<Value, Code, Context> : Type extends Types.Ident ? IdentParser<Code, Context> : Type extends Types.Number ? NumberParser<Code, Context> : Type extends Types.Optional<infer Parser extends Types.IParser> ? OptionalParser<Parser, Code, Context> : Type extends Types.String<infer Options extends string[]> ? StringParser<Options, Code, Context> : Type extends Types.Tuple<infer Parsers extends Types.IParser[]> ? TupleParser<Parsers, Code, Context> : Type extends Types.Union<infer Parsers extends Types.IParser[]> ? UnionParser<Parsers, Code, Context> : [
]);
type ParseMapping<Parser extends Types.IParser, Result extends unknown, Context extends unknown = unknown> = ((Parser['mapping'] & {
input: Result;
context: Context;
})['output']);
/** Parses code with the given parser */
export type Parse<Type extends Types.IParser, Code extends string, Context extends unknown = unknown> = (ParseCode<Type, Code, Context> extends [infer L extends unknown, infer R extends string] ? [ParseMapping<Type, L, Context>, R] : []);
export {};

View File

@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,108 @@
declare namespace Chars {
type Empty = '';
type Space = ' ';
type Newline = '\n';
type Dot = '.';
type Hyphen = '-';
type Digit = [
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9'
];
type Alpha = [
'a',
'b',
'c',
'd',
'e',
'f',
'g',
'h',
'i',
'j',
'k',
'l',
'm',
'n',
'o',
'p',
'q',
'r',
's',
't',
'u',
'v',
'w',
'x',
'y',
'z',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z'
];
}
declare namespace Trim {
type W4 = `${W3}${W3}`;
type W3 = `${W2}${W2}`;
type W2 = `${W1}${W1}`;
type W1 = `${W0}${W0}`;
type W0 = ` `;
/** Trims whitespace only */
export type TrimWhitespace<Code extends string> = (Code extends `${W4}${infer Rest extends string}` ? TrimWhitespace<Rest> : Code extends `${W3}${infer Rest extends string}` ? TrimWhitespace<Rest> : Code extends `${W1}${infer Rest extends string}` ? TrimWhitespace<Rest> : Code extends `${W0}${infer Rest extends string}` ? TrimWhitespace<Rest> : Code);
/** Trims Whitespace and Newline */
export type TrimAll<Code extends string> = (Code extends `${W4}${infer Rest extends string}` ? TrimAll<Rest> : Code extends `${W3}${infer Rest extends string}` ? TrimAll<Rest> : Code extends `${W1}${infer Rest extends string}` ? TrimAll<Rest> : Code extends `${W0}${infer Rest extends string}` ? TrimAll<Rest> : Code extends `${Chars.Newline}${infer Rest extends string}` ? TrimAll<Rest> : Code);
export {};
}
/** Scans for the next match union */
type NextUnion<Variants extends string[], Code extends string> = (Variants extends [infer Variant extends string, ...infer Rest1 extends string[]] ? NextConst<Variant, Code> extends [infer Match extends string, infer Rest2 extends string] ? [Match, Rest2] : NextUnion<Rest1, Code> : []);
type NextConst<Value extends string, Code extends string> = (Code extends `${Value}${infer Rest extends string}` ? [Value, Rest] : []);
/** Scans for the next constant value */
export type Const<Value extends string, Code extends string> = (Value extends '' ? ['', Code] : Value extends `${infer First extends string}${string}` ? (First extends Chars.Newline ? NextConst<Value, Trim.TrimWhitespace<Code>> : First extends Chars.Space ? NextConst<Value, Code> : NextConst<Value, Trim.TrimAll<Code>>) : never);
type NextNumberNegate<Code extends string> = (Code extends `${Chars.Hyphen}${infer Rest extends string}` ? [Chars.Hyphen, Rest] : [Chars.Empty, Code]);
type NextNumberZeroCheck<Code extends string> = (Code extends `0${infer Rest}` ? NextUnion<Chars.Digit, Rest> extends [string, string] ? false : true : true);
type NextNumberScan<Code extends string, HasDecimal extends boolean = false, Result extends string = Chars.Empty> = (NextUnion<[...Chars.Digit, Chars.Dot], Code> extends [infer Char extends string, infer Rest extends string] ? Char extends Chars.Dot ? HasDecimal extends false ? NextNumberScan<Rest, true, `${Result}${Char}`> : [Result, `.${Rest}`] : NextNumberScan<Rest, HasDecimal, `${Result}${Char}`> : [Result, Code]);
export type NextNumber<Code extends string> = (NextNumberNegate<Code> extends [infer Negate extends string, infer Rest extends string] ? NextNumberZeroCheck<Rest> extends true ? NextNumberScan<Rest> extends [infer Number extends string, infer Rest2 extends string] ? Number extends Chars.Empty ? [] : [`${Negate}${Number}`, Rest2] : [] : [] : []);
/** Scans for the next literal number */
export type Number<Code extends string> = NextNumber<Trim.TrimAll<Code>>;
type NextStringQuote<Options extends string[], Code extends string> = NextUnion<Options, Code>;
type NextStringBody<Code extends string, Quote extends string, Result extends string = Chars.Empty> = (Code extends `${infer Char extends string}${infer Rest extends string}` ? Char extends Quote ? [Result, Rest] : NextStringBody<Rest, Quote, `${Result}${Char}`> : []);
type NextString<Options extends string[], Code extends string> = (NextStringQuote<Options, Code> extends [infer Quote extends string, infer Rest extends string] ? NextStringBody<Rest, Quote> extends [infer String extends string, infer Rest extends string] ? [String, Rest] : [] : []);
/** Scans for the next literal string */
export type String<Options extends string[], Code extends string> = NextString<Options, Trim.TrimAll<Code>>;
type IdentLeft = [...Chars.Alpha, '_', '$'];
type IdentRight = [...Chars.Digit, ...IdentLeft];
type NextIdentScan<Code extends string, Result extends string = Chars.Empty> = (NextUnion<IdentRight, Code> extends [infer Char extends string, infer Rest extends string] ? NextIdentScan<Rest, `${Result}${Char}`> : [Result, Code]);
type NextIdent<Code extends string> = (NextUnion<IdentLeft, Code> extends [infer Left extends string, infer Rest1 extends string] ? NextIdentScan<Rest1> extends [infer Right extends string, infer Rest2 extends string] ? [`${Left}${Right}`, Rest2] : [] : []);
/** Scans for the next Ident */
export type Ident<Code extends string> = NextIdent<Trim.TrimAll<Code>>;
export {};

View File

@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1,69 @@
/**
* `[ACTION]` Inference mapping base type. Used to specify semantic actions for
* Parser productions. This type is implemented as a higher-kinded type where
* productions are received on the `input` property with mapping assigned
* the `output` property. The parsing context is available on the `context`
* property.
*/
export interface IMapping {
context: unknown;
input: unknown;
output: unknown;
}
/** `[ACTION]` Default inference mapping. */
export interface Identity extends IMapping {
output: this['input'];
}
/** `[ACTION]` Maps the given argument `T` as the mapping output */
export interface As<T> extends IMapping {
output: T;
}
/** Base type Parser implemented by all other parsers */
export interface IParser<Mapping extends IMapping = Identity> {
type: string;
mapping: Mapping;
}
/** `[Context]` Creates a Context Parser */
export interface Context<Left extends IParser = IParser, Right extends IParser = IParser, Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Context';
left: Left;
right: Right;
}
/** `[EBNF]` Creates an Array Parser */
export interface Array<Parser extends IParser = IParser, Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Array';
parser: Parser;
}
/** `[TERM]` Creates a Const Parser */
export interface Const<Value extends string = string, Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Const';
value: Value;
}
/** `[TERM]` Creates an Ident Parser. */
export interface Ident<Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Ident';
}
/** `[TERM]` Creates a Number Parser. */
export interface Number<Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Number';
}
/** `[EBNF]` Creates a Optional Parser */
export interface Optional<Parser extends IParser = IParser, Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Optional';
parser: Parser;
}
/** `[TERM]` Creates a String Parser. Options are an array of permissable quote characters */
export interface String<Options extends string[], Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'String';
quote: Options;
}
/** `[BNF]` Creates a Tuple Parser */
export interface Tuple<Parsers extends IParser[] = [], Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Tuple';
parsers: [...Parsers];
}
/** `[BNF]` Creates a Union Parser */
export interface Union<Parsers extends IParser[] = [], Mapping extends IMapping = Identity> extends IParser<Mapping> {
type: 'Union';
parsers: [...Parsers];
}

View File

@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@@ -0,0 +1 @@
export * from './syntax';

View File

@@ -0,0 +1,18 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./syntax"), exports);

View File

@@ -0,0 +1,167 @@
import * as T from '../type/index';
type TDereference<Context extends T.TProperties, Key extends string> = (Key extends keyof Context ? Context[Key] : T.TRef<Key>);
type TDelimitedDecode<Input extends ([unknown, unknown] | unknown)[], Result extends unknown[] = []> = (Input extends [infer Left, ...infer Right] ? Left extends [infer Item, infer _] ? TDelimitedDecode<Right, [...Result, Item]> : TDelimitedDecode<Right, [...Result, Left]> : Result);
type TDelimited<Input extends [unknown, unknown]> = Input extends [infer Left extends unknown[], infer Right extends unknown[]] ? TDelimitedDecode<[...Left, ...Right]> : [];
export type TGenericReferenceParameterListMapping<Input extends [unknown, unknown], Context extends T.TProperties> = TDelimited<Input>;
export declare function GenericReferenceParameterListMapping(input: [unknown, unknown], context: unknown): unknown[];
export type TGenericReferenceMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties, Result = Context extends T.TProperties ? Input extends [infer Reference extends string, '<', infer Args extends T.TSchema[], '>'] ? T.TInstantiate<TDereference<Context, Reference>, Args> : never : never> = Result;
export declare function GenericReferenceMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TGenericArgumentsListMapping<Input extends [unknown, unknown], Context extends T.TProperties> = TDelimited<Input>;
export declare function GenericArgumentsListMapping(input: [unknown, unknown], context: unknown): unknown[];
type GenericArgumentsContext<Arguments extends string[], Context extends T.TProperties, Result extends T.TProperties = {}> = (Arguments extends [...infer Left extends string[], infer Right extends string] ? GenericArgumentsContext<Left, Context, Result & {
[_ in Right]: T.TArgument<Left['length']>;
}> : T.Evaluate<Result & Context>);
export type TGenericArgumentsMapping<Input extends [unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['<', infer Arguments extends string[], '>'] ? Context extends infer Context extends T.TProperties ? GenericArgumentsContext<Arguments, Context> : never : never;
declare const GenericArgumentsContext: (_arguments: string[], context: T.TProperties) => T.TProperties;
export declare function GenericArgumentsMapping(input: [unknown, unknown, unknown], context: unknown): T.TProperties;
export type TKeywordStringMapping<Input extends 'string', Context extends T.TProperties> = T.TString;
export declare function KeywordStringMapping(input: 'string', context: unknown): T.TString;
export type TKeywordNumberMapping<Input extends 'number', Context extends T.TProperties> = T.TNumber;
export declare function KeywordNumberMapping(input: 'number', context: unknown): T.TNumber;
export type TKeywordBooleanMapping<Input extends 'boolean', Context extends T.TProperties> = T.TBoolean;
export declare function KeywordBooleanMapping(input: 'boolean', context: unknown): T.TBoolean;
export type TKeywordUndefinedMapping<Input extends 'undefined', Context extends T.TProperties> = T.TUndefined;
export declare function KeywordUndefinedMapping(input: 'undefined', context: unknown): T.TUndefined;
export type TKeywordNullMapping<Input extends 'null', Context extends T.TProperties> = T.TNull;
export declare function KeywordNullMapping(input: 'null', context: unknown): T.TNull;
export type TKeywordIntegerMapping<Input extends 'integer', Context extends T.TProperties> = T.TInteger;
export declare function KeywordIntegerMapping(input: 'integer', context: unknown): T.TInteger;
export type TKeywordBigIntMapping<Input extends 'bigint', Context extends T.TProperties> = T.TBigInt;
export declare function KeywordBigIntMapping(input: 'bigint', context: unknown): T.TBigInt;
export type TKeywordUnknownMapping<Input extends 'unknown', Context extends T.TProperties> = T.TUnknown;
export declare function KeywordUnknownMapping(input: 'unknown', context: unknown): T.TUnknown;
export type TKeywordAnyMapping<Input extends 'any', Context extends T.TProperties> = T.TAny;
export declare function KeywordAnyMapping(input: 'any', context: unknown): T.TAny;
export type TKeywordNeverMapping<Input extends 'never', Context extends T.TProperties> = T.TNever;
export declare function KeywordNeverMapping(input: 'never', context: unknown): T.TNever;
export type TKeywordSymbolMapping<Input extends 'symbol', Context extends T.TProperties> = T.TSymbol;
export declare function KeywordSymbolMapping(input: 'symbol', context: unknown): T.TSymbol;
export type TKeywordVoidMapping<Input extends 'void', Context extends T.TProperties> = T.TVoid;
export declare function KeywordVoidMapping(input: 'void', context: unknown): T.TVoid;
export type TKeywordMapping<Input extends unknown, Context extends T.TProperties> = Input;
export declare function KeywordMapping(input: unknown, context: unknown): unknown;
export type TLiteralStringMapping<Input extends string, Context extends T.TProperties> = Input extends T.TLiteralValue ? T.TLiteral<Input> : never;
export declare function LiteralStringMapping(input: string, context: unknown): T.TLiteral<string>;
export type TLiteralNumberMapping<Input extends string, Context extends T.TProperties> = Input extends `${infer Value extends number}` ? T.TLiteral<Value> : never;
export declare function LiteralNumberMapping(input: string, context: unknown): T.TLiteral<number>;
export type TLiteralBooleanMapping<Input extends 'true' | 'false', Context extends T.TProperties> = Input extends 'true' ? T.TLiteral<true> : T.TLiteral<false>;
export declare function LiteralBooleanMapping(input: 'true' | 'false', context: unknown): T.TLiteral<boolean>;
export type TLiteralMapping<Input extends unknown, Context extends T.TProperties> = Input;
export declare function LiteralMapping(input: unknown, context: unknown): unknown;
export type TKeyOfMapping<Input extends [unknown] | [], Context extends T.TProperties> = Input extends [unknown] ? true : false;
export declare function KeyOfMapping(input: [unknown] | [], context: unknown): boolean;
type TIndexArrayMappingReduce<Input extends unknown[], Result extends unknown[] = []> = (Input extends [infer Left extends unknown, ...infer Right extends unknown[]] ? Left extends ['[', infer Type extends T.TSchema, ']'] ? TIndexArrayMappingReduce<Right, [...Result, [Type]]> : TIndexArrayMappingReduce<Right, [...Result, []]> : Result);
export type TIndexArrayMapping<Input extends ([unknown, unknown, unknown] | [unknown, unknown])[], Context extends T.TProperties> = Input extends unknown[] ? TIndexArrayMappingReduce<Input> : [];
export declare function IndexArrayMapping(input: ([unknown, unknown, unknown] | [unknown, unknown])[], context: unknown): unknown[];
export type TExtendsMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown] | [], Context extends T.TProperties> = Input extends ['extends', infer Type extends T.TSchema, '?', infer True extends T.TSchema, ':', infer False extends T.TSchema] ? [Type, True, False] : [];
export declare function ExtendsMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown] | [], context: unknown): unknown[];
export type TBaseMapping<Input extends [unknown, unknown, unknown] | unknown, Context extends T.TProperties> = (Input extends ['(', infer Type extends T.TSchema, ')'] ? Type : Input extends infer Type extends T.TSchema ? Type : never);
export declare function BaseMapping(input: [unknown, unknown, unknown] | unknown, context: unknown): unknown;
type TFactorIndexArray<Type extends T.TSchema, IndexArray extends unknown[]> = (IndexArray extends [...infer Left extends unknown[], infer Right extends T.TSchema[]] ? (Right extends [infer Indexer extends T.TSchema] ? T.TIndex<TFactorIndexArray<Type, Left>, T.TIndexPropertyKeys<Indexer>> : Right extends [] ? T.TArray<TFactorIndexArray<Type, Left>> : T.TNever) : Type);
type TFactorExtends<Type extends T.TSchema, Extends extends unknown[]> = (Extends extends [infer Right extends T.TSchema, infer True extends T.TSchema, infer False extends T.TSchema] ? T.TExtends<Type, Right, True, False> : Type);
export type TFactorMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends [infer KeyOf extends boolean, infer Type extends T.TSchema, infer IndexArray extends unknown[], infer Extends extends unknown[]] ? KeyOf extends true ? TFactorExtends<T.TKeyOf<TFactorIndexArray<Type, IndexArray>>, Extends> : TFactorExtends<TFactorIndexArray<Type, IndexArray>, Extends> : never;
export declare function FactorMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
type TExprBinaryMapping<Left extends T.TSchema, Rest extends unknown[]> = (Rest extends [infer Operator extends unknown, infer Right extends T.TSchema, infer Next extends unknown[]] ? (TExprBinaryMapping<Right, Next> extends infer Schema extends T.TSchema ? (Operator extends '&' ? (Schema extends T.TIntersect<infer Types extends T.TSchema[]> ? T.TIntersect<[Left, ...Types]> : T.TIntersect<[Left, Schema]>) : Operator extends '|' ? (Schema extends T.TUnion<infer Types extends T.TSchema[]> ? T.TUnion<[Left, ...Types]> : T.TUnion<[Left, Schema]>) : never) : never) : Left);
export type TExprTermTailMapping<Input extends [unknown, unknown, unknown] | [], Context extends T.TProperties> = Input;
export declare function ExprTermTailMapping(input: [unknown, unknown, unknown] | [], context: unknown): [] | [unknown, unknown, unknown];
export type TExprTermMapping<Input extends [unknown, unknown], Context extends T.TProperties> = (Input extends [infer Left extends T.TSchema, infer Rest extends unknown[]] ? TExprBinaryMapping<Left, Rest> : []);
export declare function ExprTermMapping(input: [unknown, unknown], context: unknown): T.TSchema;
export type TExprTailMapping<Input extends [unknown, unknown, unknown] | [], Context extends T.TProperties> = Input;
export declare function ExprTailMapping(input: [unknown, unknown, unknown] | [], context: unknown): [] | [unknown, unknown, unknown];
export type TExprMapping<Input extends [unknown, unknown], Context extends T.TProperties> = Input extends [infer Left extends T.TSchema, infer Rest extends unknown[]] ? TExprBinaryMapping<Left, Rest> : [];
export declare function ExprMapping(input: [unknown, unknown], context: unknown): T.TSchema;
export type TTypeMapping<Input extends unknown, Context extends T.TProperties> = Input;
export declare function TypeMapping(input: unknown, context: unknown): unknown;
export type TPropertyKeyMapping<Input extends string, Context extends T.TProperties> = Input;
export declare function PropertyKeyMapping(input: string, context: unknown): string;
export type TReadonlyMapping<Input extends [unknown] | [], Context extends T.TProperties> = Input extends [unknown] ? true : false;
export declare function ReadonlyMapping(input: [unknown] | [], context: unknown): boolean;
export type TOptionalMapping<Input extends [unknown] | [], Context extends T.TProperties> = Input extends [unknown] ? true : false;
export declare function OptionalMapping(input: [unknown] | [], context: unknown): boolean;
export type TPropertyMapping<Input extends [unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends [infer IsReadonly extends boolean, infer Key extends string, infer IsOptional extends boolean, string, infer Type extends T.TSchema] ? {
[_ in Key]: ([
IsReadonly,
IsOptional
] extends [true, true] ? T.TReadonlyOptional<Type> : [
IsReadonly,
IsOptional
] extends [true, false] ? T.TReadonly<Type> : [
IsReadonly,
IsOptional
] extends [false, true] ? T.TOptional<Type> : Type);
} : never;
export declare function PropertyMapping(input: [unknown, unknown, unknown, unknown, unknown], context: unknown): {
[x: string]: T.TSchema;
};
export type TPropertyDelimiterMapping<Input extends [unknown, unknown] | [unknown], Context extends T.TProperties> = Input;
export declare function PropertyDelimiterMapping(input: [unknown, unknown] | [unknown], context: unknown): [unknown] | [unknown, unknown];
export type TPropertyListMapping<Input extends [unknown, unknown], Context extends T.TProperties> = TDelimited<Input>;
export declare function PropertyListMapping(input: [unknown, unknown], context: unknown): unknown[];
type TObjectMappingReduce<PropertiesList extends T.TProperties[], Result extends T.TProperties = {}> = (PropertiesList extends [infer Left extends T.TProperties, ...infer Right extends T.TProperties[]] ? TObjectMappingReduce<Right, Result & Left> : {
[Key in keyof Result]: Result[Key];
});
export type TObjectMapping<Input extends [unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['{', infer PropertyList extends T.TProperties[], '}'] ? T.TObject<TObjectMappingReduce<PropertyList>> : never;
export declare function ObjectMapping(input: [unknown, unknown, unknown], context: unknown): T.TObject<T.TProperties>;
export type TElementListMapping<Input extends [unknown, unknown], Context extends T.TProperties> = TDelimited<Input>;
export declare function ElementListMapping(input: [unknown, unknown], context: unknown): unknown[];
export type TTupleMapping<Input extends [unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['[', infer Types extends T.TSchema[], ']'] ? T.TTuple<Types> : never;
export declare function TupleMapping(input: [unknown, unknown, unknown], context: unknown): T.TTuple<T.TSchema[]>;
export type TParameterMapping<Input extends [unknown, unknown, unknown], Context extends T.TProperties> = Input extends [string, ':', infer Type extends T.TSchema] ? Type : never;
export declare function ParameterMapping(input: [unknown, unknown, unknown], context: unknown): T.TSchema;
export type TParameterListMapping<Input extends [unknown, unknown], Context extends T.TProperties> = TDelimited<Input>;
export declare function ParameterListMapping(input: [unknown, unknown], context: unknown): unknown[];
export type TFunctionMapping<Input extends [unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['(', infer ParameterList extends T.TSchema[], ')', '=>', infer ReturnType extends T.TSchema] ? T.TFunction<ParameterList, ReturnType> : never;
export declare function FunctionMapping(input: [unknown, unknown, unknown, unknown, unknown], context: unknown): T.TFunction<T.TSchema[], T.TSchema>;
export type TConstructorMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['new', '(', infer ParameterList extends T.TSchema[], ')', '=>', infer InstanceType extends T.TSchema] ? T.TConstructor<ParameterList, InstanceType> : never;
export declare function ConstructorMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TConstructor<T.TSchema[], T.TSchema>;
export type TMappedMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['{', '[', infer _Key extends string, 'in', infer _Right extends T.TSchema, ']', ':', infer _Type extends T.TSchema, '}'] ? T.TLiteral<'Mapped types not supported'> : never;
export declare function MappedMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TLiteral<"Mapped types not supported">;
export type TAsyncIteratorMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['AsyncIterator', '<', infer Type extends T.TSchema, '>'] ? T.TAsyncIterator<Type> : never;
export declare function AsyncIteratorMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TAsyncIterator<T.TSchema>;
export type TIteratorMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Iterator', '<', infer Type extends T.TSchema, '>'] ? T.TIterator<Type> : never;
export declare function IteratorMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TIterator<T.TSchema>;
export type TArgumentMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Argument', '<', infer Type extends T.TSchema, '>'] ? Type extends T.TLiteral<infer Index extends number> ? T.TArgument<Index> : T.TNever : never;
export declare function ArgumentMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TNever | T.TArgument<number>;
export type TAwaitedMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Awaited', '<', infer Type extends T.TSchema, '>'] ? T.TAwaited<Type> : never;
export declare function AwaitedMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TArrayMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Array', '<', infer Type extends T.TSchema, '>'] ? T.TArray<Type> : never;
export declare function ArrayMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TArray<T.TSchema>;
export type TRecordMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Record', '<', infer Key extends T.TSchema, ',', infer Type extends T.TSchema, '>'] ? T.TRecordOrObject<Key, Type> : never;
export declare function RecordMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TPromiseMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Promise', '<', infer Type extends T.TSchema, '>'] ? T.TPromise<Type> : never;
export declare function PromiseMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TPromise<T.TSchema>;
export type TConstructorParametersMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['ConstructorParameters', '<', infer Type extends T.TSchema, '>'] ? T.TConstructorParameters<Type> : never;
export declare function ConstructorParametersMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TFunctionParametersMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Parameters', '<', infer Type extends T.TSchema, '>'] ? T.TParameters<Type> : never;
export declare function FunctionParametersMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TInstanceTypeMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['InstanceType', '<', infer Type extends T.TSchema, '>'] ? T.TInstanceType<Type> : never;
export declare function InstanceTypeMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TReturnTypeMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['ReturnType', '<', infer Type extends T.TSchema, '>'] ? T.TReturnType<Type> : never;
export declare function ReturnTypeMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TPartialMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Partial', '<', infer Type extends T.TSchema, '>'] ? T.TPartial<Type> : never;
export declare function PartialMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TObject<{}>;
export type TRequiredMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Required', '<', infer Type extends T.TSchema, '>'] ? T.TRequired<Type> : never;
export declare function RequiredMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TObject<{}>;
export type TPickMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Pick', '<', infer Type extends T.TSchema, ',', infer Key extends T.TSchema, '>'] ? T.TPick<Type, Key> : never;
export declare function PickMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TObject<{}>;
export type TOmitMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Omit', '<', infer Type extends T.TSchema, ',', infer Key extends T.TSchema, '>'] ? T.TOmit<Type, Key> : never;
export declare function OmitMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TObject<{}>;
export type TExcludeMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Exclude', '<', infer Type extends T.TSchema, ',', infer Key extends T.TSchema, '>'] ? T.TExclude<Type, Key> : never;
export declare function ExcludeMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TNever;
export type TExtractMapping<Input extends [unknown, unknown, unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Extract', '<', infer Type extends T.TSchema, ',', infer Key extends T.TSchema, '>'] ? T.TExtract<Type, Key> : never;
export declare function ExtractMapping(input: [unknown, unknown, unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TUppercaseMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Uppercase', '<', infer Type extends T.TSchema, '>'] ? T.TUppercase<Type> : never;
export declare function UppercaseMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TLowercaseMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Lowercase', '<', infer Type extends T.TSchema, '>'] ? T.TLowercase<Type> : never;
export declare function LowercaseMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TCapitalizeMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Capitalize', '<', infer Type extends T.TSchema, '>'] ? T.TCapitalize<Type> : never;
export declare function CapitalizeMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TUncapitalizeMapping<Input extends [unknown, unknown, unknown, unknown], Context extends T.TProperties> = Input extends ['Uncapitalize', '<', infer Type extends T.TSchema, '>'] ? T.TUncapitalize<Type> : never;
export declare function UncapitalizeMapping(input: [unknown, unknown, unknown, unknown], context: unknown): T.TSchema;
export type TDateMapping<Input extends 'Date', Context extends T.TProperties> = T.TDate;
export declare function DateMapping(input: 'Date', context: unknown): T.TDate;
export type TUint8ArrayMapping<Input extends 'Uint8Array', Context extends T.TProperties> = T.TUint8Array;
export declare function Uint8ArrayMapping(input: 'Uint8Array', context: unknown): T.TUint8Array;
export type TReferenceMapping<Input extends string, Context extends T.TProperties> = Context extends T.TProperties ? Input extends string ? TDereference<Context, Input> : never : never;
export declare function ReferenceMapping(input: string, context: unknown): T.TSchema;
export {};

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