feat(auth): implement user authentication system

This commit is contained in:
J.A.R.V.I.S. 2026-03-19 23:10:50 +00:00
parent 4847ab793a
commit 25cea4fbe8
12051 changed files with 1462377 additions and 0 deletions

21
backend/node_modules/@jest/core/LICENSE generated vendored Normal file
View file

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

3
backend/node_modules/@jest/core/README.md generated vendored Normal file
View file

@ -0,0 +1,3 @@
# @jest/core
Jest is currently working on providing a programmatic API. This is under development, and usage of this package directly is currently not supported.

View file

@ -0,0 +1,46 @@
'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

@ -0,0 +1,195 @@
'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

@ -0,0 +1,87 @@
'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;

408
backend/node_modules/@jest/core/build/SearchSource.js generated vendored Normal file
View file

@ -0,0 +1,408 @@
'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

@ -0,0 +1,238 @@
'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

@ -0,0 +1,39 @@
'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

@ -0,0 +1,39 @@
'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;

463
backend/node_modules/@jest/core/build/TestScheduler.js generated vendored Normal file
View file

@ -0,0 +1,463 @@
'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));
};

417
backend/node_modules/@jest/core/build/cli/index.js generated vendored Normal file
View file

@ -0,0 +1,417 @@
'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();
};

266
backend/node_modules/@jest/core/build/collectHandles.js generated vendored Normal file
View file

@ -0,0 +1,266 @@
'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

@ -0,0 +1,65 @@
'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

@ -0,0 +1,40 @@
'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

@ -0,0 +1,80 @@
'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

@ -0,0 +1,43 @@
'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

@ -0,0 +1,26 @@
'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

@ -0,0 +1,48 @@
'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

@ -0,0 +1,91 @@
'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

@ -0,0 +1,64 @@
'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

@ -0,0 +1,16 @@
'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

@ -0,0 +1,49 @@
'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

@ -0,0 +1,71 @@
'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}`;
}

118
backend/node_modules/@jest/core/build/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,118 @@
/**
* 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 {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';
export declare function createTestScheduler(
globalConfig: Config.GlobalConfig,
context: TestSchedulerContext,
): Promise<TestScheduler>;
declare type Filter = (testPaths: Array<string>) => Promise<{
filtered: Array<FilterResult>;
}>;
declare type FilterResult = {
test: string;
message: string;
};
export declare function getVersion(): string;
declare type ReporterConstructor = new (
globalConfig: Config.GlobalConfig,
reporterConfig: Record<string, unknown>,
reporterContext: ReporterContext,
) => BaseReporter;
export declare function runCLI(
argv: Config.Argv,
projects: Array<string>,
): Promise<{
results: AggregatedResult;
globalConfig: Config.GlobalConfig;
}>;
declare type SearchResult = {
noSCM?: boolean;
stats?: Stats;
collectCoverageFrom?: Set<string>;
tests: Array<Test>;
total?: number;
};
export 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(testPathPattern: string): 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,
changedFiles?: ChangedFiles,
filter?: Filter,
): Promise<SearchResult>;
findRelatedSourcesFromTestsInChangedFiles(
changedFilesInfo: ChangedFiles,
): Promise<Array<string>>;
}
declare type Stats = {
roots: number;
testMatch: number;
testPathIgnorePatterns: number;
testRegex: number;
testPathPattern?: number;
};
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;
}
declare type TestSchedulerContext = ReporterContext & TestRunnerContext;
export {};

36
backend/node_modules/@jest/core/build/index.js generated vendored Normal file
View file

@ -0,0 +1,36 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
Object.defineProperty(exports, 'SearchSource', {
enumerable: true,
get: function () {
return _SearchSource.default;
}
});
Object.defineProperty(exports, 'createTestScheduler', {
enumerable: true,
get: function () {
return _TestScheduler.createTestScheduler;
}
});
Object.defineProperty(exports, 'getVersion', {
enumerable: true,
get: function () {
return _version.default;
}
});
Object.defineProperty(exports, 'runCLI', {
enumerable: true,
get: function () {
return _cli.runCLI;
}
});
var _SearchSource = _interopRequireDefault(require('./SearchSource'));
var _TestScheduler = require('./TestScheduler');
var _cli = require('./cli');
var _version = _interopRequireDefault(require('./version'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}

View file

@ -0,0 +1,52 @@
'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

@ -0,0 +1,31 @@
'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

@ -0,0 +1,65 @@
'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

@ -0,0 +1,26 @@
'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

@ -0,0 +1,24 @@
'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

@ -0,0 +1,95 @@
'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

@ -0,0 +1,56 @@
'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

@ -0,0 +1,96 @@
'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;

42
backend/node_modules/@jest/core/build/plugins/Quit.js generated vendored Normal file
View file

@ -0,0 +1,42 @@
'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

@ -0,0 +1,70 @@
'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

@ -0,0 +1,70 @@
'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

@ -0,0 +1,51 @@
'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

@ -0,0 +1,99 @@
'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;

133
backend/node_modules/@jest/core/build/runGlobalHook.js generated vendored Normal file
View file

@ -0,0 +1,133 @@
'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
})}`
);
}
}
}
}

391
backend/node_modules/@jest/core/build/runJest.js generated vendored Normal file
View file

@ -0,0 +1,391 @@
'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

@ -0,0 +1,57 @@
'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))
);
}

1
backend/node_modules/@jest/core/build/types.js generated vendored Normal file
View file

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

18
backend/node_modules/@jest/core/build/version.js generated vendored Normal file
View file

@ -0,0 +1,18 @@
'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;
}

666
backend/node_modules/@jest/core/build/watch.js generated vendored Normal file
View file

@ -0,0 +1,666 @@
'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 @@
../semver/bin/semver.js

View file

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

View file

@ -0,0 +1,3 @@
# `@jest/schemas`
Experimental and currently incomplete module for JSON schemas for [Jest's](https://jestjs.io/) configuration.

View file

@ -0,0 +1,63 @@
/**
* 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} from '@sinclair/typebox';
import {TBoolean} from '@sinclair/typebox';
import {TNull} from '@sinclair/typebox';
import {TNumber} from '@sinclair/typebox';
import {TObject} from '@sinclair/typebox';
import {TReadonlyOptional} from '@sinclair/typebox';
import {TString} from '@sinclair/typebox';
declare const RawSnapshotFormat: TObject<{
callToJSON: TReadonlyOptional<TBoolean>;
compareKeys: TReadonlyOptional<TNull>;
escapeRegex: TReadonlyOptional<TBoolean>;
escapeString: TReadonlyOptional<TBoolean>;
highlight: TReadonlyOptional<TBoolean>;
indent: TReadonlyOptional<TNumber>;
maxDepth: TReadonlyOptional<TNumber>;
maxWidth: TReadonlyOptional<TNumber>;
min: TReadonlyOptional<TBoolean>;
printBasicPrototype: TReadonlyOptional<TBoolean>;
printFunctionName: TReadonlyOptional<TBoolean>;
theme: TReadonlyOptional<
TObject<{
comment: TReadonlyOptional<TString<string>>;
content: TReadonlyOptional<TString<string>>;
prop: TReadonlyOptional<TString<string>>;
tag: TReadonlyOptional<TString<string>>;
value: TReadonlyOptional<TString<string>>;
}>
>;
}>;
export declare const SnapshotFormat: TObject<{
callToJSON: TReadonlyOptional<TBoolean>;
compareKeys: TReadonlyOptional<TNull>;
escapeRegex: TReadonlyOptional<TBoolean>;
escapeString: TReadonlyOptional<TBoolean>;
highlight: TReadonlyOptional<TBoolean>;
indent: TReadonlyOptional<TNumber>;
maxDepth: TReadonlyOptional<TNumber>;
maxWidth: TReadonlyOptional<TNumber>;
min: TReadonlyOptional<TBoolean>;
printBasicPrototype: TReadonlyOptional<TBoolean>;
printFunctionName: TReadonlyOptional<TBoolean>;
theme: TReadonlyOptional<
TObject<{
comment: TReadonlyOptional<TString<string>>;
content: TReadonlyOptional<TString<string>>;
prop: TReadonlyOptional<TString<string>>;
tag: TReadonlyOptional<TString<string>>;
value: TReadonlyOptional<TString<string>>;
}>
>;
}>;
export declare type SnapshotFormat = Static<typeof RawSnapshotFormat>;
export {};

View file

@ -0,0 +1,60 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.SnapshotFormat = 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.
*/
const RawSnapshotFormat = _typebox().Type.Partial(
_typebox().Type.Object({
callToJSON: _typebox().Type.Readonly(_typebox().Type.Boolean()),
compareKeys: _typebox().Type.Readonly(_typebox().Type.Null()),
escapeRegex: _typebox().Type.Readonly(_typebox().Type.Boolean()),
escapeString: _typebox().Type.Readonly(_typebox().Type.Boolean()),
highlight: _typebox().Type.Readonly(_typebox().Type.Boolean()),
indent: _typebox().Type.Readonly(
_typebox().Type.Number({
minimum: 0
})
),
maxDepth: _typebox().Type.Readonly(
_typebox().Type.Number({
minimum: 0
})
),
maxWidth: _typebox().Type.Readonly(
_typebox().Type.Number({
minimum: 0
})
),
min: _typebox().Type.Readonly(_typebox().Type.Boolean()),
printBasicPrototype: _typebox().Type.Readonly(_typebox().Type.Boolean()),
printFunctionName: _typebox().Type.Readonly(_typebox().Type.Boolean()),
theme: _typebox().Type.Readonly(
_typebox().Type.Partial(
_typebox().Type.Object({
comment: _typebox().Type.Readonly(_typebox().Type.String()),
content: _typebox().Type.Readonly(_typebox().Type.String()),
prop: _typebox().Type.Readonly(_typebox().Type.String()),
tag: _typebox().Type.Readonly(_typebox().Type.String()),
value: _typebox().Type.Readonly(_typebox().Type.String())
})
)
)
})
);
const SnapshotFormat = _typebox().Type.Strict(RawSnapshotFormat);
exports.SnapshotFormat = SnapshotFormat;

View file

@ -0,0 +1,29 @@
{
"name": "@jest/schemas",
"version": "29.6.3",
"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",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@sinclair/typebox": "^0.27.8"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "fb7d95c8af6e0d65a8b65348433d8a0ea0725b5b"
}

View file

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

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,76 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = handlePotentialSyntaxError;
exports.enhanceUnexpectedTokenMessage = enhanceUnexpectedTokenMessage;
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.
*/
const DOT = ' \u2022 ';
function handlePotentialSyntaxError(e) {
if (e.codeFrame != null) {
e.stack = `${e.message}\n${e.codeFrame}`;
}
if (
// `instanceof` might come from the wrong context
e.name === 'SyntaxError' &&
!e.message.includes(' expected')
) {
throw enhanceUnexpectedTokenMessage(e);
}
return e;
}
function enhanceUnexpectedTokenMessage(e) {
e.stack = `${_chalk().default.bold.red(
'Jest encountered an unexpected token'
)}
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
${DOT}If you are trying to use ECMAScript Modules, see ${_chalk().default.underline(
'https://jestjs.io/docs/ecmascript-modules'
)} for how to enable it.
${DOT}If you are trying to use TypeScript, see ${_chalk().default.underline(
'https://jestjs.io/docs/getting-started#using-typescript'
)}
${DOT}To have some of your "node_modules" files transformed, you can specify a custom ${_chalk().default.bold(
'"transformIgnorePatterns"'
)} in your config.
${DOT}If you need a custom transformation specify a ${_chalk().default.bold(
'"transform"'
)} option in your config.
${DOT}If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the ${_chalk().default.bold(
'"moduleNameMapper"'
)} config option.
You'll find more details and examples of these config options in the docs:
${_chalk().default.cyan('https://jestjs.io/docs/configuration')}
For information about custom transformations, see:
${_chalk().default.cyan('https://jestjs.io/docs/code-transformation')}
${_chalk().default.bold.red('Details:')}
${e.stack ?? ''}`.trimRight();
return e;
}

View file

@ -0,0 +1,240 @@
/**
* 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 type {Config} from '@jest/types';
import type {EncodedSourceMap} from '@jridgewell/trace-mapping';
import type {TransformTypes} from '@jest/types';
export declare interface AsyncTransformer<TransformerConfig = unknown> {
/**
* Indicates if the transformer is capable of instrumenting the code for code coverage.
*
* If V8 coverage is _not_ active, and this is `true`, Jest will assume the code is instrumented.
* If V8 coverage is _not_ active, and this is `false`. Jest will instrument the code returned by this transformer using Babel.
*/
canInstrument?: boolean;
getCacheKey?: (
sourceText: string,
sourcePath: string,
options: TransformOptions<TransformerConfig>,
) => string;
getCacheKeyAsync?: (
sourceText: string,
sourcePath: string,
options: TransformOptions<TransformerConfig>,
) => Promise<string>;
process?: (
sourceText: string,
sourcePath: string,
options: TransformOptions<TransformerConfig>,
) => TransformedSource;
processAsync: (
sourceText: string,
sourcePath: string,
options: TransformOptions<TransformerConfig>,
) => Promise<TransformedSource>;
}
export declare interface CallerTransformOptions {
supportsDynamicImport: boolean;
supportsExportNamespaceFrom: boolean;
supportsStaticESM: boolean;
supportsTopLevelAwait: boolean;
}
export declare function createScriptTransformer(
config: Config.ProjectConfig,
cacheFS?: StringMap,
): Promise<ScriptTransformer>;
export declare function createTranspilingRequire(
config: Config.ProjectConfig,
): Promise<
<TModuleType = unknown>(
resolverPath: string,
applyInteropRequireDefault?: boolean,
) => Promise<TModuleType>
>;
declare interface ErrorWithCodeFrame extends Error {
codeFrame?: string;
}
declare interface FixedRawSourceMap extends Omit<EncodedSourceMap, 'version'> {
version: number;
}
export declare function handlePotentialSyntaxError(
e: ErrorWithCodeFrame,
): ErrorWithCodeFrame;
declare interface ReducedTransformOptions extends CallerTransformOptions {
instrument: boolean;
}
declare interface RequireAndTranspileModuleOptions
extends ReducedTransformOptions {
applyInteropRequireDefault: boolean;
}
export declare type ScriptTransformer = ScriptTransformer_2;
declare class ScriptTransformer_2 {
private readonly _config;
private readonly _cacheFS;
private readonly _cache;
private readonly _transformCache;
private _transformsAreLoaded;
constructor(_config: Config.ProjectConfig, _cacheFS: StringMap);
private _buildCacheKeyFromFileInfo;
private _buildTransformCacheKey;
private _getCacheKey;
private _getCacheKeyAsync;
private _createCachedFilename;
private _getFileCachePath;
private _getFileCachePathAsync;
private _getTransformPatternAndPath;
private _getTransformPath;
loadTransformers(): Promise<void>;
private _getTransformer;
private _instrumentFile;
private _buildTransformResult;
transformSource(
filepath: string,
content: string,
options: ReducedTransformOptions,
): TransformResult;
transformSourceAsync(
filepath: string,
content: string,
options: ReducedTransformOptions,
): Promise<TransformResult>;
private _transformAndBuildScriptAsync;
private _transformAndBuildScript;
transformAsync(
filename: string,
options: TransformationOptions,
fileSource?: string,
): Promise<TransformResult>;
transform(
filename: string,
options: TransformationOptions,
fileSource?: string,
): TransformResult;
transformJson(
filename: string,
options: TransformationOptions,
fileSource: string,
): string;
requireAndTranspileModule<ModuleType = unknown>(
moduleName: string,
callback?: (module: ModuleType) => void | Promise<void>,
options?: RequireAndTranspileModuleOptions,
): Promise<ModuleType>;
shouldTransform(filename: string): boolean;
}
export declare function shouldInstrument(
filename: string,
options: ShouldInstrumentOptions,
config: Config.ProjectConfig,
loadedFilenames?: Array<string>,
): boolean;
export declare interface ShouldInstrumentOptions
extends Pick<
Config.GlobalConfig,
'collectCoverage' | 'collectCoverageFrom' | 'coverageProvider'
> {
changedFiles?: Set<string>;
sourcesRelatedToTestsInChangedFiles?: Set<string>;
}
declare type StringMap = Map<string, string>;
export declare interface SyncTransformer<TransformerConfig = unknown> {
/**
* Indicates if the transformer is capable of instrumenting the code for code coverage.
*
* If V8 coverage is _not_ active, and this is `true`, Jest will assume the code is instrumented.
* If V8 coverage is _not_ active, and this is `false`. Jest will instrument the code returned by this transformer using Babel.
*/
canInstrument?: boolean;
getCacheKey?: (
sourceText: string,
sourcePath: string,
options: TransformOptions<TransformerConfig>,
) => string;
getCacheKeyAsync?: (
sourceText: string,
sourcePath: string,
options: TransformOptions<TransformerConfig>,
) => Promise<string>;
process: (
sourceText: string,
sourcePath: string,
options: TransformOptions<TransformerConfig>,
) => TransformedSource;
processAsync?: (
sourceText: string,
sourcePath: string,
options: TransformOptions<TransformerConfig>,
) => Promise<TransformedSource>;
}
export declare interface TransformationOptions
extends ShouldInstrumentOptions,
CallerTransformOptions {
isInternalModule?: boolean;
}
export declare type TransformedSource = {
code: string;
map?: FixedRawSourceMap | string | null;
};
/**
* We have both sync (`process`) and async (`processAsync`) code transformation, which both can be provided.
* `require` will always use `process`, and `import` will use `processAsync` if it exists, otherwise fall back to `process`.
* Meaning, if you use `import` exclusively you do not need `process`, but in most cases supplying both makes sense:
* Jest transpiles on demand rather than ahead of time, so the sync one needs to exist.
*
* For more info on the sync vs async model, see https://jestjs.io/docs/code-transformation#writing-custom-transformers
*/
declare type Transformer_2<TransformerConfig = unknown> =
| SyncTransformer<TransformerConfig>
| AsyncTransformer<TransformerConfig>;
export {Transformer_2 as Transformer};
export declare type TransformerCreator<
X extends Transformer_2<TransformerConfig>,
TransformerConfig = unknown,
> = (transformerConfig?: TransformerConfig) => X | Promise<X>;
/**
* Instead of having your custom transformer implement the Transformer interface
* directly, you can choose to export a factory function to dynamically create
* transformers. This is to allow having a transformer config in your jest config.
*/
export declare type TransformerFactory<X extends Transformer_2> = {
createTransformer: TransformerCreator<X>;
};
export declare interface TransformOptions<TransformerConfig = unknown>
extends ReducedTransformOptions {
/** Cached file system which is used by `jest-runtime` to improve performance. */
cacheFS: StringMap;
/** Jest configuration of currently running project. */
config: Config.ProjectConfig;
/** Stringified version of the `config` - useful in cache busting. */
configString: string;
/** Transformer configuration passed through `transform` option by the user. */
transformerConfig: TransformerConfig;
}
export declare type TransformResult = TransformTypes.TransformResult;
export {};

View file

@ -0,0 +1,37 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
Object.defineProperty(exports, 'createScriptTransformer', {
enumerable: true,
get: function () {
return _ScriptTransformer.createScriptTransformer;
}
});
Object.defineProperty(exports, 'createTranspilingRequire', {
enumerable: true,
get: function () {
return _ScriptTransformer.createTranspilingRequire;
}
});
Object.defineProperty(exports, 'handlePotentialSyntaxError', {
enumerable: true,
get: function () {
return _enhanceUnexpectedTokenMessage.default;
}
});
Object.defineProperty(exports, 'shouldInstrument', {
enumerable: true,
get: function () {
return _shouldInstrument.default;
}
});
var _ScriptTransformer = require('./ScriptTransformer');
var _shouldInstrument = _interopRequireDefault(require('./shouldInstrument'));
var _enhanceUnexpectedTokenMessage = _interopRequireDefault(
require('./enhanceUnexpectedTokenMessage')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}

View file

@ -0,0 +1,94 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.makeInvalidTransformerError =
exports.makeInvalidSyncTransformerError =
exports.makeInvalidSourceMapWarning =
exports.makeInvalidReturnValueError =
void 0;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _slash() {
const data = _interopRequireDefault(require('slash'));
_slash = 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 BULLET = '\u25cf ';
const DOCUMENTATION_NOTE = ` ${_chalk().default.bold(
'Code Transformation Documentation:'
)}
https://jestjs.io/docs/code-transformation
`;
const UPGRADE_NOTE = ` ${_chalk().default.bold(
'This error may be caused by a breaking change in Jest 28:'
)}
https://jestjs.io/docs/28.x/upgrading-to-jest28#transformer
`;
const makeInvalidReturnValueError = transformPath =>
_chalk().default.red(
[
_chalk().default.bold(`${BULLET}Invalid return value:`),
' `process()` or/and `processAsync()` method of code transformer found at ',
` "${(0, _slash().default)(transformPath)}" `,
' should return an object or a Promise resolving to an object. The object ',
' must have `code` property with a string of processed code.',
''
].join('\n') +
UPGRADE_NOTE +
DOCUMENTATION_NOTE
);
exports.makeInvalidReturnValueError = makeInvalidReturnValueError;
const makeInvalidSourceMapWarning = (filename, transformPath) =>
_chalk().default.yellow(
[
_chalk().default.bold(`${BULLET}Invalid source map:`),
` The source map for "${(0, _slash().default)(
filename
)}" returned by "${(0, _slash().default)(transformPath)}" is invalid.`,
' Proceeding without source mapping for that file.'
].join('\n')
);
exports.makeInvalidSourceMapWarning = makeInvalidSourceMapWarning;
const makeInvalidSyncTransformerError = transformPath =>
_chalk().default.red(
[
_chalk().default.bold(`${BULLET}Invalid synchronous transformer module:`),
` "${(0, _slash().default)(
transformPath
)}" specified in the "transform" object of Jest configuration`,
' must export a `process` function.',
''
].join('\n') + DOCUMENTATION_NOTE
);
exports.makeInvalidSyncTransformerError = makeInvalidSyncTransformerError;
const makeInvalidTransformerError = transformPath =>
_chalk().default.red(
[
_chalk().default.bold(`${BULLET}Invalid transformer module:`),
` "${(0, _slash().default)(
transformPath
)}" specified in the "transform" object of Jest configuration`,
' must export a `process` or `processAsync` or `createTransformer` function.',
''
].join('\n') + DOCUMENTATION_NOTE
);
exports.makeInvalidTransformerError = makeInvalidTransformerError;

View file

@ -0,0 +1,177 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = shouldInstrument;
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 _jestRegexUtil() {
const data = require('jest-regex-util');
_jestRegexUtil = 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 MOCKS_PATTERN = new RegExp(
(0, _jestRegexUtil().escapePathForRegex)(
`${path().sep}__mocks__${path().sep}`
)
);
const cachedRegexes = new Map();
const getRegex = regexStr => {
if (!cachedRegexes.has(regexStr)) {
cachedRegexes.set(regexStr, new RegExp(regexStr));
}
const regex = cachedRegexes.get(regexStr);
// prevent stateful regexes from breaking, just in case
regex.lastIndex = 0;
return regex;
};
function shouldInstrument(filename, options, config, loadedFilenames) {
if (!options.collectCoverage) {
return false;
}
if (
config.forceCoverageMatch.length &&
_micromatch().default.any(filename, config.forceCoverageMatch)
) {
return true;
}
if (
!config.testPathIgnorePatterns.some(pattern =>
getRegex(pattern).test(filename)
)
) {
if (config.testRegex.some(regex => new RegExp(regex).test(filename))) {
return false;
}
if (
(0, _jestUtil().globsToMatcher)(config.testMatch)(
(0, _jestUtil().replacePathSepForGlob)(filename)
)
) {
return false;
}
}
if (
options.collectCoverageFrom.length === 0 &&
loadedFilenames != null &&
!loadedFilenames.includes(filename)
) {
return false;
}
if (
// still cover if `only` is specified
options.collectCoverageFrom.length &&
!(0, _jestUtil().globsToMatcher)(options.collectCoverageFrom)(
(0, _jestUtil().replacePathSepForGlob)(
path().relative(config.rootDir, filename)
)
)
) {
return false;
}
if (
config.coveragePathIgnorePatterns.some(pattern => !!filename.match(pattern))
) {
return false;
}
if (config.globalSetup === filename) {
return false;
}
if (config.globalTeardown === filename) {
return false;
}
if (config.setupFiles.includes(filename)) {
return false;
}
if (config.setupFilesAfterEnv.includes(filename)) {
return false;
}
if (MOCKS_PATTERN.test(filename)) {
return false;
}
if (options.changedFiles && !options.changedFiles.has(filename)) {
if (!options.sourcesRelatedToTestsInChangedFiles) {
return false;
}
if (!options.sourcesRelatedToTestsInChangedFiles.has(filename)) {
return false;
}
}
if (filename.endsWith('.json')) {
return false;
}
return true;
}

View file

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

View file

@ -0,0 +1,52 @@
{
"name": "@jest/transform",
"version": "29.7.0",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-transform"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@babel/core": "^7.11.6",
"@jest/types": "^29.6.3",
"@jridgewell/trace-mapping": "^0.3.18",
"babel-plugin-istanbul": "^6.1.1",
"chalk": "^4.0.0",
"convert-source-map": "^2.0.0",
"fast-json-stable-stringify": "^2.1.0",
"graceful-fs": "^4.2.9",
"jest-haste-map": "^29.7.0",
"jest-regex-util": "^29.6.3",
"jest-util": "^29.7.0",
"micromatch": "^4.0.4",
"pirates": "^4.0.4",
"slash": "^3.0.0",
"write-file-atomic": "^4.0.2"
},
"devDependencies": {
"@jest/test-utils": "^29.7.0",
"@types/babel__core": "^7.1.14",
"@types/convert-source-map": "^2.0.0",
"@types/graceful-fs": "^4.1.3",
"@types/micromatch": "^4.0.1",
"@types/write-file-atomic": "^4.0.0",
"dedent": "^1.0.0"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "4e56991693da7cd4c3730dc3579a1dd1403ee630"
}

View file

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

View file

@ -0,0 +1,30 @@
# @jest/types
This package contains shared types of Jest's packages.
If you are looking for types of [Jest globals](https://jestjs.io/docs/api), you can import them from `@jest/globals` package:
```ts
import {describe, expect, it} from '@jest/globals';
describe('my tests', () => {
it('works', () => {
expect(1).toBe(1);
});
});
```
If you prefer to omit imports, a similar result can be achieved installing the [@types/jest](https://npmjs.com/package/@types/jest) package. Note that this is a third party library maintained at [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest) and may not cover the latest Jest features.
Another use-case for `@types/jest` is a typed Jest config as those types are not provided by Jest out of the box:
```ts
// jest.config.ts
import {Config} from '@jest/types';
const config: Config.InitialOptions = {
// some typed config
};
export default config;
```

View file

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

View file

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

View file

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

View file

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

View file

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

File diff suppressed because it is too large Load diff

View file

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

View file

@ -0,0 +1,38 @@
{
"name": "@jest/types",
"version": "29.6.3",
"repository": {
"type": "git",
"url": "https://github.com/jestjs/jest.git",
"directory": "packages/jest-types"
},
"engines": {
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
},
"license": "MIT",
"main": "./build/index.js",
"types": "./build/index.d.ts",
"exports": {
".": {
"types": "./build/index.d.ts",
"default": "./build/index.js"
},
"./package.json": "./package.json"
},
"dependencies": {
"@jest/schemas": "^29.6.3",
"@types/istanbul-lib-coverage": "^2.0.0",
"@types/istanbul-reports": "^3.0.0",
"@types/node": "*",
"@types/yargs": "^17.0.8",
"chalk": "^4.0.0"
},
"devDependencies": {
"@tsd/typescript": "^5.0.4",
"tsd-lite": "^0.7.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "fb7d95c8af6e0d65a8b65348433d8a0ea0725b5b"
}

View file

@ -0,0 +1,35 @@
import * as Types from '../typebox';
import { ValueErrorIterator } from '../errors/index';
export type CheckFunction = (value: unknown) => boolean;
export declare class TypeCheck<T extends Types.TSchema> {
private readonly schema;
private readonly references;
private readonly checkFunc;
private readonly code;
constructor(schema: T, references: Types.TSchema[], checkFunc: CheckFunction, code: string);
/** Returns the generated assertion code used to validate this type. */
Code(): string;
/** 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 Types.Static<T>;
}
export declare class TypeCompilerUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class TypeCompilerDereferenceError extends Error {
readonly schema: Types.TRef;
constructor(schema: Types.TRef);
}
export declare class TypeCompilerTypeGuardError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
/** Compiles Types for Runtime Type Checking */
export declare namespace TypeCompiler {
/** Returns the generated assertion code used to validate this type. */
function Code<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): string;
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
function Compile<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): TypeCheck<T>;
}

View file

@ -0,0 +1,577 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/compiler
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeCompiler = exports.TypeCompilerTypeGuardError = exports.TypeCompilerDereferenceError = exports.TypeCompilerUnknownTypeError = exports.TypeCheck = void 0;
const Types = require("../typebox");
const index_1 = require("../errors/index");
const index_2 = require("../system/index");
const hash_1 = require("../value/hash");
// -------------------------------------------------------------------
// TypeCheck
// -------------------------------------------------------------------
class TypeCheck {
constructor(schema, references, checkFunc, code) {
this.schema = schema;
this.references = references;
this.checkFunc = checkFunc;
this.code = code;
}
/** Returns the generated assertion code used to validate this type. */
Code() {
return this.code;
}
/** Returns an iterator for each error in this value. */
Errors(value) {
return index_1.ValueErrors.Errors(this.schema, this.references, value);
}
/** Returns true if the value matches the compiled type. */
Check(value) {
return this.checkFunc(value);
}
}
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 = {}));
// -------------------------------------------------------------------
// TypeCompiler
// -------------------------------------------------------------------
class TypeCompilerUnknownTypeError extends Error {
constructor(schema) {
super('TypeCompiler: Unknown type');
this.schema = schema;
}
}
exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
class TypeCompilerDereferenceError extends Error {
constructor(schema) {
super(`TypeCompiler: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.TypeCompilerDereferenceError = TypeCompilerDereferenceError;
class TypeCompilerTypeGuardError extends Error {
constructor(schema) {
super('TypeCompiler: Preflight validation check failed to guard for the given schema');
this.schema = schema;
}
}
exports.TypeCompilerTypeGuardError = TypeCompilerTypeGuardError;
/** Compiles Types for Runtime Type Checking */
var TypeCompiler;
(function (TypeCompiler) {
// -------------------------------------------------------------------
// Guards
// -------------------------------------------------------------------
function IsBigInt(value) {
return typeof value === 'bigint';
}
function IsNumber(value) {
return typeof value === 'number' && globalThis.Number.isFinite(value);
}
function IsString(value) {
return typeof value === 'string';
}
// -------------------------------------------------------------------
// Polices
// -------------------------------------------------------------------
function IsExactOptionalProperty(value, key, expression) {
return index_2.TypeSystem.ExactOptionalPropertyTypes ? `('${key}' in ${value} ? ${expression} : true)` : `(${MemberExpression.Encode(value, key)} !== undefined ? ${expression} : true)`;
}
function IsObjectCheck(value) {
return !index_2.TypeSystem.AllowArrayObjects ? `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))` : `(typeof ${value} === 'object' && ${value} !== null)`;
}
function IsRecordCheck(value) {
return !index_2.TypeSystem.AllowArrayObjects
? `(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))`;
}
function IsNumberCheck(value) {
return !index_2.TypeSystem.AllowNaN ? `(typeof ${value} === 'number' && Number.isFinite(${value}))` : `typeof ${value} === 'number'`;
}
function IsVoidCheck(value) {
return index_2.TypeSystem.AllowVoidNull ? `(${value} === undefined || ${value} === null)` : `${value} === undefined`;
}
// -------------------------------------------------------------------
// Types
// -------------------------------------------------------------------
function* Any(schema, references, value) {
yield 'true';
}
function* Array(schema, references, value) {
const expression = CreateExpression(schema.items, references, 'value');
yield `Array.isArray(${value}) && ${value}.every(value => ${expression})`;
if (IsNumber(schema.minItems))
yield `${value}.length >= ${schema.minItems}`;
if (IsNumber(schema.maxItems))
yield `${value}.length <= ${schema.maxItems}`;
if (schema.uniqueItems === true)
yield `((function() { const set = new Set(); for(const element of ${value}) { const hashed = hash(element); if(set.has(hashed)) { return false } else { set.add(hashed) } } return true })())`;
}
function* BigInt(schema, references, value) {
yield `(typeof ${value} === 'bigint')`;
if (IsBigInt(schema.multipleOf))
yield `(${value} % BigInt(${schema.multipleOf})) === 0`;
if (IsBigInt(schema.exclusiveMinimum))
yield `${value} > BigInt(${schema.exclusiveMinimum})`;
if (IsBigInt(schema.exclusiveMaximum))
yield `${value} < BigInt(${schema.exclusiveMaximum})`;
if (IsBigInt(schema.minimum))
yield `${value} >= BigInt(${schema.minimum})`;
if (IsBigInt(schema.maximum))
yield `${value} <= BigInt(${schema.maximum})`;
}
function* Boolean(schema, references, value) {
yield `typeof ${value} === 'boolean'`;
}
function* Constructor(schema, references, value) {
yield* Visit(schema.returns, references, `${value}.prototype`);
}
function* Date(schema, references, value) {
yield `(${value} instanceof Date) && Number.isFinite(${value}.getTime())`;
if (IsNumber(schema.exclusiveMinimumTimestamp))
yield `${value}.getTime() > ${schema.exclusiveMinimumTimestamp}`;
if (IsNumber(schema.exclusiveMaximumTimestamp))
yield `${value}.getTime() < ${schema.exclusiveMaximumTimestamp}`;
if (IsNumber(schema.minimumTimestamp))
yield `${value}.getTime() >= ${schema.minimumTimestamp}`;
if (IsNumber(schema.maximumTimestamp))
yield `${value}.getTime() <= ${schema.maximumTimestamp}`;
}
function* Function(schema, references, value) {
yield `typeof ${value} === 'function'`;
}
function* Integer(schema, references, value) {
yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
if (IsNumber(schema.multipleOf))
yield `(${value} % ${schema.multipleOf}) === 0`;
if (IsNumber(schema.exclusiveMinimum))
yield `${value} > ${schema.exclusiveMinimum}`;
if (IsNumber(schema.exclusiveMaximum))
yield `${value} < ${schema.exclusiveMaximum}`;
if (IsNumber(schema.minimum))
yield `${value} >= ${schema.minimum}`;
if (IsNumber(schema.maximum))
yield `${value} <= ${schema.maximum}`;
}
function* Intersect(schema, references, value) {
if (schema.unevaluatedProperties === undefined) {
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
yield `${expressions.join(' && ')}`;
}
else if (schema.unevaluatedProperties === false) {
// prettier-ignore
const schemaKeys = Types.KeyResolver.Resolve(schema).map((key) => `'${key}'`).join(', ');
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
const expression1 = `Object.getOwnPropertyNames(${value}).every(key => [${schemaKeys}].includes(key))`;
yield `${expressions.join(' && ')} && ${expression1}`;
}
else if (typeof schema.unevaluatedProperties === 'object') {
// prettier-ignore
const schemaKeys = Types.KeyResolver.Resolve(schema).map((key) => `'${key}'`).join(', ');
const expressions = schema.allOf.map((schema) => CreateExpression(schema, references, value));
const expression1 = CreateExpression(schema.unevaluatedProperties, references, 'value[key]');
const expression2 = `Object.getOwnPropertyNames(${value}).every(key => [${schemaKeys}].includes(key) || ${expression1})`;
yield `${expressions.join(' && ')} && ${expression2}`;
}
}
function* Literal(schema, references, value) {
if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
yield `${value} === ${schema.const}`;
}
else {
yield `${value} === '${schema.const}'`;
}
}
function* Never(schema, references, value) {
yield `false`;
}
function* Not(schema, references, value) {
const left = CreateExpression(schema.allOf[0].not, references, value);
const right = CreateExpression(schema.allOf[1], references, value);
yield `!${left} && ${right}`;
}
function* Null(schema, references, value) {
yield `${value} === null`;
}
function* Number(schema, references, value) {
yield IsNumberCheck(value);
if (IsNumber(schema.multipleOf))
yield `(${value} % ${schema.multipleOf}) === 0`;
if (IsNumber(schema.exclusiveMinimum))
yield `${value} > ${schema.exclusiveMinimum}`;
if (IsNumber(schema.exclusiveMaximum))
yield `${value} < ${schema.exclusiveMaximum}`;
if (IsNumber(schema.minimum))
yield `${value} >= ${schema.minimum}`;
if (IsNumber(schema.maximum))
yield `${value} <= ${schema.maximum}`;
}
function* Object(schema, references, value) {
yield IsObjectCheck(value);
if (IsNumber(schema.minProperties))
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
if (IsNumber(schema.maxProperties))
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
const knownKeys = globalThis.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 (Types.ExtendsUndefined.Check(property))
yield `('${knownKey}' in ${value})`;
}
else {
const expression = CreateExpression(property, references, memberExpression);
yield 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* Promise(schema, references, value) {
yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
}
function* Record(schema, references, value) {
yield IsRecordCheck(value);
if (IsNumber(schema.minProperties))
yield `Object.getOwnPropertyNames(${value}).length >= ${schema.minProperties}`;
if (IsNumber(schema.maxProperties))
yield `Object.getOwnPropertyNames(${value}).length <= ${schema.maxProperties}`;
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const local = PushLocal(`new RegExp(/${keyPattern}/)`);
yield `(Object.getOwnPropertyNames(${value}).every(key => ${local}.test(key)))`;
const expression = CreateExpression(valueSchema, references, 'value');
yield `Object.values(${value}).every(value => ${expression})`;
}
function* Ref(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new TypeCompilerDereferenceError(schema);
const target = references[index];
// 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. Consider for refactor.
if (state_local_function_names.has(schema.$ref))
return yield `${CreateFunctionName(schema.$ref)}(${value})`;
yield* Visit(target, references, value);
}
function* String(schema, references, value) {
yield `(typeof ${value} === 'string')`;
if (IsNumber(schema.minLength))
yield `${value}.length >= ${schema.minLength}`;
if (IsNumber(schema.maxLength))
yield `${value}.length <= ${schema.maxLength}`;
if (schema.pattern !== undefined) {
const local = PushLocal(`${new RegExp(schema.pattern)};`);
yield `${local}.test(${value})`;
}
if (schema.format !== undefined) {
yield `format('${schema.format}', ${value})`;
}
}
function* Symbol(schema, references, value) {
yield `(typeof ${value} === 'symbol')`;
}
function* TemplateLiteral(schema, references, value) {
yield `(typeof ${value} === 'string')`;
const local = PushLocal(`${new RegExp(schema.pattern)};`);
yield `${local}.test(${value})`;
}
function* This(schema, references, value) {
const func = CreateFunctionName(schema.$ref);
yield `${func}(${value})`;
}
function* Tuple(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* Undefined(schema, references, value) {
yield `${value} === undefined`;
}
function* Union(schema, references, value) {
const expressions = schema.anyOf.map((schema) => CreateExpression(schema, references, value));
yield `(${expressions.join(' || ')})`;
}
function* Uint8Array(schema, references, value) {
yield `${value} instanceof Uint8Array`;
if (IsNumber(schema.maxByteLength))
yield `(${value}.length <= ${schema.maxByteLength})`;
if (IsNumber(schema.minByteLength))
yield `(${value}.length >= ${schema.minByteLength})`;
}
function* Unknown(schema, references, value) {
yield 'true';
}
function* Void(schema, references, value) {
yield IsVoidCheck(value);
}
function* UserDefined(schema, references, value) {
const schema_key = `schema_key_${state_remote_custom_types.size}`;
state_remote_custom_types.set(schema_key, schema);
yield `custom('${schema[Types.Kind]}', '${schema_key}', ${value})`;
}
function* Visit(schema, references, value) {
const references_ = IsString(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
// Reference: Referenced schemas can originate from either additional schemas
// or inline in the schema itself. Ideally the recursive path should align to
// reference path. Consider for refactor.
if (IsString(schema.$id) && !state_local_function_names.has(schema.$id)) {
state_local_function_names.add(schema.$id);
const name = CreateFunctionName(schema.$id);
const body = CreateFunction(name, schema, references, 'value');
PushFunction(body);
yield `${name}(${value})`;
return;
}
switch (schema_[Types.Kind]) {
case 'Any':
return yield* Any(schema_, references_, value);
case 'Array':
return yield* Array(schema_, references_, value);
case 'BigInt':
return yield* BigInt(schema_, references_, value);
case 'Boolean':
return yield* Boolean(schema_, references_, value);
case 'Constructor':
return yield* Constructor(schema_, references_, value);
case 'Date':
return yield* Date(schema_, references_, value);
case 'Function':
return yield* Function(schema_, references_, value);
case 'Integer':
return yield* Integer(schema_, references_, value);
case 'Intersect':
return yield* Intersect(schema_, references_, value);
case 'Literal':
return yield* Literal(schema_, references_, value);
case 'Never':
return yield* Never(schema_, references_, value);
case 'Not':
return yield* Not(schema_, references_, value);
case 'Null':
return yield* Null(schema_, references_, value);
case 'Number':
return yield* Number(schema_, references_, value);
case 'Object':
return yield* Object(schema_, references_, value);
case 'Promise':
return yield* Promise(schema_, references_, value);
case 'Record':
return yield* Record(schema_, references_, value);
case 'Ref':
return yield* Ref(schema_, references_, value);
case 'String':
return yield* String(schema_, references_, value);
case 'Symbol':
return yield* Symbol(schema_, references_, value);
case 'TemplateLiteral':
return yield* TemplateLiteral(schema_, references_, value);
case 'This':
return yield* This(schema_, references_, value);
case 'Tuple':
return yield* Tuple(schema_, references_, value);
case 'Undefined':
return yield* Undefined(schema_, references_, value);
case 'Union':
return yield* Union(schema_, references_, value);
case 'Uint8Array':
return yield* Uint8Array(schema_, references_, value);
case 'Unknown':
return yield* Unknown(schema_, references_, value);
case 'Void':
return yield* Void(schema_, references_, value);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new TypeCompilerUnknownTypeError(schema);
return yield* UserDefined(schema_, references_, value);
}
}
// -------------------------------------------------------------------
// Compiler State
// -------------------------------------------------------------------
const state_local_variables = new Set(); // local variables and functions
const state_local_function_names = new Set(); // local function names used call ref validators
const state_remote_custom_types = new Map(); // remote custom types used during compilation
function ResetCompiler() {
state_local_variables.clear();
state_local_function_names.clear();
state_remote_custom_types.clear();
}
function CreateExpression(schema, references, value) {
return `(${[...Visit(schema, references, value)].join(' && ')})`;
}
function CreateFunctionName($id) {
return `check_${Identifier.Encode($id)}`;
}
function CreateFunction(name, schema, references, value) {
const expression = [...Visit(schema, references, value)].map((condition) => ` ${condition}`).join(' &&\n');
return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
}
function PushFunction(functionBody) {
state_local_variables.add(functionBody);
}
function PushLocal(expression) {
const local = `local_${state_local_variables.size}`;
state_local_variables.add(`const ${local} = ${expression}`);
return local;
}
function GetLocals() {
return [...state_local_variables.values()];
}
// -------------------------------------------------------------------
// Compile
// -------------------------------------------------------------------
function Build(schema, references) {
ResetCompiler();
const check = CreateFunction('check', schema, references, 'value');
const locals = GetLocals();
return `${locals.join('\n')}\nreturn ${check}`;
}
/** Returns the generated assertion code used to validate this type. */
function Code(schema, references = []) {
if (!Types.TypeGuard.TSchema(schema))
throw new TypeCompilerTypeGuardError(schema);
for (const schema of references)
if (!Types.TypeGuard.TSchema(schema))
throw new TypeCompilerTypeGuardError(schema);
return Build(schema, references);
}
TypeCompiler.Code = Code;
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
function Compile(schema, references = []) {
const code = Code(schema, references);
const custom_schemas = new Map(state_remote_custom_types);
const compiledFunction = globalThis.Function('custom', 'format', 'hash', code);
const checkFunction = compiledFunction((kind, schema_key, value) => {
if (!Types.TypeRegistry.Has(kind) || !custom_schemas.has(schema_key))
return false;
const schema = custom_schemas.get(schema_key);
const func = Types.TypeRegistry.Get(kind);
return func(schema, value);
}, (format, value) => {
if (!Types.FormatRegistry.Has(format))
return false;
const func = Types.FormatRegistry.Get(format);
return func(value);
}, (value) => {
return hash_1.ValueHash.Create(value);
});
return new TypeCheck(schema, references, checkFunction, code);
}
TypeCompiler.Compile = Compile;
})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));

View file

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

View file

@ -0,0 +1,47 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/compiler
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
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.ValueErrorType = void 0;
var index_1 = require("../errors/index");
Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } });
__exportStar(require("./compiler"), exports);

View file

@ -0,0 +1,88 @@
import * as Types from '../typebox';
export declare enum ValueErrorType {
Array = 0,
ArrayMinItems = 1,
ArrayMaxItems = 2,
ArrayUniqueItems = 3,
BigInt = 4,
BigIntMultipleOf = 5,
BigIntExclusiveMinimum = 6,
BigIntExclusiveMaximum = 7,
BigIntMinimum = 8,
BigIntMaximum = 9,
Boolean = 10,
Date = 11,
DateExclusiveMinimumTimestamp = 12,
DateExclusiveMaximumTimestamp = 13,
DateMinimumTimestamp = 14,
DateMaximumTimestamp = 15,
Function = 16,
Integer = 17,
IntegerMultipleOf = 18,
IntegerExclusiveMinimum = 19,
IntegerExclusiveMaximum = 20,
IntegerMinimum = 21,
IntegerMaximum = 22,
Intersect = 23,
IntersectUnevaluatedProperties = 24,
Literal = 25,
Never = 26,
Not = 27,
Null = 28,
Number = 29,
NumberMultipleOf = 30,
NumberExclusiveMinimum = 31,
NumberExclusiveMaximum = 32,
NumberMinumum = 33,
NumberMaximum = 34,
Object = 35,
ObjectMinProperties = 36,
ObjectMaxProperties = 37,
ObjectAdditionalProperties = 38,
ObjectRequiredProperties = 39,
Promise = 40,
RecordKeyNumeric = 41,
RecordKeyString = 42,
String = 43,
StringMinLength = 44,
StringMaxLength = 45,
StringPattern = 46,
StringFormatUnknown = 47,
StringFormat = 48,
Symbol = 49,
TupleZeroLength = 50,
TupleLength = 51,
Undefined = 52,
Union = 53,
Uint8Array = 54,
Uint8ArrayMinByteLength = 55,
Uint8ArrayMaxByteLength = 56,
Void = 57,
Custom = 58
}
export interface ValueError {
type: ValueErrorType;
schema: Types.TSchema;
path: string;
value: unknown;
message: string;
}
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;
}
export declare class ValueErrorsUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueErrorsDereferenceError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
/** Provides functionality to generate a sequence of errors against a TypeBox type. */
export declare namespace ValueErrors {
function Errors<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): ValueErrorIterator;
}

View file

@ -0,0 +1,609 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueErrors = exports.ValueErrorsDereferenceError = exports.ValueErrorsUnknownTypeError = exports.ValueErrorIterator = exports.ValueErrorType = void 0;
/*--------------------------------------------------------------------------
@sinclair/typebox/errors
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
const Types = require("../typebox");
const index_1 = require("../system/index");
const hash_1 = require("../value/hash");
// -------------------------------------------------------------------
// ValueErrorType
// -------------------------------------------------------------------
var ValueErrorType;
(function (ValueErrorType) {
ValueErrorType[ValueErrorType["Array"] = 0] = "Array";
ValueErrorType[ValueErrorType["ArrayMinItems"] = 1] = "ArrayMinItems";
ValueErrorType[ValueErrorType["ArrayMaxItems"] = 2] = "ArrayMaxItems";
ValueErrorType[ValueErrorType["ArrayUniqueItems"] = 3] = "ArrayUniqueItems";
ValueErrorType[ValueErrorType["BigInt"] = 4] = "BigInt";
ValueErrorType[ValueErrorType["BigIntMultipleOf"] = 5] = "BigIntMultipleOf";
ValueErrorType[ValueErrorType["BigIntExclusiveMinimum"] = 6] = "BigIntExclusiveMinimum";
ValueErrorType[ValueErrorType["BigIntExclusiveMaximum"] = 7] = "BigIntExclusiveMaximum";
ValueErrorType[ValueErrorType["BigIntMinimum"] = 8] = "BigIntMinimum";
ValueErrorType[ValueErrorType["BigIntMaximum"] = 9] = "BigIntMaximum";
ValueErrorType[ValueErrorType["Boolean"] = 10] = "Boolean";
ValueErrorType[ValueErrorType["Date"] = 11] = "Date";
ValueErrorType[ValueErrorType["DateExclusiveMinimumTimestamp"] = 12] = "DateExclusiveMinimumTimestamp";
ValueErrorType[ValueErrorType["DateExclusiveMaximumTimestamp"] = 13] = "DateExclusiveMaximumTimestamp";
ValueErrorType[ValueErrorType["DateMinimumTimestamp"] = 14] = "DateMinimumTimestamp";
ValueErrorType[ValueErrorType["DateMaximumTimestamp"] = 15] = "DateMaximumTimestamp";
ValueErrorType[ValueErrorType["Function"] = 16] = "Function";
ValueErrorType[ValueErrorType["Integer"] = 17] = "Integer";
ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 18] = "IntegerMultipleOf";
ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 19] = "IntegerExclusiveMinimum";
ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 20] = "IntegerExclusiveMaximum";
ValueErrorType[ValueErrorType["IntegerMinimum"] = 21] = "IntegerMinimum";
ValueErrorType[ValueErrorType["IntegerMaximum"] = 22] = "IntegerMaximum";
ValueErrorType[ValueErrorType["Intersect"] = 23] = "Intersect";
ValueErrorType[ValueErrorType["IntersectUnevaluatedProperties"] = 24] = "IntersectUnevaluatedProperties";
ValueErrorType[ValueErrorType["Literal"] = 25] = "Literal";
ValueErrorType[ValueErrorType["Never"] = 26] = "Never";
ValueErrorType[ValueErrorType["Not"] = 27] = "Not";
ValueErrorType[ValueErrorType["Null"] = 28] = "Null";
ValueErrorType[ValueErrorType["Number"] = 29] = "Number";
ValueErrorType[ValueErrorType["NumberMultipleOf"] = 30] = "NumberMultipleOf";
ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 31] = "NumberExclusiveMinimum";
ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 32] = "NumberExclusiveMaximum";
ValueErrorType[ValueErrorType["NumberMinumum"] = 33] = "NumberMinumum";
ValueErrorType[ValueErrorType["NumberMaximum"] = 34] = "NumberMaximum";
ValueErrorType[ValueErrorType["Object"] = 35] = "Object";
ValueErrorType[ValueErrorType["ObjectMinProperties"] = 36] = "ObjectMinProperties";
ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 37] = "ObjectMaxProperties";
ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 38] = "ObjectAdditionalProperties";
ValueErrorType[ValueErrorType["ObjectRequiredProperties"] = 39] = "ObjectRequiredProperties";
ValueErrorType[ValueErrorType["Promise"] = 40] = "Promise";
ValueErrorType[ValueErrorType["RecordKeyNumeric"] = 41] = "RecordKeyNumeric";
ValueErrorType[ValueErrorType["RecordKeyString"] = 42] = "RecordKeyString";
ValueErrorType[ValueErrorType["String"] = 43] = "String";
ValueErrorType[ValueErrorType["StringMinLength"] = 44] = "StringMinLength";
ValueErrorType[ValueErrorType["StringMaxLength"] = 45] = "StringMaxLength";
ValueErrorType[ValueErrorType["StringPattern"] = 46] = "StringPattern";
ValueErrorType[ValueErrorType["StringFormatUnknown"] = 47] = "StringFormatUnknown";
ValueErrorType[ValueErrorType["StringFormat"] = 48] = "StringFormat";
ValueErrorType[ValueErrorType["Symbol"] = 49] = "Symbol";
ValueErrorType[ValueErrorType["TupleZeroLength"] = 50] = "TupleZeroLength";
ValueErrorType[ValueErrorType["TupleLength"] = 51] = "TupleLength";
ValueErrorType[ValueErrorType["Undefined"] = 52] = "Undefined";
ValueErrorType[ValueErrorType["Union"] = 53] = "Union";
ValueErrorType[ValueErrorType["Uint8Array"] = 54] = "Uint8Array";
ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 55] = "Uint8ArrayMinByteLength";
ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 56] = "Uint8ArrayMaxByteLength";
ValueErrorType[ValueErrorType["Void"] = 57] = "Void";
ValueErrorType[ValueErrorType["Custom"] = 58] = "Custom";
})(ValueErrorType = exports.ValueErrorType || (exports.ValueErrorType = {}));
// -------------------------------------------------------------------
// 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;
// -------------------------------------------------------------------
// ValueErrors
// -------------------------------------------------------------------
class ValueErrorsUnknownTypeError extends Error {
constructor(schema) {
super('ValueErrors: Unknown type');
this.schema = schema;
}
}
exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError;
class ValueErrorsDereferenceError extends Error {
constructor(schema) {
super(`ValueErrors: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueErrorsDereferenceError = ValueErrorsDereferenceError;
/** Provides functionality to generate a sequence of errors against a TypeBox type. */
var ValueErrors;
(function (ValueErrors) {
// ----------------------------------------------------------------------
// Guards
// ----------------------------------------------------------------------
function IsBigInt(value) {
return typeof value === 'bigint';
}
function IsInteger(value) {
return globalThis.Number.isInteger(value);
}
function IsString(value) {
return typeof value === 'string';
}
function IsDefined(value) {
return value !== undefined;
}
// ----------------------------------------------------------------------
// Policies
// ----------------------------------------------------------------------
function IsExactOptionalProperty(value, key) {
return index_1.TypeSystem.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;
}
function IsObject(value) {
const result = typeof value === 'object' && value !== null;
return index_1.TypeSystem.AllowArrayObjects ? result : result && !globalThis.Array.isArray(value);
}
function IsRecordObject(value) {
return IsObject(value) && !(value instanceof globalThis.Date) && !(value instanceof globalThis.Uint8Array);
}
function IsNumber(value) {
const result = typeof value === 'number';
return index_1.TypeSystem.AllowNaN ? result : result && globalThis.Number.isFinite(value);
}
function IsVoid(value) {
const result = value === undefined;
return index_1.TypeSystem.AllowVoidNull ? result || value === null : result;
}
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
function* Any(schema, references, path, value) { }
function* Array(schema, references, path, value) {
if (!globalThis.Array.isArray(value)) {
return yield { type: ValueErrorType.Array, schema, path, value, message: `Expected array` };
}
if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be greater or equal to ${schema.minItems}` };
}
if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be less or equal to ${schema.maxItems}` };
}
// prettier-ignore
if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {
const hashed = hash_1.ValueHash.Create(element);
if (set.has(hashed)) {
return false;
}
else {
set.add(hashed);
}
} return true; })())) {
yield { type: ValueErrorType.ArrayUniqueItems, schema, path, value, message: `Expected array elements to be unique` };
}
for (let i = 0; i < value.length; i++) {
yield* Visit(schema.items, references, `${path}/${i}`, value[i]);
}
}
function* BigInt(schema, references, path, value) {
if (!IsBigInt(value)) {
return yield { type: ValueErrorType.BigInt, schema, path, value, message: `Expected bigint` };
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === globalThis.BigInt(0))) {
yield { type: ValueErrorType.BigIntMultipleOf, schema, path, value, message: `Expected bigint to be a multiple of ${schema.multipleOf}` };
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.BigIntExclusiveMinimum, schema, path, value, message: `Expected bigint to be greater than ${schema.exclusiveMinimum}` };
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.BigIntExclusiveMaximum, schema, path, value, message: `Expected bigint to be less than ${schema.exclusiveMaximum}` };
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield { type: ValueErrorType.BigIntMinimum, schema, path, value, message: `Expected bigint to be greater or equal to ${schema.minimum}` };
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield { type: ValueErrorType.BigIntMaximum, schema, path, value, message: `Expected bigint to be less or equal to ${schema.maximum}` };
}
}
function* Boolean(schema, references, path, value) {
if (!(typeof value === 'boolean')) {
return yield { type: ValueErrorType.Boolean, schema, path, value, message: `Expected boolean` };
}
}
function* Constructor(schema, references, path, value) {
yield* Visit(schema.returns, references, path, value.prototype);
}
function* Date(schema, references, path, value) {
if (!(value instanceof globalThis.Date)) {
return yield { type: ValueErrorType.Date, schema, path, value, message: `Expected Date object` };
}
if (!globalThis.isFinite(value.getTime())) {
return yield { type: ValueErrorType.Date, schema, path, value, message: `Invalid Date` };
}
if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {
yield { type: ValueErrorType.DateExclusiveMinimumTimestamp, schema, path, value, message: `Expected Date timestamp to be greater than ${schema.exclusiveMinimum}` };
}
if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {
yield { type: ValueErrorType.DateExclusiveMaximumTimestamp, schema, path, value, message: `Expected Date timestamp to be less than ${schema.exclusiveMaximum}` };
}
if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {
yield { type: ValueErrorType.DateMinimumTimestamp, schema, path, value, message: `Expected Date timestamp to be greater or equal to ${schema.minimum}` };
}
if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {
yield { type: ValueErrorType.DateMaximumTimestamp, schema, path, value, message: `Expected Date timestamp to be less or equal to ${schema.maximum}` };
}
}
function* Function(schema, references, path, value) {
if (!(typeof value === 'function')) {
return yield { type: ValueErrorType.Function, schema, path, value, message: `Expected function` };
}
}
function* Integer(schema, references, path, value) {
if (!IsInteger(value)) {
return yield { type: ValueErrorType.Integer, schema, path, value, message: `Expected integer` };
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
yield { type: ValueErrorType.IntegerMultipleOf, schema, path, value, message: `Expected integer to be a multiple of ${schema.multipleOf}` };
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.IntegerExclusiveMinimum, schema, path, value, message: `Expected integer to be greater than ${schema.exclusiveMinimum}` };
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.IntegerExclusiveMaximum, schema, path, value, message: `Expected integer to be less than ${schema.exclusiveMaximum}` };
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield { type: ValueErrorType.IntegerMinimum, schema, path, value, message: `Expected integer to be greater or equal to ${schema.minimum}` };
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield { type: ValueErrorType.IntegerMaximum, schema, path, value, message: `Expected integer to be less or equal to ${schema.maximum}` };
}
}
function* Intersect(schema, references, path, value) {
for (const subschema of schema.allOf) {
const next = Visit(subschema, references, path, value).next();
if (!next.done) {
yield next.value;
yield { type: ValueErrorType.Intersect, schema, path, value, message: `Expected all sub schemas to be valid` };
return;
}
}
if (schema.unevaluatedProperties === false) {
const schemaKeys = Types.KeyResolver.Resolve(schema);
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
for (const valueKey of valueKeys) {
if (!schemaKeys.includes(valueKey)) {
yield { type: ValueErrorType.IntersectUnevaluatedProperties, schema, path: `${path}/${valueKey}`, value, message: `Unexpected property` };
}
}
}
if (typeof schema.unevaluatedProperties === 'object') {
const schemaKeys = Types.KeyResolver.Resolve(schema);
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
for (const valueKey of valueKeys) {
if (!schemaKeys.includes(valueKey)) {
const next = Visit(schema.unevaluatedProperties, references, `${path}/${valueKey}`, value[valueKey]).next();
if (!next.done) {
yield next.value;
yield { type: ValueErrorType.IntersectUnevaluatedProperties, schema, path: `${path}/${valueKey}`, value, message: `Invalid additional property` };
return;
}
}
}
}
}
function* Literal(schema, references, path, value) {
if (!(value === schema.const)) {
const error = typeof schema.const === 'string' ? `'${schema.const}'` : schema.const;
return yield { type: ValueErrorType.Literal, schema, path, value, message: `Expected ${error}` };
}
}
function* Never(schema, references, path, value) {
yield { type: ValueErrorType.Never, schema, path, value, message: `Value cannot be validated` };
}
function* Not(schema, references, path, value) {
if (Visit(schema.allOf[0].not, references, path, value).next().done === true) {
yield { type: ValueErrorType.Not, schema, path, value, message: `Value should not validate` };
}
yield* Visit(schema.allOf[1], references, path, value);
}
function* Null(schema, references, path, value) {
if (!(value === null)) {
return yield { type: ValueErrorType.Null, schema, path, value, message: `Expected null` };
}
}
function* Number(schema, references, path, value) {
if (!IsNumber(value)) {
return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` };
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
yield { type: ValueErrorType.NumberMultipleOf, schema, path, value, message: `Expected number to be a multiple of ${schema.multipleOf}` };
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.NumberExclusiveMinimum, schema, path, value, message: `Expected number to be greater than ${schema.exclusiveMinimum}` };
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.NumberExclusiveMaximum, schema, path, value, message: `Expected number to be less than ${schema.exclusiveMaximum}` };
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
yield { type: ValueErrorType.NumberMaximum, schema, path, value, message: `Expected number to be greater or equal to ${schema.minimum}` };
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
yield { type: ValueErrorType.NumberMinumum, schema, path, value, message: `Expected number to be less or equal to ${schema.maximum}` };
}
}
function* Object(schema, references, path, value) {
if (!IsObject(value)) {
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` };
}
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` };
}
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
}
const requiredKeys = globalThis.Array.isArray(schema.required) ? schema.required : [];
const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
const unknownKeys = globalThis.Object.getOwnPropertyNames(value);
for (const knownKey of knownKeys) {
const property = schema.properties[knownKey];
if (schema.required && schema.required.includes(knownKey)) {
yield* Visit(property, references, `${path}/${knownKey}`, value[knownKey]);
if (Types.ExtendsUndefined.Check(schema) && !(knownKey in value)) {
yield { type: ValueErrorType.ObjectRequiredProperties, schema: property, path: `${path}/${knownKey}`, value: undefined, message: `Expected required property` };
}
}
else {
if (IsExactOptionalProperty(value, knownKey)) {
yield* Visit(property, references, `${path}/${knownKey}`, value[knownKey]);
}
}
}
for (const requiredKey of requiredKeys) {
if (unknownKeys.includes(requiredKey))
continue;
yield { type: ValueErrorType.ObjectRequiredProperties, schema: schema.properties[requiredKey], path: `${path}/${requiredKey}`, value: undefined, message: `Expected required property` };
}
if (schema.additionalProperties === false) {
for (const valueKey of unknownKeys) {
if (!knownKeys.includes(valueKey)) {
yield { type: ValueErrorType.ObjectAdditionalProperties, schema, path: `${path}/${valueKey}`, value: value[valueKey], message: `Unexpected property` };
}
}
}
if (typeof schema.additionalProperties === 'object') {
for (const valueKey of unknownKeys) {
if (knownKeys.includes(valueKey))
continue;
yield* Visit(schema.additionalProperties, references, `${path}/${valueKey}`, value[valueKey]);
}
}
}
function* Promise(schema, references, path, value) {
if (!(typeof value === 'object' && typeof value.then === 'function')) {
yield { type: ValueErrorType.Promise, schema, path, value, message: `Expected Promise` };
}
}
function* Record(schema, references, path, value) {
if (!IsRecordObject(value)) {
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected record object` };
}
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` };
}
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
}
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern);
if (!globalThis.Object.getOwnPropertyNames(value).every((key) => regex.test(key))) {
const numeric = keyPattern === Types.PatternNumberExact;
const type = numeric ? ValueErrorType.RecordKeyNumeric : ValueErrorType.RecordKeyString;
const message = numeric ? 'Expected all object property keys to be numeric' : 'Expected all object property keys to be strings';
return yield { type, schema, path, value, message };
}
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
yield* Visit(valueSchema, references, `${path}/${propKey}`, propValue);
}
}
function* Ref(schema, references, path, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueErrorsDereferenceError(schema);
const target = references[index];
yield* Visit(target, references, path, value);
}
function* String(schema, references, path, value) {
if (!IsString(value)) {
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
}
if (IsDefined(schema.minLength) && !(value.length >= schema.minLength)) {
yield { type: ValueErrorType.StringMinLength, schema, path, value, message: `Expected string length greater or equal to ${schema.minLength}` };
}
if (IsDefined(schema.maxLength) && !(value.length <= schema.maxLength)) {
yield { type: ValueErrorType.StringMaxLength, schema, path, value, message: `Expected string length less or equal to ${schema.maxLength}` };
}
if (schema.pattern !== undefined) {
const regex = new RegExp(schema.pattern);
if (!regex.test(value)) {
yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` };
}
}
if (schema.format !== undefined) {
if (!Types.FormatRegistry.Has(schema.format)) {
yield { type: ValueErrorType.StringFormatUnknown, schema, path, value, message: `Unknown string format '${schema.format}'` };
}
else {
const format = Types.FormatRegistry.Get(schema.format);
if (!format(value)) {
yield { type: ValueErrorType.StringFormat, schema, path, value, message: `Expected string to match format '${schema.format}'` };
}
}
}
}
function* Symbol(schema, references, path, value) {
if (!(typeof value === 'symbol')) {
return yield { type: ValueErrorType.Symbol, schema, path, value, message: 'Expected symbol' };
}
}
function* TemplateLiteral(schema, references, path, value) {
if (!IsString(value)) {
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
}
const regex = new RegExp(schema.pattern);
if (!regex.test(value)) {
yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` };
}
}
function* This(schema, references, path, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueErrorsDereferenceError(schema);
const target = references[index];
yield* Visit(target, references, path, value);
}
function* Tuple(schema, references, path, value) {
if (!globalThis.Array.isArray(value)) {
return yield { type: ValueErrorType.Array, schema, path, value, message: 'Expected Array' };
}
if (schema.items === undefined && !(value.length === 0)) {
return yield { type: ValueErrorType.TupleZeroLength, schema, path, value, message: 'Expected tuple to have 0 elements' };
}
if (!(value.length === schema.maxItems)) {
yield { type: ValueErrorType.TupleLength, schema, path, value, message: `Expected tuple to have ${schema.maxItems} elements` };
}
if (!schema.items) {
return;
}
for (let i = 0; i < schema.items.length; i++) {
yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]);
}
}
function* Undefined(schema, references, path, value) {
if (!(value === undefined)) {
yield { type: ValueErrorType.Undefined, schema, path, value, message: `Expected undefined` };
}
}
function* Union(schema, references, path, value) {
const errors = [];
for (const inner of schema.anyOf) {
const variantErrors = [...Visit(inner, references, path, value)];
if (variantErrors.length === 0)
return;
errors.push(...variantErrors);
}
if (errors.length > 0) {
yield { type: ValueErrorType.Union, schema, path, value, message: 'Expected value of union' };
}
for (const error of errors) {
yield error;
}
}
function* Uint8Array(schema, references, path, value) {
if (!(value instanceof globalThis.Uint8Array)) {
return yield { type: ValueErrorType.Uint8Array, schema, path, value, message: `Expected Uint8Array` };
}
if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {
yield { type: ValueErrorType.Uint8ArrayMaxByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length less or equal to ${schema.maxByteLength}` };
}
if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {
yield { type: ValueErrorType.Uint8ArrayMinByteLength, schema, path, value, message: `Expected Uint8Array to have a byte length greater or equal to ${schema.maxByteLength}` };
}
}
function* Unknown(schema, references, path, value) { }
function* Void(schema, references, path, value) {
if (!IsVoid(value)) {
return yield { type: ValueErrorType.Void, schema, path, value, message: `Expected void` };
}
}
function* UserDefined(schema, references, path, value) {
const check = Types.TypeRegistry.Get(schema[Types.Kind]);
if (!check(schema, value)) {
return yield { type: ValueErrorType.Custom, schema, path, value, message: `Expected kind ${schema[Types.Kind]}` };
}
}
function* Visit(schema, references, path, value) {
const references_ = IsDefined(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema_[Types.Kind]) {
case 'Any':
return yield* Any(schema_, references_, path, value);
case 'Array':
return yield* Array(schema_, references_, path, value);
case 'BigInt':
return yield* BigInt(schema_, references_, path, value);
case 'Boolean':
return yield* Boolean(schema_, references_, path, value);
case 'Constructor':
return yield* Constructor(schema_, references_, path, value);
case 'Date':
return yield* Date(schema_, references_, path, value);
case 'Function':
return yield* Function(schema_, references_, path, value);
case 'Integer':
return yield* Integer(schema_, references_, path, value);
case 'Intersect':
return yield* Intersect(schema_, references_, path, value);
case 'Literal':
return yield* Literal(schema_, references_, path, value);
case 'Never':
return yield* Never(schema_, references_, path, value);
case 'Not':
return yield* Not(schema_, references_, path, value);
case 'Null':
return yield* Null(schema_, references_, path, value);
case 'Number':
return yield* Number(schema_, references_, path, value);
case 'Object':
return yield* Object(schema_, references_, path, value);
case 'Promise':
return yield* Promise(schema_, references_, path, value);
case 'Record':
return yield* Record(schema_, references_, path, value);
case 'Ref':
return yield* Ref(schema_, references_, path, value);
case 'String':
return yield* String(schema_, references_, path, value);
case 'Symbol':
return yield* Symbol(schema_, references_, path, value);
case 'TemplateLiteral':
return yield* TemplateLiteral(schema_, references_, path, value);
case 'This':
return yield* This(schema_, references_, path, value);
case 'Tuple':
return yield* Tuple(schema_, references_, path, value);
case 'Undefined':
return yield* Undefined(schema_, references_, path, value);
case 'Union':
return yield* Union(schema_, references_, path, value);
case 'Uint8Array':
return yield* Uint8Array(schema_, references_, path, value);
case 'Unknown':
return yield* Unknown(schema_, references_, path, value);
case 'Void':
return yield* Void(schema_, references_, path, value);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new ValueErrorsUnknownTypeError(schema);
return yield* UserDefined(schema_, references_, path, value);
}
}
function Errors(schema, references, value) {
const iterator = Visit(schema, references, '', value);
return new ValueErrorIterator(iterator);
}
ValueErrors.Errors = Errors;
})(ValueErrors = exports.ValueErrors || (exports.ValueErrors = {}));

View file

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

View file

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

View file

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

View file

@ -0,0 +1,49 @@
{
"name": "@sinclair/typebox",
"version": "0.27.10",
"description": "JSONSchema Type Builder with Static Type Resolution for TypeScript",
"keywords": [
"typescript",
"json-schema",
"validate",
"typecheck"
],
"author": "sinclairzx81",
"license": "MIT",
"main": "./typebox.js",
"types": "./typebox.d.ts",
"exports": {
"./compiler": "./compiler/index.js",
"./errors": "./errors/index.js",
"./system": "./system/index.js",
"./value": "./value/index.js",
".": "./typebox.js"
},
"repository": {
"type": "git",
"url": "https://github.com/sinclairzx81/typebox-legacy"
},
"scripts": {
"clean": "hammer task clean",
"format": "hammer task format",
"start": "hammer task start",
"test": "hammer task test",
"benchmark": "hammer task benchmark",
"build": "hammer task build",
"build:native": "hammer task build_native",
"publish": "hammer task publish"
},
"devDependencies": {
"@sinclair/hammer": "^0.17.1",
"@typescript/native-preview": "^7.0.0-dev.20260203.1",
"@types/chai": "^4.3.3",
"@types/mocha": "^9.1.1",
"@types/node": "^18.19.130",
"ajv": "^8.12.0",
"ajv-formats": "^2.1.1",
"chai": "^4.3.6",
"mocha": "^9.2.2",
"prettier": "^2.7.1",
"typescript": "5.0.2"
}
}

File diff suppressed because it is too large Load diff

View file

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

View file

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

View file

@ -0,0 +1,26 @@
import * as Types from '../typebox';
export declare class TypeSystemDuplicateTypeKind extends Error {
constructor(kind: string);
}
export declare class TypeSystemDuplicateFormat extends Error {
constructor(kind: string);
}
/** Creates user defined types and formats and provides overrides for value checking behaviours */
export declare namespace TypeSystem {
/** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */
let ExactOptionalPropertyTypes: boolean;
/** Sets whether arrays should be treated as a kind of objects. The default is `false` */
let AllowArrayObjects: boolean;
/** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */
let AllowNaN: boolean;
/** Sets whether `null` should validate for void types. The default is `false` */
let AllowVoidNull: boolean;
/** Creates a new type */
function Type<Type, Options = object>(kind: string, check: (options: Options, value: unknown) => boolean): (options?: Partial<Options>) => Types.TUnsafe<Type>;
/** Creates a new string format */
function Format<F extends string>(format: F, check: (value: string) => boolean): F;
/** @deprecated Use `TypeSystem.Type()` instead. */
function CreateType<Type, Options = object>(kind: string, check: (options: Options, value: unknown) => boolean): (options?: Partial<Options>) => Types.TUnsafe<Type>;
/** @deprecated Use `TypeSystem.Format()` instead. */
function CreateFormat<F extends string>(format: F, check: (value: string) => boolean): F;
}

View file

@ -0,0 +1,90 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/system
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeSystem = exports.TypeSystemDuplicateFormat = exports.TypeSystemDuplicateTypeKind = void 0;
const Types = require("../typebox");
class TypeSystemDuplicateTypeKind extends Error {
constructor(kind) {
super(`Duplicate type kind '${kind}' detected`);
}
}
exports.TypeSystemDuplicateTypeKind = TypeSystemDuplicateTypeKind;
class TypeSystemDuplicateFormat extends Error {
constructor(kind) {
super(`Duplicate string format '${kind}' detected`);
}
}
exports.TypeSystemDuplicateFormat = TypeSystemDuplicateFormat;
/** Creates user defined types and formats and provides overrides for value checking behaviours */
var TypeSystem;
(function (TypeSystem) {
// ------------------------------------------------------------------------
// Assertion Policies
// ------------------------------------------------------------------------
/** Sets whether TypeBox should assert optional properties using the TypeScript `exactOptionalPropertyTypes` assertion policy. The default is `false` */
TypeSystem.ExactOptionalPropertyTypes = false;
/** Sets whether arrays should be treated as a kind of objects. The default is `false` */
TypeSystem.AllowArrayObjects = false;
/** Sets whether `NaN` or `Infinity` should be treated as valid numeric values. The default is `false` */
TypeSystem.AllowNaN = false;
/** Sets whether `null` should validate for void types. The default is `false` */
TypeSystem.AllowVoidNull = false;
// ------------------------------------------------------------------------
// String Formats and Types
// ------------------------------------------------------------------------
/** Creates a new type */
function Type(kind, check) {
if (Types.TypeRegistry.Has(kind))
throw new TypeSystemDuplicateTypeKind(kind);
Types.TypeRegistry.Set(kind, check);
return (options = {}) => Types.Type.Unsafe({ ...options, [Types.Kind]: kind });
}
TypeSystem.Type = Type;
/** Creates a new string format */
function Format(format, check) {
if (Types.FormatRegistry.Has(format))
throw new TypeSystemDuplicateFormat(format);
Types.FormatRegistry.Set(format, check);
return format;
}
TypeSystem.Format = Format;
// ------------------------------------------------------------------------
// Deprecated
// ------------------------------------------------------------------------
/** @deprecated Use `TypeSystem.Type()` instead. */
function CreateType(kind, check) {
return Type(kind, check);
}
TypeSystem.CreateType = CreateType;
/** @deprecated Use `TypeSystem.Format()` instead. */
function CreateFormat(format, check) {
return Format(format, check);
}
TypeSystem.CreateFormat = CreateFormat;
})(TypeSystem = exports.TypeSystem || (exports.TypeSystem = {}));

View file

@ -0,0 +1,717 @@
export declare const Modifier: unique symbol;
export declare const Hint: unique symbol;
export declare const Kind: unique symbol;
export declare const PatternBoolean = "(true|false)";
export declare const PatternNumber = "(0|[1-9][0-9]*)";
export declare const PatternString = "(.*)";
export declare const PatternBooleanExact: string;
export declare const PatternNumberExact: string;
export declare const PatternStringExact: string;
export type TupleToIntersect<T extends any[]> = T extends [infer I] ? I : T extends [infer I, ...infer R] ? I & TupleToIntersect<R> : never;
export type TupleToUnion<T extends any[]> = {
[K in keyof T]: T[K];
}[number];
export type UnionToIntersect<U> = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never;
export type UnionLast<U> = UnionToIntersect<U extends unknown ? (x: U) => 0 : never> extends (x: infer L) => 0 ? L : never;
export type UnionToTuple<U, L = UnionLast<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, L>>, L];
export type Assert<T, E> = T extends E ? T : never;
export type Evaluate<T> = T extends infer O ? {
[K in keyof O]: O[K];
} : never;
export type Ensure<T> = T extends infer U ? U : never;
export type TModifier = TReadonlyOptional<TSchema> | TOptional<TSchema> | TReadonly<TSchema>;
export type TReadonly<T extends TSchema> = T & {
[Modifier]: 'Readonly';
};
export type TOptional<T extends TSchema> = T & {
[Modifier]: 'Optional';
};
export type TReadonlyOptional<T extends TSchema> = T & {
[Modifier]: 'ReadonlyOptional';
};
export interface SchemaOptions {
$schema?: string;
/** Id for this schema */
$id?: string;
/** Title of this schema */
title?: string;
/** Description of this schema */
description?: string;
/** Default value for this schema */
default?: any;
/** Example values matching this schema */
examples?: any;
[prop: string]: any;
}
export interface TKind {
[Kind]: string;
}
export interface TSchema extends SchemaOptions, TKind {
[Modifier]?: string;
[Hint]?: string;
params: unknown[];
static: unknown;
}
export type TAnySchema = TSchema | TAny | TArray | TBigInt | TBoolean | TConstructor | TDate | TEnum | TFunction | TInteger | TIntersect | TLiteral | TNot | TNull | TNumber | TObject | TPromise | TRecord | TRef | TString | TSymbol | TTemplateLiteral | TThis | TTuple | TUndefined | TUnion | TUint8Array | TUnknown | TVoid;
export type TNumeric = TInteger | TNumber;
export interface NumericOptions<N extends number | bigint> extends SchemaOptions {
exclusiveMaximum?: N;
exclusiveMinimum?: N;
maximum?: N;
minimum?: N;
multipleOf?: N;
}
export interface TAny extends TSchema {
[Kind]: 'Any';
static: any;
}
export interface ArrayOptions extends SchemaOptions {
uniqueItems?: boolean;
minItems?: number;
maxItems?: number;
}
export interface TArray<T extends TSchema = TSchema> extends TSchema, ArrayOptions {
[Kind]: 'Array';
static: Static<T, this['params']>[];
type: 'array';
items: T;
}
export interface TBigInt extends TSchema, NumericOptions<bigint> {
[Kind]: 'BigInt';
static: bigint;
type: 'null';
typeOf: 'BigInt';
}
export interface TBoolean extends TSchema {
[Kind]: 'Boolean';
static: boolean;
type: 'boolean';
}
export type TConstructorParameters<T extends TConstructor<TSchema[], TSchema>> = TTuple<T['parameters']>;
export type TInstanceType<T extends TConstructor<TSchema[], TSchema>> = T['returns'];
export type TCompositeEvaluateArray<T extends readonly TSchema[], P extends unknown[]> = {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never;
};
export type TCompositeArray<T extends readonly TObject[]> = {
[K in keyof T]: T[K] extends TObject<infer P> ? P : {};
};
export type TCompositeProperties<I extends unknown, T extends readonly any[]> = Evaluate<T extends [infer A, ...infer B] ? TCompositeProperties<I & A, B> : I extends object ? I : {}>;
export interface TComposite<T extends TObject[] = TObject[]> extends TObject {
[Hint]: 'Composite';
static: Evaluate<TCompositeProperties<unknown, TCompositeEvaluateArray<T, this['params']>>>;
properties: TCompositeProperties<unknown, TCompositeArray<T>>;
}
export type TConstructorParameterArray<T extends readonly TSchema[], P extends unknown[]> = [...{
[K in keyof T]: Static<Assert<T[K], TSchema>, P>;
}];
export interface TConstructor<T extends TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Constructor';
static: new (...param: TConstructorParameterArray<T, this['params']>) => Static<U, this['params']>;
type: 'object';
instanceOf: 'Constructor';
parameters: T;
returns: U;
}
export interface DateOptions extends SchemaOptions {
exclusiveMaximumTimestamp?: number;
exclusiveMinimumTimestamp?: number;
maximumTimestamp?: number;
minimumTimestamp?: number;
}
export interface TDate extends TSchema, DateOptions {
[Kind]: 'Date';
static: Date;
type: 'object';
instanceOf: 'Date';
}
export interface TEnumOption<T> {
type: 'number' | 'string';
const: T;
}
export interface TEnum<T extends Record<string, string | number> = Record<string, string | number>> extends TSchema {
[Kind]: 'Union';
static: T[keyof T];
anyOf: TLiteral<string | number>[];
}
export type TExtends<L extends TSchema, R extends TSchema, T extends TSchema, U extends TSchema> = (Static<L> extends Static<R> ? T : U) extends infer O ? UnionToTuple<O> extends [infer X, infer Y] ? TUnion<[Assert<X, TSchema>, Assert<Y, TSchema>]> : Assert<O, TSchema> : never;
export type TExcludeTemplateLiteralResult<T extends string> = TString;
export type TExcludeTemplateLiteral<T extends TTemplateLiteral, U extends TSchema> = Exclude<Static<T>, Static<U>> extends infer S ? TExcludeTemplateLiteralResult<Assert<S, string>> : never;
export type TExcludeArray<T extends TSchema[], U extends TSchema> = Assert<UnionToTuple<{
[K in keyof T]: Static<Assert<T[K], TSchema>> extends Static<U> ? never : T[K];
}[number]>, TSchema[]> extends infer R ? TUnionResult<Assert<R, TSchema[]>> : never;
export type TExclude<T extends TSchema, U extends TSchema> = T extends TTemplateLiteral ? TExcludeTemplateLiteral<T, U> : T extends TUnion<infer S> ? TExcludeArray<S, U> : T extends U ? TNever : T;
export type TExtractTemplateLiteralResult<T extends string> = TString;
export type TExtractTemplateLiteral<T extends TTemplateLiteral, U extends TSchema> = Extract<Static<T>, Static<U>> extends infer S ? TExtractTemplateLiteralResult<Assert<S, string>> : never;
export type TExtractArray<T extends TSchema[], U extends TSchema> = Assert<UnionToTuple<{
[K in keyof T]: Static<Assert<T[K], TSchema>> extends Static<U> ? T[K] : never;
}[number]>, TSchema[]> extends infer R ? TUnionResult<Assert<R, TSchema[]>> : never;
export type TExtract<T extends TSchema, U extends TSchema> = T extends TTemplateLiteral ? TExtractTemplateLiteral<T, U> : T extends TUnion<infer S> ? TExtractArray<S, U> : T extends U ? T : T;
export type TFunctionParameters<T extends readonly TSchema[], P extends unknown[]> = [...{
[K in keyof T]: Static<Assert<T[K], TSchema>, P>;
}];
export interface TFunction<T extends readonly TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Function';
static: (...param: TFunctionParameters<T, this['params']>) => Static<U, this['params']>;
type: 'object';
instanceOf: 'Function';
parameters: T;
returns: U;
}
export interface TInteger extends TSchema, NumericOptions<number> {
[Kind]: 'Integer';
static: number;
type: 'integer';
}
export type TUnevaluatedProperties = undefined | TSchema | boolean;
export interface IntersectOptions extends SchemaOptions {
unevaluatedProperties?: TUnevaluatedProperties;
}
export interface TIntersect<T extends TSchema[] = TSchema[]> extends TSchema, IntersectOptions {
[Kind]: 'Intersect';
static: TupleToIntersect<{
[K in keyof T]: Static<Assert<T[K], TSchema>, this['params']>;
}>;
type?: 'object';
allOf: [...T];
}
export type TKeyOfTuple<T extends TSchema> = {
[K in keyof Static<T>]: TLiteral<Assert<K, TLiteralValue>>;
} extends infer U ? UnionToTuple<Exclude<{
[K in keyof U]: U[K];
}[keyof U], undefined>> : never;
export type TKeyOf<T extends TSchema = TSchema> = (T extends TRecursive<infer S> ? TKeyOfTuple<S> : T extends TComposite ? TKeyOfTuple<T> : T extends TIntersect ? TKeyOfTuple<T> : T extends TUnion ? TKeyOfTuple<T> : T extends TObject ? TKeyOfTuple<T> : T extends TRecord<infer K> ? [K] : [
]) extends infer R ? TUnionResult<Assert<R, TSchema[]>> : never;
export type TLiteralValue = string | number | boolean;
export interface TLiteral<T extends TLiteralValue = TLiteralValue> extends TSchema {
[Kind]: 'Literal';
static: T;
const: T;
}
export interface TNever extends TSchema {
[Kind]: 'Never';
static: never;
not: {};
}
export interface TNot<Not extends TSchema = TSchema, T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Not';
static: Static<T>;
allOf: [{
not: Not;
}, T];
}
export interface TNull extends TSchema {
[Kind]: 'Null';
static: null;
type: 'null';
}
export interface TNumber extends TSchema, NumericOptions<number> {
[Kind]: 'Number';
static: number;
type: 'number';
}
export type ReadonlyOptionalPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TReadonlyOptional<TSchema> ? K : never;
}[keyof T];
export type ReadonlyPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TReadonly<TSchema> ? K : never;
}[keyof T];
export type OptionalPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TOptional<TSchema> ? K : never;
}[keyof T];
export type RequiredPropertyKeys<T extends TProperties> = keyof Omit<T, ReadonlyOptionalPropertyKeys<T> | ReadonlyPropertyKeys<T> | OptionalPropertyKeys<T>>;
export type PropertiesReducer<T extends TProperties, R extends Record<keyof any, unknown>> = Evaluate<(Readonly<Partial<Pick<R, ReadonlyOptionalPropertyKeys<T>>>> & Readonly<Pick<R, ReadonlyPropertyKeys<T>>> & Partial<Pick<R, OptionalPropertyKeys<T>>> & Required<Pick<R, RequiredPropertyKeys<T>>>)>;
export type PropertiesReduce<T extends TProperties, P extends unknown[]> = PropertiesReducer<T, {
[K in keyof T]: Static<T[K], P>;
}>;
export type TProperties = Record<keyof any, TSchema>;
export type ObjectProperties<T> = T extends TObject<infer U> ? U : never;
export type ObjectPropertyKeys<T> = T extends TObject<infer U> ? keyof U : never;
export type TAdditionalProperties = undefined | TSchema | boolean;
export interface ObjectOptions extends SchemaOptions {
additionalProperties?: TAdditionalProperties;
minProperties?: number;
maxProperties?: number;
}
export interface TObject<T extends TProperties = TProperties> extends TSchema, ObjectOptions {
[Kind]: 'Object';
static: PropertiesReduce<T, this['params']>;
additionalProperties?: TAdditionalProperties;
type: 'object';
properties: T;
required?: string[];
}
export type TOmitArray<T extends TSchema[], K extends keyof any> = Assert<{
[K2 in keyof T]: TOmit<Assert<T[K2], TSchema>, K>;
}, TSchema[]>;
export type TOmitProperties<T extends TProperties, K extends keyof any> = Evaluate<Assert<Omit<T, K>, TProperties>>;
export type TOmit<T extends TSchema = TSchema, K extends keyof any = keyof any> = T extends TRecursive<infer S> ? TRecursive<TOmit<S, K>> : T extends TComposite<infer S> ? TComposite<TOmitArray<S, K>> : T extends TIntersect<infer S> ? TIntersect<TOmitArray<S, K>> : T extends TUnion<infer S> ? TUnion<TOmitArray<S, K>> : T extends TObject<infer S> ? TObject<TOmitProperties<S, K>> : T;
export type TParameters<T extends TFunction> = TTuple<T['parameters']>;
export type TPartialObjectArray<T extends TObject[]> = Assert<{
[K in keyof T]: TPartial<Assert<T[K], TObject>>;
}, TObject[]>;
export type TPartialArray<T extends TSchema[]> = Assert<{
[K in keyof T]: TPartial<Assert<T[K], TSchema>>;
}, TSchema[]>;
export type TPartialProperties<T extends TProperties> = Evaluate<Assert<{
[K in keyof T]: T[K] extends TReadonlyOptional<infer U> ? TReadonlyOptional<U> : T[K] extends TReadonly<infer U> ? TReadonlyOptional<U> : T[K] extends TOptional<infer U> ? TOptional<U> : TOptional<T[K]>;
}, TProperties>>;
export type TPartial<T extends TSchema> = T extends TRecursive<infer S> ? TRecursive<TPartial<S>> : T extends TComposite<infer S> ? TComposite<TPartialArray<S>> : T extends TIntersect<infer S> ? TIntersect<TPartialArray<S>> : T extends TUnion<infer S> ? TUnion<TPartialArray<S>> : T extends TObject<infer S> ? TObject<TPartialProperties<S>> : T;
export type TPickArray<T extends TSchema[], K extends keyof any> = {
[K2 in keyof T]: TPick<Assert<T[K2], TSchema>, K>;
};
export type TPickProperties<T extends TProperties, K extends keyof any> = Pick<T, Assert<Extract<K, keyof T>, keyof T>> extends infer R ? ({
[K in keyof R]: Assert<R[K], TSchema> extends TSchema ? R[K] : never;
}) : never;
export type TPick<T extends TSchema = TSchema, K extends keyof any = keyof any> = T extends TRecursive<infer S> ? TRecursive<TPick<S, K>> : T extends TComposite<infer S> ? TComposite<TPickArray<S, K>> : T extends TIntersect<infer S> ? TIntersect<TPickArray<S, K>> : T extends TUnion<infer S> ? TUnion<TPickArray<S, K>> : T extends TObject<infer S> ? TObject<TPickProperties<S, K>> : T;
export interface TPromise<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Promise';
static: Promise<Static<T, this['params']>>;
type: 'object';
instanceOf: 'Promise';
item: TSchema;
}
export type RecordTemplateLiteralObjectType<K extends TTemplateLiteral, T extends TSchema> = Ensure<TObject<Evaluate<{
[_ in Static<K>]: T;
}>>>;
export type RecordTemplateLiteralType<K extends TTemplateLiteral, T extends TSchema> = IsTemplateLiteralFinite<K> extends true ? RecordTemplateLiteralObjectType<K, T> : TRecord<K, T>;
export type RecordUnionLiteralType<K extends TUnion<TLiteral<string | number>[]>, T extends TSchema> = Static<K> extends string ? Ensure<TObject<{
[X in Static<K>]: T;
}>> : never;
export type RecordLiteralType<K extends TLiteral<string | number>, T extends TSchema> = Ensure<TObject<{
[K2 in K['const']]: T;
}>>;
export type RecordNumberType<K extends TInteger | TNumber, T extends TSchema> = Ensure<TRecord<K, T>>;
export type RecordStringType<K extends TString, T extends TSchema> = Ensure<TRecord<K, T>>;
export type RecordKey = TUnion<TLiteral<string | number>[]> | TLiteral<string | number> | TTemplateLiteral | TInteger | TNumber | TString;
export interface TRecord<K extends RecordKey = RecordKey, T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Record';
static: Record<Static<K>, Static<T, this['params']>>;
type: 'object';
patternProperties: {
[pattern: string]: T;
};
additionalProperties: false;
}
export interface TThis extends TSchema {
[Kind]: 'This';
static: this['params'][0];
$ref: string;
}
export type TRecursiveReduce<T extends TSchema> = Static<T, [TRecursiveReduce<T>]>;
export interface TRecursive<T extends TSchema> extends TSchema {
[Hint]: 'Recursive';
static: TRecursiveReduce<T>;
}
export interface TRef<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Ref';
static: Static<T, this['params']>;
$ref: string;
}
export type TReturnType<T extends TFunction> = T['returns'];
export type TRequiredArray<T extends TSchema[]> = Assert<{
[K in keyof T]: TRequired<Assert<T[K], TSchema>>;
}, TSchema[]>;
export type TRequiredProperties<T extends TProperties> = Evaluate<Assert<{
[K in keyof T]: T[K] extends TReadonlyOptional<infer U> ? TReadonly<U> : T[K] extends TReadonly<infer U> ? TReadonly<U> : T[K] extends TOptional<infer U> ? U : T[K];
}, TProperties>>;
export type TRequired<T extends TSchema> = T extends TRecursive<infer S> ? TRecursive<TRequired<S>> : T extends TComposite<infer S> ? TComposite<TRequiredArray<S>> : T extends TIntersect<infer S> ? TIntersect<TRequiredArray<S>> : T extends TUnion<infer S> ? TUnion<TRequiredArray<S>> : T extends TObject<infer S> ? TObject<TRequiredProperties<S>> : T;
export type StringFormatOption = 'date-time' | 'time' | 'date' | 'email' | 'idn-email' | 'hostname' | 'idn-hostname' | 'ipv4' | 'ipv6' | 'uri' | 'uri-reference' | 'iri' | 'uuid' | 'iri-reference' | 'uri-template' | 'json-pointer' | 'relative-json-pointer' | 'regex';
export interface StringOptions<Format extends string> extends SchemaOptions {
minLength?: number;
maxLength?: number;
pattern?: string;
format?: Format;
contentEncoding?: '7bit' | '8bit' | 'binary' | 'quoted-printable' | 'base64';
contentMediaType?: string;
}
export interface TString<Format extends string = string> extends TSchema, StringOptions<Format> {
[Kind]: 'String';
static: string;
type: 'string';
}
export type SymbolValue = string | number | undefined;
export interface TSymbol extends TSchema, SchemaOptions {
[Kind]: 'Symbol';
static: symbol;
type: 'null';
typeOf: 'Symbol';
}
export type IsTemplateLiteralFiniteCheck<T> = T extends TTemplateLiteral<infer U> ? IsTemplateLiteralFiniteArray<Assert<U, TTemplateLiteralKind[]>> : T extends TUnion<infer U> ? IsTemplateLiteralFiniteArray<Assert<U, TTemplateLiteralKind[]>> : T extends TString ? false : T extends TBoolean ? false : T extends TNumber ? false : T extends TInteger ? false : T extends TBigInt ? false : T extends TLiteral ? true : false;
export type IsTemplateLiteralFiniteArray<T extends TTemplateLiteralKind[]> = T extends [infer L, ...infer R] ? IsTemplateLiteralFiniteCheck<L> extends false ? false : IsTemplateLiteralFiniteArray<Assert<R, TTemplateLiteralKind[]>> : T extends [infer L] ? IsTemplateLiteralFiniteCheck<L> extends false ? false : true : true;
export type IsTemplateLiteralFinite<T> = T extends TTemplateLiteral<infer U> ? IsTemplateLiteralFiniteArray<U> : false;
export type TTemplateLiteralKind = TUnion | TLiteral | TInteger | TTemplateLiteral | TNumber | TBigInt | TString | TBoolean | TNever;
export type TTemplateLiteralConst<T, Acc extends string> = T extends TUnion<infer U> ? {
[K in keyof U]: TTemplateLiteralUnion<Assert<[U[K]], TTemplateLiteralKind[]>, Acc>;
}[number] : T extends TTemplateLiteral ? `${Static<T>}` : T extends TLiteral<infer U> ? `${U}` : T extends TString ? `${string}` : T extends TNumber ? `${number}` : T extends TBigInt ? `${bigint}` : T extends TBoolean ? `${boolean}` : never;
export type TTemplateLiteralUnion<T extends TTemplateLiteralKind[], Acc extends string = ''> = T extends [infer L, ...infer R] ? `${TTemplateLiteralConst<L, Acc>}${TTemplateLiteralUnion<Assert<R, TTemplateLiteralKind[]>, Acc>}` : T extends [infer L] ? `${TTemplateLiteralConst<L, Acc>}${Acc}` : Acc;
export interface TTemplateLiteral<T extends TTemplateLiteralKind[] = TTemplateLiteralKind[]> extends TSchema {
[Kind]: 'TemplateLiteral';
static: TTemplateLiteralUnion<T>;
type: 'string';
pattern: string;
}
export type TTupleIntoArray<T extends TTuple<TSchema[]>> = T extends TTuple<infer R> ? Assert<R, TSchema[]> : never;
export interface TTuple<T extends TSchema[] = TSchema[]> extends TSchema {
[Kind]: 'Tuple';
static: {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : T[K];
};
type: 'array';
items?: T;
additionalItems?: false;
minItems: number;
maxItems: number;
}
export interface TUndefined extends TSchema {
[Kind]: 'Undefined';
static: undefined;
type: 'null';
typeOf: 'Undefined';
}
export type TUnionOfLiteralArray<T extends TLiteral<string>[]> = {
[K in keyof T]: Assert<T[K], TLiteral>['const'];
}[number];
export type TUnionOfLiteral<T extends TUnion<TLiteral<string>[]>> = TUnionOfLiteralArray<T['anyOf']>;
export type TUnionResult<T extends TSchema[]> = T extends [] ? TNever : T extends [infer S] ? S : TUnion<T>;
export type TUnionTemplateLiteral<T extends TTemplateLiteral, S extends string = Static<T>> = (string);
export interface TUnion<T extends TSchema[] = TSchema[]> extends TSchema {
[Kind]: 'Union';
static: {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : never;
}[number];
anyOf: T;
}
export interface Uint8ArrayOptions extends SchemaOptions {
maxByteLength?: number;
minByteLength?: number;
}
export interface TUint8Array extends TSchema, Uint8ArrayOptions {
[Kind]: 'Uint8Array';
static: Uint8Array;
instanceOf: 'Uint8Array';
type: 'object';
}
export interface TUnknown extends TSchema {
[Kind]: 'Unknown';
static: unknown;
}
export interface UnsafeOptions extends SchemaOptions {
[Kind]?: string;
}
export interface TUnsafe<T> extends TSchema {
[Kind]: string;
static: T;
}
export interface TVoid extends TSchema {
[Kind]: 'Void';
static: void;
type: 'null';
typeOf: 'Void';
}
/** Creates a TypeScript static type from a TypeBox type */
export type Static<T extends TSchema, P extends unknown[] = []> = (T & {
params: P;
})['static'];
export type TypeRegistryValidationFunction<TSchema> = (schema: TSchema, value: unknown) => boolean;
/** A registry for user defined types */
export declare namespace TypeRegistry {
/** Returns the entries in this registry */
function Entries(): Map<string, TypeRegistryValidationFunction<any>>;
/** Clears all user defined types */
function Clear(): void;
/** Returns true if this registry contains this kind */
function Has(kind: string): boolean;
/** Sets a validation function for a user defined type */
function Set<TSchema = unknown>(kind: string, func: TypeRegistryValidationFunction<TSchema>): void;
/** Gets a custom validation function for a user defined type */
function Get(kind: string): TypeRegistryValidationFunction<any> | undefined;
}
export type FormatRegistryValidationFunction = (value: string) => boolean;
/** A registry for user defined string formats */
export declare namespace FormatRegistry {
/** Returns the entries in this registry */
function Entries(): Map<string, FormatRegistryValidationFunction>;
/** Clears all user defined string formats */
function Clear(): void;
/** Returns true if the user defined string format exists */
function Has(format: string): boolean;
/** Sets a validation function for a user defined string format */
function Set(format: string, func: FormatRegistryValidationFunction): void;
/** Gets a validation function for a user defined string format */
function Get(format: string): FormatRegistryValidationFunction | undefined;
}
export declare class TypeGuardUnknownTypeError extends Error {
readonly schema: unknown;
constructor(schema: unknown);
}
/** Provides functions to test if JavaScript values are TypeBox types */
export declare namespace TypeGuard {
/** Returns true if the given schema is TAny */
function TAny(schema: unknown): schema is TAny;
/** Returns true if the given schema is TArray */
function TArray(schema: unknown): schema is TArray;
/** Returns true if the given schema is TBigInt */
function TBigInt(schema: unknown): schema is TBigInt;
/** Returns true if the given schema is TBoolean */
function TBoolean(schema: unknown): schema is TBoolean;
/** Returns true if the given schema is TConstructor */
function TConstructor(schema: unknown): schema is TConstructor;
/** Returns true if the given schema is TDate */
function TDate(schema: unknown): schema is TDate;
/** Returns true if the given schema is TFunction */
function TFunction(schema: unknown): schema is TFunction;
/** Returns true if the given schema is TInteger */
function TInteger(schema: unknown): schema is TInteger;
/** Returns true if the given schema is TIntersect */
function TIntersect(schema: unknown): schema is TIntersect;
/** Returns true if the given schema is TKind */
function TKind(schema: unknown): schema is Record<typeof Kind | string, unknown>;
/** Returns true if the given schema is TLiteral */
function TLiteral(schema: unknown): schema is TLiteral;
/** Returns true if the given schema is TNever */
function TNever(schema: unknown): schema is TNever;
/** Returns true if the given schema is TNot */
function TNot(schema: unknown): schema is TNot;
/** Returns true if the given schema is TNull */
function TNull(schema: unknown): schema is TNull;
/** Returns true if the given schema is TNumber */
function TNumber(schema: unknown): schema is TNumber;
/** Returns true if the given schema is TObject */
function TObject(schema: unknown): schema is TObject;
/** Returns true if the given schema is TPromise */
function TPromise(schema: unknown): schema is TPromise;
/** Returns true if the given schema is TRecord */
function TRecord(schema: unknown): schema is TRecord;
/** Returns true if the given schema is TRef */
function TRef(schema: unknown): schema is TRef;
/** Returns true if the given schema is TString */
function TString(schema: unknown): schema is TString;
/** Returns true if the given schema is TSymbol */
function TSymbol(schema: unknown): schema is TSymbol;
/** Returns true if the given schema is TTemplateLiteral */
function TTemplateLiteral(schema: unknown): schema is TTemplateLiteral;
/** Returns true if the given schema is TThis */
function TThis(schema: unknown): schema is TThis;
/** Returns true if the given schema is TTuple */
function TTuple(schema: unknown): schema is TTuple;
/** Returns true if the given schema is TUndefined */
function TUndefined(schema: unknown): schema is TUndefined;
/** Returns true if the given schema is TUnion */
function TUnion(schema: unknown): schema is TUnion;
/** Returns true if the given schema is TUnion<Literal<string>[]> */
function TUnionLiteral(schema: unknown): schema is TUnion<TLiteral<string>[]>;
/** Returns true if the given schema is TUint8Array */
function TUint8Array(schema: unknown): schema is TUint8Array;
/** Returns true if the given schema is TUnknown */
function TUnknown(schema: unknown): schema is TUnknown;
/** Returns true if the given schema is a raw TUnsafe */
function TUnsafe(schema: unknown): schema is TUnsafe<unknown>;
/** Returns true if the given schema is TVoid */
function TVoid(schema: unknown): schema is TVoid;
/** Returns true if this schema has the ReadonlyOptional modifier */
function TReadonlyOptional<T extends TSchema>(schema: T): schema is TReadonlyOptional<T>;
/** Returns true if this schema has the Readonly modifier */
function TReadonly<T extends TSchema>(schema: T): schema is TReadonly<T>;
/** Returns true if this schema has the Optional modifier */
function TOptional<T extends TSchema>(schema: T): schema is TOptional<T>;
/** Returns true if the given schema is TSchema */
function TSchema(schema: unknown): schema is TSchema;
}
/** Fast undefined check used for properties of type undefined */
export declare namespace ExtendsUndefined {
function Check(schema: TSchema): boolean;
}
export declare enum TypeExtendsResult {
Union = 0,
True = 1,
False = 2
}
export declare namespace TypeExtends {
function Extends(left: TSchema, right: TSchema): TypeExtendsResult;
}
/** Specialized Clone for Types */
export declare namespace TypeClone {
/** Clones a type. */
function Clone<T extends TSchema>(schema: T, options: SchemaOptions): T;
}
export declare namespace ObjectMap {
function Map<T = TSchema>(schema: TSchema, callback: (object: TObject) => TObject, options: SchemaOptions): T;
}
export declare namespace KeyResolver {
function Resolve<T extends TSchema>(schema: T): string[];
}
export declare namespace TemplateLiteralPattern {
function Create(kinds: TTemplateLiteralKind[]): string;
}
export declare namespace TemplateLiteralResolver {
function Resolve(template: TTemplateLiteral): TString | TUnion | TLiteral;
}
export declare class TemplateLiteralParserError extends Error {
constructor(message: string);
}
export declare namespace TemplateLiteralParser {
type Expression = And | Or | Const;
type Const = {
type: 'const';
const: string;
};
type And = {
type: 'and';
expr: Expression[];
};
type Or = {
type: 'or';
expr: Expression[];
};
/** Parses a pattern and returns an expression tree */
function Parse(pattern: string): Expression;
/** Parses a pattern and strips forward and trailing ^ and $ */
function ParseExact(pattern: string): Expression;
}
export declare namespace TemplateLiteralFinite {
function Check(expression: TemplateLiteralParser.Expression): boolean;
}
export declare namespace TemplateLiteralGenerator {
function Generate(expression: TemplateLiteralParser.Expression): IterableIterator<string>;
}
export declare class TypeBuilder {
/** `[Utility]` Creates a schema without `static` and `params` types */
protected Create<T>(schema: Omit<T, 'static' | 'params'>): T;
/** `[Standard]` Omits compositing symbols from this schema */
Strict<T extends TSchema>(schema: T): T;
}
export declare class StandardTypeBuilder extends TypeBuilder {
/** `[Modifier]` Creates a Optional property */
Optional<T extends TSchema>(schema: T): TOptional<T>;
/** `[Modifier]` Creates a ReadonlyOptional property */
ReadonlyOptional<T extends TSchema>(schema: T): TReadonlyOptional<T>;
/** `[Modifier]` Creates a Readonly object or property */
Readonly<T extends TSchema>(schema: T): TReadonly<T>;
/** `[Standard]` Creates an Any type */
Any(options?: SchemaOptions): TAny;
/** `[Standard]` Creates an Array type */
Array<T extends TSchema>(items: T, options?: ArrayOptions): TArray<T>;
/** `[Standard]` Creates a Boolean type */
Boolean(options?: SchemaOptions): TBoolean;
/** `[Standard]` Creates a Composite object type. */
Composite<T extends TObject[]>(objects: [...T], options?: ObjectOptions): TComposite<T>;
/** `[Standard]` Creates a Enum type */
Enum<T extends Record<string, string | number>>(item: T, options?: SchemaOptions): TEnum<T>;
/** `[Standard]` A conditional type expression that will return the true type if the left type extends the right */
Extends<L extends TSchema, R extends TSchema, T extends TSchema, U extends TSchema>(left: L, right: R, trueType: T, falseType: U, options?: SchemaOptions): TExtends<L, R, T, U>;
/** `[Standard]` Excludes from the left type any type that is not assignable to the right */
Exclude<L extends TSchema, R extends TSchema>(left: L, right: R, options?: SchemaOptions): TExclude<L, R>;
/** `[Standard]` Extracts from the left type any type that is assignable to the right */
Extract<L extends TSchema, R extends TSchema>(left: L, right: R, options?: SchemaOptions): TExtract<L, R>;
/** `[Standard]` Creates an Integer type */
Integer(options?: NumericOptions<number>): TInteger;
/** `[Standard]` Creates a Intersect type */
Intersect(allOf: [], options?: SchemaOptions): TNever;
/** `[Standard]` Creates a Intersect type */
Intersect<T extends [TSchema]>(allOf: [...T], options?: SchemaOptions): T[0];
Intersect<T extends TSchema[]>(allOf: [...T], options?: IntersectOptions): TIntersect<T>;
/** `[Standard]` Creates a KeyOf type */
KeyOf<T extends TSchema>(schema: T, options?: SchemaOptions): TKeyOf<T>;
/** `[Standard]` Creates a Literal type */
Literal<T extends TLiteralValue>(value: T, options?: SchemaOptions): TLiteral<T>;
/** `[Standard]` Creates a Never type */
Never(options?: SchemaOptions): TNever;
/** `[Standard]` Creates a Not type. The first argument is the disallowed type, the second is the allowed. */
Not<N extends TSchema, T extends TSchema>(not: N, schema: T, options?: SchemaOptions): TNot<N, T>;
/** `[Standard]` Creates a Null type */
Null(options?: SchemaOptions): TNull;
/** `[Standard]` Creates a Number type */
Number(options?: NumericOptions<number>): TNumber;
/** `[Standard]` Creates an Object type */
Object<T extends TProperties>(properties: T, options?: ObjectOptions): TObject<T>;
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
Omit<T extends TSchema, K extends (keyof Static<T>)[]>(schema: T, keys: readonly [...K], options?: SchemaOptions): TOmit<T, K[number]>;
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
Omit<T extends TSchema, K extends TUnion<TLiteral<string>[]>>(schema: T, keys: K, options?: SchemaOptions): TOmit<T, TUnionOfLiteral<K>>;
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
Omit<T extends TSchema, K extends TLiteral<string>>(schema: T, key: K, options?: SchemaOptions): TOmit<T, K['const']>;
/** `[Standard]` Creates a mapped type whose keys are omitted from the given type */
Omit<T extends TSchema, K extends TNever>(schema: T, key: K, options?: SchemaOptions): TOmit<T, never>;
/** `[Standard]` Creates a mapped type where all properties are Optional */
Partial<T extends TSchema>(schema: T, options?: ObjectOptions): TPartial<T>;
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
Pick<T extends TSchema, K extends (keyof Static<T>)[]>(schema: T, keys: readonly [...K], options?: SchemaOptions): TPick<T, K[number]>;
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
Pick<T extends TSchema, K extends TUnion<TLiteral<string>[]>>(schema: T, keys: K, options?: SchemaOptions): TPick<T, TUnionOfLiteral<K>>;
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
Pick<T extends TSchema, K extends TLiteral<string>>(schema: T, key: K, options?: SchemaOptions): TPick<T, K['const']>;
/** `[Standard]` Creates a mapped type whose keys are picked from the given type */
Pick<T extends TSchema, K extends TNever>(schema: T, key: K, options?: SchemaOptions): TPick<T, never>;
/** `[Standard]` Creates a Record type */
Record<K extends TUnion<TLiteral<string | number>[]>, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordUnionLiteralType<K, T>;
/** `[Standard]` Creates a Record type */
Record<K extends TLiteral<string | number>, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordLiteralType<K, T>;
/** `[Standard]` Creates a Record type */
Record<K extends TTemplateLiteral, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordTemplateLiteralType<K, T>;
/** `[Standard]` Creates a Record type */
Record<K extends TInteger | TNumber, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordNumberType<K, T>;
/** `[Standard]` Creates a Record type */
Record<K extends TString, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): RecordStringType<K, T>;
/** `[Standard]` Creates a Recursive type */
Recursive<T extends TSchema>(callback: (thisType: TThis) => T, options?: SchemaOptions): TRecursive<T>;
/** `[Standard]` Creates a Ref type. The referenced type must contain a $id */
Ref<T extends TSchema>(schema: T, options?: SchemaOptions): TRef<T>;
/** `[Standard]` Creates a mapped type where all properties are Required */
Required<T extends TSchema>(schema: T, options?: SchemaOptions): TRequired<T>;
/** `[Standard]` Creates a String type */
String<Format extends string>(options?: StringOptions<StringFormatOption | Format>): TString<Format>;
/** `[Standard]` Creates a template literal type */
TemplateLiteral<T extends TTemplateLiteralKind[]>(kinds: [...T], options?: SchemaOptions): TTemplateLiteral<T>;
/** `[Standard]` Creates a Tuple type */
Tuple<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TTuple<T>;
/** `[Standard]` Creates a Union type */
Union(anyOf: [], options?: SchemaOptions): TNever;
/** `[Standard]` Creates a Union type */
Union<T extends [TSchema]>(anyOf: [...T], options?: SchemaOptions): T[0];
/** `[Standard]` Creates a Union type */
Union<T extends TSchema[]>(anyOf: [...T], options?: SchemaOptions): TUnion<T>;
/** `[Experimental]` Remaps a TemplateLiteral into a Union representation. This function is known to cause TS compiler crashes for finite templates with large generation counts. Use with caution. */
Union<T extends TTemplateLiteral>(template: T): TUnionTemplateLiteral<T>;
/** `[Standard]` Creates an Unknown type */
Unknown(options?: SchemaOptions): TUnknown;
/** `[Standard]` Creates a Unsafe type that infers for the generic argument */
Unsafe<T>(options?: UnsafeOptions): TUnsafe<T>;
}
export declare class ExtendedTypeBuilder extends StandardTypeBuilder {
/** `[Extended]` Creates a BigInt type */
BigInt(options?: NumericOptions<bigint>): TBigInt;
/** `[Extended]` Extracts the ConstructorParameters from the given Constructor type */
ConstructorParameters<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TConstructorParameters<T>;
/** `[Extended]` Creates a Constructor type */
Constructor<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TConstructor<TTupleIntoArray<T>, U>;
/** `[Extended]` Creates a Constructor type */
Constructor<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TConstructor<T, U>;
/** `[Extended]` Creates a Date type */
Date(options?: DateOptions): TDate;
/** `[Extended]` Creates a Function type */
Function<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TFunction<TTupleIntoArray<T>, U>;
/** `[Extended]` Creates a Function type */
Function<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TFunction<T, U>;
/** `[Extended]` Extracts the InstanceType from the given Constructor */
InstanceType<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TInstanceType<T>;
/** `[Extended]` Extracts the Parameters from the given Function type */
Parameters<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TParameters<T>;
/** `[Extended]` Creates a Promise type */
Promise<T extends TSchema>(item: T, options?: SchemaOptions): TPromise<T>;
/** `[Extended]` Creates a regular expression type */
RegEx(regex: RegExp, options?: SchemaOptions): TString;
/** `[Extended]` Extracts the ReturnType from the given Function */
ReturnType<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TReturnType<T>;
/** `[Extended]` Creates a Symbol type */
Symbol(options?: SchemaOptions): TSymbol;
/** `[Extended]` Creates a Undefined type */
Undefined(options?: SchemaOptions): TUndefined;
/** `[Extended]` Creates a Uint8Array type */
Uint8Array(options?: Uint8ArrayOptions): TUint8Array;
/** `[Extended]` Creates a Void type */
Void(options?: SchemaOptions): TVoid;
}
/** JSON Schema TypeBuilder with Static Resolution for TypeScript */
export declare const StandardType: StandardTypeBuilder;
/** JSON Schema TypeBuilder with Static Resolution for TypeScript */
export declare const Type: ExtendedTypeBuilder;

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,30 @@
import * as Types from '../typebox';
export declare class ValueCastReferenceTypeError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
export declare class ValueCastArrayUniqueItemsTypeError extends Error {
readonly schema: Types.TSchema;
readonly value: unknown;
constructor(schema: Types.TSchema, value: unknown);
}
export declare class ValueCastNeverTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCastRecursiveTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCastUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCastDereferenceError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
export declare namespace ValueCast {
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): any;
function Cast<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): Types.Static<T>;
}

View file

@ -0,0 +1,372 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueCast = exports.ValueCastDereferenceError = exports.ValueCastUnknownTypeError = exports.ValueCastRecursiveTypeError = exports.ValueCastNeverTypeError = exports.ValueCastArrayUniqueItemsTypeError = exports.ValueCastReferenceTypeError = void 0;
const Types = require("../typebox");
const create_1 = require("./create");
const check_1 = require("./check");
const clone_1 = require("./clone");
// ----------------------------------------------------------------------------------------------
// Errors
// ----------------------------------------------------------------------------------------------
class ValueCastReferenceTypeError extends Error {
constructor(schema) {
super(`ValueCast: Cannot locate referenced schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueCastReferenceTypeError = ValueCastReferenceTypeError;
class ValueCastArrayUniqueItemsTypeError extends Error {
constructor(schema, value) {
super('ValueCast: Array cast produced invalid data due to uniqueItems constraint');
this.schema = schema;
this.value = value;
}
}
exports.ValueCastArrayUniqueItemsTypeError = ValueCastArrayUniqueItemsTypeError;
class ValueCastNeverTypeError extends Error {
constructor(schema) {
super('ValueCast: Never types cannot be cast');
this.schema = schema;
}
}
exports.ValueCastNeverTypeError = ValueCastNeverTypeError;
class ValueCastRecursiveTypeError extends Error {
constructor(schema) {
super('ValueCast.Recursive: Cannot cast recursive schemas');
this.schema = schema;
}
}
exports.ValueCastRecursiveTypeError = ValueCastRecursiveTypeError;
class ValueCastUnknownTypeError extends Error {
constructor(schema) {
super('ValueCast: Unknown type');
this.schema = schema;
}
}
exports.ValueCastUnknownTypeError = ValueCastUnknownTypeError;
class ValueCastDereferenceError extends Error {
constructor(schema) {
super(`ValueCast: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueCastDereferenceError = ValueCastDereferenceError;
// ----------------------------------------------------------------------------------------------
// The following will score a schema against a value. For objects, the score is the tally of
// points awarded for each property of the value. Property points are (1.0 / propertyCount)
// to prevent large property counts biasing results. Properties that match literal values are
// maximally awarded as literals are typically used as union discriminator fields.
// ----------------------------------------------------------------------------------------------
var UnionCastCreate;
(function (UnionCastCreate) {
function Score(schema, references, value) {
if (schema[Types.Kind] === 'Object' && typeof value === 'object' && value !== null) {
const object = schema;
const keys = Object.keys(value);
const entries = globalThis.Object.entries(object.properties);
const [point, max] = [1 / entries.length, entries.length];
return entries.reduce((acc, [key, schema]) => {
const literal = schema[Types.Kind] === 'Literal' && schema.const === value[key] ? max : 0;
const checks = check_1.ValueCheck.Check(schema, references, value[key]) ? point : 0;
const exists = keys.includes(key) ? point : 0;
return acc + (literal + checks + exists);
}, 0);
}
else {
return check_1.ValueCheck.Check(schema, references, value) ? 1 : 0;
}
}
function Select(union, references, value) {
let [select, best] = [union.anyOf[0], 0];
for (const schema of union.anyOf) {
const score = Score(schema, references, value);
if (score > best) {
select = schema;
best = score;
}
}
return select;
}
function Create(union, references, value) {
if (union.default !== undefined) {
return union.default;
}
else {
const schema = Select(union, references, value);
return ValueCast.Cast(schema, references, value);
}
}
UnionCastCreate.Create = Create;
})(UnionCastCreate || (UnionCastCreate = {}));
var ValueCast;
(function (ValueCast) {
// ----------------------------------------------------------------------------------------------
// Guards
// ----------------------------------------------------------------------------------------------
function IsObject(value) {
return typeof value === 'object' && value !== null && !globalThis.Array.isArray(value);
}
function IsArray(value) {
return typeof value === 'object' && globalThis.Array.isArray(value);
}
function IsNumber(value) {
return typeof value === 'number' && !isNaN(value);
}
function IsString(value) {
return typeof value === 'string';
}
// ----------------------------------------------------------------------------------------------
// Cast
// ----------------------------------------------------------------------------------------------
function Any(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Array(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(value);
const created = IsArray(value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
const minimum = IsNumber(schema.minItems) && created.length < schema.minItems ? [...created, ...globalThis.Array.from({ length: schema.minItems - created.length }, () => null)] : created;
const maximum = IsNumber(schema.maxItems) && minimum.length > schema.maxItems ? minimum.slice(0, schema.maxItems) : minimum;
const casted = maximum.map((value) => Visit(schema.items, references, value));
if (schema.uniqueItems !== true)
return casted;
const unique = [...new Set(casted)];
if (!check_1.ValueCheck.Check(schema, references, unique))
throw new ValueCastArrayUniqueItemsTypeError(schema, unique);
return unique;
}
function BigInt(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Boolean(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Constructor(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return create_1.ValueCreate.Create(schema, references);
const required = new Set(schema.returns.required || []);
const result = function () { };
for (const [key, property] of globalThis.Object.entries(schema.returns.properties)) {
if (!required.has(key) && value.prototype[key] === undefined)
continue;
result.prototype[key] = Visit(property, references, value.prototype[key]);
}
return result;
}
function Date(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Function(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Integer(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Intersect(schema, references, value) {
const created = create_1.ValueCreate.Create(schema, references);
const mapped = IsObject(created) && IsObject(value) ? { ...created, ...value } : value;
return check_1.ValueCheck.Check(schema, references, mapped) ? mapped : create_1.ValueCreate.Create(schema, references);
}
function Literal(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Never(schema, references, value) {
throw new ValueCastNeverTypeError(schema);
}
function Not(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema.allOf[1], references);
}
function Null(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Number(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Object(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return value;
if (value === null || typeof value !== 'object')
return create_1.ValueCreate.Create(schema, references);
const required = new Set(schema.required || []);
const result = {};
for (const [key, property] of globalThis.Object.entries(schema.properties)) {
if (!required.has(key) && value[key] === undefined)
continue;
result[key] = Visit(property, references, value[key]);
}
// additional schema properties
if (typeof schema.additionalProperties === 'object') {
const propertyNames = globalThis.Object.getOwnPropertyNames(schema.properties);
for (const propertyName of globalThis.Object.getOwnPropertyNames(value)) {
if (propertyNames.includes(propertyName))
continue;
result[propertyName] = Visit(schema.additionalProperties, references, value[propertyName]);
}
}
return result;
}
function Promise(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Record(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(value);
if (value === null || typeof value !== 'object' || globalThis.Array.isArray(value) || value instanceof globalThis.Date)
return create_1.ValueCreate.Create(schema, references);
const subschemaPropertyName = globalThis.Object.getOwnPropertyNames(schema.patternProperties)[0];
const subschema = schema.patternProperties[subschemaPropertyName];
const result = {};
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
result[propKey] = Visit(subschema, references, propValue);
}
return result;
}
function Ref(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueCastDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function String(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Symbol(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function TemplateLiteral(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function This(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueCastDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function Tuple(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(value);
if (!globalThis.Array.isArray(value))
return create_1.ValueCreate.Create(schema, references);
if (schema.items === undefined)
return [];
return schema.items.map((schema, index) => Visit(schema, references, value[index]));
}
function Undefined(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Union(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : UnionCastCreate.Create(schema, references, value);
}
function Uint8Array(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Unknown(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Void(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function UserDefined(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references);
}
function Visit(schema, references, value) {
const references_ = IsString(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema[Types.Kind]) {
case 'Any':
return Any(schema_, references_, value);
case 'Array':
return Array(schema_, references_, value);
case 'BigInt':
return BigInt(schema_, references_, value);
case 'Boolean':
return Boolean(schema_, references_, value);
case 'Constructor':
return Constructor(schema_, references_, value);
case 'Date':
return Date(schema_, references_, value);
case 'Function':
return Function(schema_, references_, value);
case 'Integer':
return Integer(schema_, references_, value);
case 'Intersect':
return Intersect(schema_, references_, value);
case 'Literal':
return Literal(schema_, references_, value);
case 'Never':
return Never(schema_, references_, value);
case 'Not':
return Not(schema_, references_, value);
case 'Null':
return Null(schema_, references_, value);
case 'Number':
return Number(schema_, references_, value);
case 'Object':
return Object(schema_, references_, value);
case 'Promise':
return Promise(schema_, references_, value);
case 'Record':
return Record(schema_, references_, value);
case 'Ref':
return Ref(schema_, references_, value);
case 'String':
return String(schema_, references_, value);
case 'Symbol':
return Symbol(schema_, references_, value);
case 'TemplateLiteral':
return TemplateLiteral(schema_, references_, value);
case 'This':
return This(schema_, references_, value);
case 'Tuple':
return Tuple(schema_, references_, value);
case 'Undefined':
return Undefined(schema_, references_, value);
case 'Union':
return Union(schema_, references_, value);
case 'Uint8Array':
return Uint8Array(schema_, references_, value);
case 'Unknown':
return Unknown(schema_, references_, value);
case 'Void':
return Void(schema_, references_, value);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new ValueCastUnknownTypeError(schema_);
return UserDefined(schema_, references_, value);
}
}
ValueCast.Visit = Visit;
function Cast(schema, references, value) {
return Visit(schema, references, clone_1.ValueClone.Clone(value));
}
ValueCast.Cast = Cast;
})(ValueCast = exports.ValueCast || (exports.ValueCast = {}));

View file

@ -0,0 +1,12 @@
import * as Types from '../typebox';
export declare class ValueCheckUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCheckDereferenceError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
export declare namespace ValueCheck {
function Check<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): boolean;
}

View file

@ -0,0 +1,484 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueCheck = exports.ValueCheckDereferenceError = exports.ValueCheckUnknownTypeError = void 0;
const Types = require("../typebox");
const index_1 = require("../system/index");
const hash_1 = require("./hash");
// -------------------------------------------------------------------------
// Errors
// -------------------------------------------------------------------------
class ValueCheckUnknownTypeError extends Error {
constructor(schema) {
super(`ValueCheck: ${schema[Types.Kind] ? `Unknown type '${schema[Types.Kind]}'` : 'Unknown type'}`);
this.schema = schema;
}
}
exports.ValueCheckUnknownTypeError = ValueCheckUnknownTypeError;
class ValueCheckDereferenceError extends Error {
constructor(schema) {
super(`ValueCheck: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueCheckDereferenceError = ValueCheckDereferenceError;
var ValueCheck;
(function (ValueCheck) {
// ----------------------------------------------------------------------
// Guards
// ----------------------------------------------------------------------
function IsBigInt(value) {
return typeof value === 'bigint';
}
function IsInteger(value) {
return globalThis.Number.isInteger(value);
}
function IsString(value) {
return typeof value === 'string';
}
function IsDefined(value) {
return value !== undefined;
}
// ----------------------------------------------------------------------
// Policies
// ----------------------------------------------------------------------
function IsExactOptionalProperty(value, key) {
return index_1.TypeSystem.ExactOptionalPropertyTypes ? key in value : value[key] !== undefined;
}
function IsObject(value) {
const result = typeof value === 'object' && value !== null;
return index_1.TypeSystem.AllowArrayObjects ? result : result && !globalThis.Array.isArray(value);
}
function IsRecordObject(value) {
return IsObject(value) && !(value instanceof globalThis.Date) && !(value instanceof globalThis.Uint8Array);
}
function IsNumber(value) {
const result = typeof value === 'number';
return index_1.TypeSystem.AllowNaN ? result : result && globalThis.Number.isFinite(value);
}
function IsVoid(value) {
const result = value === undefined;
return index_1.TypeSystem.AllowVoidNull ? result || value === null : result;
}
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
function Any(schema, references, value) {
return true;
}
function Array(schema, references, value) {
if (!globalThis.Array.isArray(value)) {
return false;
}
if (IsDefined(schema.minItems) && !(value.length >= schema.minItems)) {
return false;
}
if (IsDefined(schema.maxItems) && !(value.length <= schema.maxItems)) {
return false;
}
// prettier-ignore
if (schema.uniqueItems === true && !((function () { const set = new Set(); for (const element of value) {
const hashed = hash_1.ValueHash.Create(element);
if (set.has(hashed)) {
return false;
}
else {
set.add(hashed);
}
} return true; })())) {
return false;
}
return value.every((value) => Visit(schema.items, references, value));
}
function BigInt(schema, references, value) {
if (!IsBigInt(value)) {
return false;
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === globalThis.BigInt(0))) {
return false;
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
return false;
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
return false;
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
return false;
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Boolean(schema, references, value) {
return typeof value === 'boolean';
}
function Constructor(schema, references, value) {
return Visit(schema.returns, references, value.prototype);
}
function Date(schema, references, value) {
if (!(value instanceof globalThis.Date)) {
return false;
}
if (!IsNumber(value.getTime())) {
return false;
}
if (IsDefined(schema.exclusiveMinimumTimestamp) && !(value.getTime() > schema.exclusiveMinimumTimestamp)) {
return false;
}
if (IsDefined(schema.exclusiveMaximumTimestamp) && !(value.getTime() < schema.exclusiveMaximumTimestamp)) {
return false;
}
if (IsDefined(schema.minimumTimestamp) && !(value.getTime() >= schema.minimumTimestamp)) {
return false;
}
if (IsDefined(schema.maximumTimestamp) && !(value.getTime() <= schema.maximumTimestamp)) {
return false;
}
return true;
}
function Function(schema, references, value) {
return typeof value === 'function';
}
function Integer(schema, references, value) {
if (!IsInteger(value)) {
return false;
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
return false;
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
return false;
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
return false;
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
return false;
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Intersect(schema, references, value) {
if (!schema.allOf.every((schema) => Visit(schema, references, value))) {
return false;
}
else if (schema.unevaluatedProperties === false) {
const schemaKeys = Types.KeyResolver.Resolve(schema);
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
return valueKeys.every((key) => schemaKeys.includes(key));
}
else if (Types.TypeGuard.TSchema(schema.unevaluatedProperties)) {
const schemaKeys = Types.KeyResolver.Resolve(schema);
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
return valueKeys.every((key) => schemaKeys.includes(key) || Visit(schema.unevaluatedProperties, references, value[key]));
}
else {
return true;
}
}
function Literal(schema, references, value) {
return value === schema.const;
}
function Never(schema, references, value) {
return false;
}
function Not(schema, references, value) {
return !Visit(schema.allOf[0].not, references, value) && Visit(schema.allOf[1], references, value);
}
function Null(schema, references, value) {
return value === null;
}
function Number(schema, references, value) {
if (!IsNumber(value)) {
return false;
}
if (IsDefined(schema.multipleOf) && !(value % schema.multipleOf === 0)) {
return false;
}
if (IsDefined(schema.exclusiveMinimum) && !(value > schema.exclusiveMinimum)) {
return false;
}
if (IsDefined(schema.exclusiveMaximum) && !(value < schema.exclusiveMaximum)) {
return false;
}
if (IsDefined(schema.minimum) && !(value >= schema.minimum)) {
return false;
}
if (IsDefined(schema.maximum) && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Object(schema, references, value) {
if (!IsObject(value)) {
return false;
}
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
return false;
}
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
return false;
}
const knownKeys = globalThis.Object.getOwnPropertyNames(schema.properties);
for (const knownKey of knownKeys) {
const property = schema.properties[knownKey];
if (schema.required && schema.required.includes(knownKey)) {
if (!Visit(property, references, value[knownKey])) {
return false;
}
if (Types.ExtendsUndefined.Check(property)) {
return knownKey in value;
}
}
else {
if (IsExactOptionalProperty(value, knownKey) && !Visit(property, references, value[knownKey])) {
return false;
}
}
}
if (schema.additionalProperties === false) {
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
// optimization: value is valid if schemaKey length matches the valueKey length
if (schema.required && schema.required.length === knownKeys.length && valueKeys.length === knownKeys.length) {
return true;
}
else {
return valueKeys.every((valueKey) => knownKeys.includes(valueKey));
}
}
else if (typeof schema.additionalProperties === 'object') {
const valueKeys = globalThis.Object.getOwnPropertyNames(value);
return valueKeys.every((key) => knownKeys.includes(key) || Visit(schema.additionalProperties, references, value[key]));
}
else {
return true;
}
}
function Promise(schema, references, value) {
return typeof value === 'object' && typeof value.then === 'function';
}
function Record(schema, references, value) {
if (!IsRecordObject(value)) {
return false;
}
if (IsDefined(schema.minProperties) && !(globalThis.Object.getOwnPropertyNames(value).length >= schema.minProperties)) {
return false;
}
if (IsDefined(schema.maxProperties) && !(globalThis.Object.getOwnPropertyNames(value).length <= schema.maxProperties)) {
return false;
}
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern);
if (!globalThis.Object.getOwnPropertyNames(value).every((key) => regex.test(key))) {
return false;
}
for (const propValue of globalThis.Object.values(value)) {
if (!Visit(valueSchema, references, propValue))
return false;
}
return true;
}
function Ref(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueCheckDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function String(schema, references, value) {
if (!IsString(value)) {
return false;
}
if (IsDefined(schema.minLength)) {
if (!(value.length >= schema.minLength))
return false;
}
if (IsDefined(schema.maxLength)) {
if (!(value.length <= schema.maxLength))
return false;
}
if (IsDefined(schema.pattern)) {
const regex = new RegExp(schema.pattern);
if (!regex.test(value))
return false;
}
if (IsDefined(schema.format)) {
if (!Types.FormatRegistry.Has(schema.format))
return false;
const func = Types.FormatRegistry.Get(schema.format);
return func(value);
}
return true;
}
function Symbol(schema, references, value) {
if (!(typeof value === 'symbol')) {
return false;
}
return true;
}
function TemplateLiteral(schema, references, value) {
if (!IsString(value)) {
return false;
}
return new RegExp(schema.pattern).test(value);
}
function This(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueCheckDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function Tuple(schema, references, value) {
if (!globalThis.Array.isArray(value)) {
return false;
}
if (schema.items === undefined && !(value.length === 0)) {
return false;
}
if (!(value.length === schema.maxItems)) {
return false;
}
if (!schema.items) {
return true;
}
for (let i = 0; i < schema.items.length; i++) {
if (!Visit(schema.items[i], references, value[i]))
return false;
}
return true;
}
function Undefined(schema, references, value) {
return value === undefined;
}
function Union(schema, references, value) {
return schema.anyOf.some((inner) => Visit(inner, references, value));
}
function Uint8Array(schema, references, value) {
if (!(value instanceof globalThis.Uint8Array)) {
return false;
}
if (IsDefined(schema.maxByteLength) && !(value.length <= schema.maxByteLength)) {
return false;
}
if (IsDefined(schema.minByteLength) && !(value.length >= schema.minByteLength)) {
return false;
}
return true;
}
function Unknown(schema, references, value) {
return true;
}
function Void(schema, references, value) {
return IsVoid(value);
}
function UserDefined(schema, references, value) {
if (!Types.TypeRegistry.Has(schema[Types.Kind]))
return false;
const func = Types.TypeRegistry.Get(schema[Types.Kind]);
return func(schema, value);
}
function Visit(schema, references, value) {
const references_ = IsDefined(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema_[Types.Kind]) {
case 'Any':
return Any(schema_, references_, value);
case 'Array':
return Array(schema_, references_, value);
case 'BigInt':
return BigInt(schema_, references_, value);
case 'Boolean':
return Boolean(schema_, references_, value);
case 'Constructor':
return Constructor(schema_, references_, value);
case 'Date':
return Date(schema_, references_, value);
case 'Function':
return Function(schema_, references_, value);
case 'Integer':
return Integer(schema_, references_, value);
case 'Intersect':
return Intersect(schema_, references_, value);
case 'Literal':
return Literal(schema_, references_, value);
case 'Never':
return Never(schema_, references_, value);
case 'Not':
return Not(schema_, references_, value);
case 'Null':
return Null(schema_, references_, value);
case 'Number':
return Number(schema_, references_, value);
case 'Object':
return Object(schema_, references_, value);
case 'Promise':
return Promise(schema_, references_, value);
case 'Record':
return Record(schema_, references_, value);
case 'Ref':
return Ref(schema_, references_, value);
case 'String':
return String(schema_, references_, value);
case 'Symbol':
return Symbol(schema_, references_, value);
case 'TemplateLiteral':
return TemplateLiteral(schema_, references_, value);
case 'This':
return This(schema_, references_, value);
case 'Tuple':
return Tuple(schema_, references_, value);
case 'Undefined':
return Undefined(schema_, references_, value);
case 'Union':
return Union(schema_, references_, value);
case 'Uint8Array':
return Uint8Array(schema_, references_, value);
case 'Unknown':
return Unknown(schema_, references_, value);
case 'Void':
return Void(schema_, references_, value);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new ValueCheckUnknownTypeError(schema_);
return UserDefined(schema_, references_, value);
}
}
// -------------------------------------------------------------------------
// Check
// -------------------------------------------------------------------------
function Check(schema, references, value) {
return Visit(schema, references, value);
}
ValueCheck.Check = Check;
})(ValueCheck = exports.ValueCheck || (exports.ValueCheck = {}));

View file

@ -0,0 +1,3 @@
export declare namespace ValueClone {
function Clone<T extends unknown>(value: T): T;
}

View file

@ -0,0 +1,71 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueClone = void 0;
const is_1 = require("./is");
var ValueClone;
(function (ValueClone) {
function Array(value) {
return value.map((element) => Clone(element));
}
function Date(value) {
return new globalThis.Date(value.toISOString());
}
function Object(value) {
const keys = [...globalThis.Object.keys(value), ...globalThis.Object.getOwnPropertySymbols(value)];
return keys.reduce((acc, key) => ({ ...acc, [key]: Clone(value[key]) }), {});
}
function TypedArray(value) {
return value.slice();
}
function Value(value) {
return value;
}
function Clone(value) {
if (is_1.Is.Date(value)) {
return Date(value);
}
else if (is_1.Is.Object(value)) {
return Object(value);
}
else if (is_1.Is.Array(value)) {
return Array(value);
}
else if (is_1.Is.TypedArray(value)) {
return TypedArray(value);
}
else if (is_1.Is.Value(value)) {
return Value(value);
}
else {
throw new Error('ValueClone: Unable to clone value');
}
}
ValueClone.Clone = Clone;
})(ValueClone = exports.ValueClone || (exports.ValueClone = {}));

View file

@ -0,0 +1,13 @@
import * as Types from '../typebox';
export declare class ValueConvertUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueConvertDereferenceError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
export declare namespace ValueConvert {
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): unknown;
function Convert<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): unknown;
}

View file

@ -0,0 +1,372 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueConvert = exports.ValueConvertDereferenceError = exports.ValueConvertUnknownTypeError = void 0;
const Types = require("../typebox");
const clone_1 = require("./clone");
const check_1 = require("./check");
// ----------------------------------------------------------------------------------------------
// Errors
// ----------------------------------------------------------------------------------------------
class ValueConvertUnknownTypeError extends Error {
constructor(schema) {
super('ValueConvert: Unknown type');
this.schema = schema;
}
}
exports.ValueConvertUnknownTypeError = ValueConvertUnknownTypeError;
class ValueConvertDereferenceError extends Error {
constructor(schema) {
super(`ValueConvert: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueConvertDereferenceError = ValueConvertDereferenceError;
var ValueConvert;
(function (ValueConvert) {
// ----------------------------------------------------------------------------------------------
// Guards
// ----------------------------------------------------------------------------------------------
function IsObject(value) {
return typeof value === 'object' && value !== null && !globalThis.Array.isArray(value);
}
function IsArray(value) {
return typeof value === 'object' && globalThis.Array.isArray(value);
}
function IsDate(value) {
return typeof value === 'object' && value instanceof globalThis.Date;
}
function IsSymbol(value) {
return typeof value === 'symbol';
}
function IsString(value) {
return typeof value === 'string';
}
function IsBoolean(value) {
return typeof value === 'boolean';
}
function IsBigInt(value) {
return typeof value === 'bigint';
}
function IsNumber(value) {
return typeof value === 'number' && !isNaN(value);
}
function IsStringNumeric(value) {
return IsString(value) && !isNaN(value) && !isNaN(parseFloat(value));
}
function IsValueToString(value) {
return IsBigInt(value) || IsBoolean(value) || IsNumber(value);
}
function IsValueTrue(value) {
return value === true || (IsNumber(value) && value === 1) || (IsBigInt(value) && value === globalThis.BigInt('1')) || (IsString(value) && (value.toLowerCase() === 'true' || value === '1'));
}
function IsValueFalse(value) {
return value === false || (IsNumber(value) && value === 0) || (IsBigInt(value) && value === globalThis.BigInt('0')) || (IsString(value) && (value.toLowerCase() === 'false' || value === '0'));
}
function IsTimeStringWithTimeZone(value) {
return IsString(value) && /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i.test(value);
}
function IsTimeStringWithoutTimeZone(value) {
return IsString(value) && /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)?$/i.test(value);
}
function IsDateTimeStringWithTimeZone(value) {
return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i.test(value);
}
function IsDateTimeStringWithoutTimeZone(value) {
return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)?$/i.test(value);
}
function IsDateString(value) {
return IsString(value) && /^\d\d\d\d-[0-1]\d-[0-3]\d$/i.test(value);
}
// ----------------------------------------------------------------------------------------------
// Convert
// ----------------------------------------------------------------------------------------------
function TryConvertLiteralString(value, target) {
const conversion = TryConvertString(value);
return conversion === target ? conversion : value;
}
function TryConvertLiteralNumber(value, target) {
const conversion = TryConvertNumber(value);
return conversion === target ? conversion : value;
}
function TryConvertLiteralBoolean(value, target) {
const conversion = TryConvertBoolean(value);
return conversion === target ? conversion : value;
}
function TryConvertLiteral(schema, value) {
if (typeof schema.const === 'string') {
return TryConvertLiteralString(value, schema.const);
}
else if (typeof schema.const === 'number') {
return TryConvertLiteralNumber(value, schema.const);
}
else if (typeof schema.const === 'boolean') {
return TryConvertLiteralBoolean(value, schema.const);
}
else {
return clone_1.ValueClone.Clone(value);
}
}
function TryConvertBoolean(value) {
return IsValueTrue(value) ? true : IsValueFalse(value) ? false : value;
}
function TryConvertBigInt(value) {
return IsStringNumeric(value) ? globalThis.BigInt(parseInt(value)) : IsNumber(value) ? globalThis.BigInt(value | 0) : IsValueFalse(value) ? 0 : IsValueTrue(value) ? 1 : value;
}
function TryConvertString(value) {
return IsValueToString(value) ? value.toString() : value;
}
function TryConvertNumber(value) {
return IsStringNumeric(value) ? parseFloat(value) : IsValueTrue(value) ? 1 : IsValueFalse(value) ? 0 : value;
}
function TryConvertInteger(value) {
return IsStringNumeric(value) ? parseInt(value) : IsNumber(value) ? value | 0 : IsValueTrue(value) ? 1 : IsValueFalse(value) ? 0 : value;
}
function TryConvertNull(value) {
return IsString(value) && value.toLowerCase() === 'null' ? null : value;
}
function TryConvertUndefined(value) {
return IsString(value) && value === 'undefined' ? undefined : value;
}
function TryConvertDate(value) {
// note: this function may return an invalid dates for the regex tests
// above. Invalid dates will however be checked during the casting
// function and will return a epoch date if invalid. Consider better
// string parsing for the iso dates in future revisions.
return IsDate(value)
? value
: IsNumber(value)
? new globalThis.Date(value)
: IsValueTrue(value)
? new globalThis.Date(1)
: IsValueFalse(value)
? new globalThis.Date(0)
: IsStringNumeric(value)
? new globalThis.Date(parseInt(value))
: IsTimeStringWithoutTimeZone(value)
? new globalThis.Date(`1970-01-01T${value}.000Z`)
: IsTimeStringWithTimeZone(value)
? new globalThis.Date(`1970-01-01T${value}`)
: IsDateTimeStringWithoutTimeZone(value)
? new globalThis.Date(`${value}.000Z`)
: IsDateTimeStringWithTimeZone(value)
? new globalThis.Date(value)
: IsDateString(value)
? new globalThis.Date(`${value}T00:00:00.000Z`)
: value;
}
// ----------------------------------------------------------------------------------------------
// Cast
// ----------------------------------------------------------------------------------------------
function Any(schema, references, value) {
return value;
}
function Array(schema, references, value) {
if (IsArray(value)) {
return value.map((value) => Visit(schema.items, references, value));
}
return value;
}
function BigInt(schema, references, value) {
return TryConvertBigInt(value);
}
function Boolean(schema, references, value) {
return TryConvertBoolean(value);
}
function Constructor(schema, references, value) {
return clone_1.ValueClone.Clone(value);
}
function Date(schema, references, value) {
return TryConvertDate(value);
}
function Function(schema, references, value) {
return value;
}
function Integer(schema, references, value) {
return TryConvertInteger(value);
}
function Intersect(schema, references, value) {
return value;
}
function Literal(schema, references, value) {
return TryConvertLiteral(schema, value);
}
function Never(schema, references, value) {
return value;
}
function Null(schema, references, value) {
return TryConvertNull(value);
}
function Number(schema, references, value) {
return TryConvertNumber(value);
}
function Object(schema, references, value) {
if (IsObject(value))
return globalThis.Object.keys(schema.properties).reduce((acc, key) => {
return value[key] !== undefined ? { ...acc, [key]: Visit(schema.properties[key], references, value[key]) } : { ...acc };
}, value);
return value;
}
function Promise(schema, references, value) {
return value;
}
function Record(schema, references, value) {
const propertyKey = globalThis.Object.getOwnPropertyNames(schema.patternProperties)[0];
const property = schema.patternProperties[propertyKey];
const result = {};
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
result[propKey] = Visit(property, references, propValue);
}
return result;
}
function Ref(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueConvertDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function String(schema, references, value) {
return TryConvertString(value);
}
function Symbol(schema, references, value) {
return value;
}
function TemplateLiteral(schema, references, value) {
return value;
}
function This(schema, references, value) {
const index = references.findIndex((foreign) => foreign.$id === schema.$ref);
if (index === -1)
throw new ValueConvertDereferenceError(schema);
const target = references[index];
return Visit(target, references, value);
}
function Tuple(schema, references, value) {
if (IsArray(value) && schema.items !== undefined) {
return value.map((value, index) => {
return index < schema.items.length ? Visit(schema.items[index], references, value) : value;
});
}
return value;
}
function Undefined(schema, references, value) {
return TryConvertUndefined(value);
}
function Union(schema, references, value) {
for (const subschema of schema.anyOf) {
const converted = Visit(subschema, references, value);
if (check_1.ValueCheck.Check(subschema, references, converted)) {
return converted;
}
}
return value;
}
function Uint8Array(schema, references, value) {
return value;
}
function Unknown(schema, references, value) {
return value;
}
function Void(schema, references, value) {
return value;
}
function UserDefined(schema, references, value) {
return value;
}
function Visit(schema, references, value) {
const references_ = IsString(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema[Types.Kind]) {
case 'Any':
return Any(schema_, references_, value);
case 'Array':
return Array(schema_, references_, value);
case 'BigInt':
return BigInt(schema_, references_, value);
case 'Boolean':
return Boolean(schema_, references_, value);
case 'Constructor':
return Constructor(schema_, references_, value);
case 'Date':
return Date(schema_, references_, value);
case 'Function':
return Function(schema_, references_, value);
case 'Integer':
return Integer(schema_, references_, value);
case 'Intersect':
return Intersect(schema_, references_, value);
case 'Literal':
return Literal(schema_, references_, value);
case 'Never':
return Never(schema_, references_, value);
case 'Null':
return Null(schema_, references_, value);
case 'Number':
return Number(schema_, references_, value);
case 'Object':
return Object(schema_, references_, value);
case 'Promise':
return Promise(schema_, references_, value);
case 'Record':
return Record(schema_, references_, value);
case 'Ref':
return Ref(schema_, references_, value);
case 'String':
return String(schema_, references_, value);
case 'Symbol':
return Symbol(schema_, references_, value);
case 'TemplateLiteral':
return TemplateLiteral(schema_, references_, value);
case 'This':
return This(schema_, references_, value);
case 'Tuple':
return Tuple(schema_, references_, value);
case 'Undefined':
return Undefined(schema_, references_, value);
case 'Union':
return Union(schema_, references_, value);
case 'Uint8Array':
return Uint8Array(schema_, references_, value);
case 'Unknown':
return Unknown(schema_, references_, value);
case 'Void':
return Void(schema_, references_, value);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new ValueConvertUnknownTypeError(schema_);
return UserDefined(schema_, references_, value);
}
}
ValueConvert.Visit = Visit;
function Convert(schema, references, value) {
return Visit(schema, references, clone_1.ValueClone.Clone(value));
}
ValueConvert.Convert = Convert;
})(ValueConvert = exports.ValueConvert || (exports.ValueConvert = {}));

View file

@ -0,0 +1,26 @@
import * as Types from '../typebox';
export declare class ValueCreateUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCreateNeverTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCreateIntersectTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCreateTempateLiteralTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare class ValueCreateDereferenceError extends Error {
readonly schema: Types.TRef | Types.TThis;
constructor(schema: Types.TRef | Types.TThis);
}
export declare namespace ValueCreate {
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit(schema: Types.TSchema, references: Types.TSchema[]): unknown;
function Create<T extends Types.TSchema>(schema: T, references: Types.TSchema[]): Types.Static<T>;
}

View file

@ -0,0 +1,480 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueCreate = exports.ValueCreateDereferenceError = exports.ValueCreateTempateLiteralTypeError = exports.ValueCreateIntersectTypeError = exports.ValueCreateNeverTypeError = exports.ValueCreateUnknownTypeError = void 0;
const Types = require("../typebox");
const check_1 = require("./check");
// --------------------------------------------------------------------------
// Errors
// --------------------------------------------------------------------------
class ValueCreateUnknownTypeError extends Error {
constructor(schema) {
super('ValueCreate: Unknown type');
this.schema = schema;
}
}
exports.ValueCreateUnknownTypeError = ValueCreateUnknownTypeError;
class ValueCreateNeverTypeError extends Error {
constructor(schema) {
super('ValueCreate: Never types cannot be created');
this.schema = schema;
}
}
exports.ValueCreateNeverTypeError = ValueCreateNeverTypeError;
class ValueCreateIntersectTypeError extends Error {
constructor(schema) {
super('ValueCreate: Intersect produced invalid value. Consider using a default value.');
this.schema = schema;
}
}
exports.ValueCreateIntersectTypeError = ValueCreateIntersectTypeError;
class ValueCreateTempateLiteralTypeError extends Error {
constructor(schema) {
super('ValueCreate: Can only create template literal values from patterns that produce finite sequences. Consider using a default value.');
this.schema = schema;
}
}
exports.ValueCreateTempateLiteralTypeError = ValueCreateTempateLiteralTypeError;
class ValueCreateDereferenceError extends Error {
constructor(schema) {
super(`ValueCreate: Unable to dereference schema with $id '${schema.$ref}'`);
this.schema = schema;
}
}
exports.ValueCreateDereferenceError = ValueCreateDereferenceError;
// --------------------------------------------------------------------------
// ValueCreate
// --------------------------------------------------------------------------
var ValueCreate;
(function (ValueCreate) {
// --------------------------------------------------------
// Guards
// --------------------------------------------------------
function IsString(value) {
return typeof value === 'string';
}
// --------------------------------------------------------
// Types
// --------------------------------------------------------
function Any(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return {};
}
}
function Array(schema, references) {
if (schema.uniqueItems === true && schema.default === undefined) {
throw new Error('ValueCreate.Array: Arrays with uniqueItems require a default value');
}
else if ('default' in schema) {
return schema.default;
}
else if (schema.minItems !== undefined) {
return globalThis.Array.from({ length: schema.minItems }).map((item) => {
return ValueCreate.Create(schema.items, references);
});
}
else {
return [];
}
}
function BigInt(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return globalThis.BigInt(0);
}
}
function Boolean(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return false;
}
}
function Constructor(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
const value = ValueCreate.Create(schema.returns, references);
if (typeof value === 'object' && !globalThis.Array.isArray(value)) {
return class {
constructor() {
for (const [key, val] of globalThis.Object.entries(value)) {
const self = this;
self[key] = val;
}
}
};
}
else {
return class {
};
}
}
}
function Date(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if (schema.minimumTimestamp !== undefined) {
return new globalThis.Date(schema.minimumTimestamp);
}
else {
return new globalThis.Date(0);
}
}
function Function(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return () => ValueCreate.Create(schema.returns, references);
}
}
function Integer(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if (schema.minimum !== undefined) {
return schema.minimum;
}
else {
return 0;
}
}
function Intersect(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
// Note: The best we can do here is attempt to instance each sub type and apply through object assign. For non-object
// sub types, we just escape the assignment and just return the value. In the latter case, this is typically going to
// be a consequence of an illogical intersection.
const value = schema.allOf.reduce((acc, schema) => {
const next = Visit(schema, references);
return typeof next === 'object' ? { ...acc, ...next } : next;
}, {});
if (!check_1.ValueCheck.Check(schema, references, value))
throw new ValueCreateIntersectTypeError(schema);
return value;
}
}
function Literal(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return schema.const;
}
}
function Never(schema, references) {
throw new ValueCreateNeverTypeError(schema);
}
function Not(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return Visit(schema.allOf[1], references);
}
}
function Null(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return null;
}
}
function Number(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if (schema.minimum !== undefined) {
return schema.minimum;
}
else {
return 0;
}
}
function Object(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
const required = new Set(schema.required);
return (schema.default ||
globalThis.Object.entries(schema.properties).reduce((acc, [key, schema]) => {
return required.has(key) ? { ...acc, [key]: ValueCreate.Create(schema, references) } : { ...acc };
}, {}));
}
}
function Promise(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return globalThis.Promise.resolve(ValueCreate.Create(schema.item, references));
}
}
function Record(schema, references) {
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
if ('default' in schema) {
return schema.default;
}
else if (!(keyPattern === Types.PatternStringExact || keyPattern === Types.PatternNumberExact)) {
const propertyKeys = keyPattern.slice(1, keyPattern.length - 1).split('|');
return propertyKeys.reduce((acc, key) => {
return { ...acc, [key]: Create(valueSchema, references) };
}, {});
}
else {
return {};
}
}
function Ref(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
const index = references.findIndex((foreign) => foreign.$id === schema.$id);
if (index === -1)
throw new ValueCreateDereferenceError(schema);
const target = references[index];
return Visit(target, references);
}
}
function String(schema, references) {
if (schema.pattern !== undefined) {
if (!('default' in schema)) {
throw new Error('ValueCreate.String: String types with patterns must specify a default value');
}
else {
return schema.default;
}
}
else if (schema.format !== undefined) {
if (!('default' in schema)) {
throw new Error('ValueCreate.String: String types with formats must specify a default value');
}
else {
return schema.default;
}
}
else {
if ('default' in schema) {
return schema.default;
}
else if (schema.minLength !== undefined) {
return globalThis.Array.from({ length: schema.minLength })
.map(() => '.')
.join('');
}
else {
return '';
}
}
}
function Symbol(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if ('value' in schema) {
return globalThis.Symbol.for(schema.value);
}
else {
return globalThis.Symbol();
}
}
function TemplateLiteral(schema, references) {
if ('default' in schema) {
return schema.default;
}
const expression = Types.TemplateLiteralParser.ParseExact(schema.pattern);
if (!Types.TemplateLiteralFinite.Check(expression))
throw new ValueCreateTempateLiteralTypeError(schema);
const sequence = Types.TemplateLiteralGenerator.Generate(expression);
return sequence.next().value;
}
function This(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
const index = references.findIndex((foreign) => foreign.$id === schema.$id);
if (index === -1)
throw new ValueCreateDereferenceError(schema);
const target = references[index];
return Visit(target, references);
}
}
function Tuple(schema, references) {
if ('default' in schema) {
return schema.default;
}
if (schema.items === undefined) {
return [];
}
else {
return globalThis.Array.from({ length: schema.minItems }).map((_, index) => ValueCreate.Create(schema.items[index], references));
}
}
function Undefined(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return undefined;
}
}
function Union(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if (schema.anyOf.length === 0) {
throw new Error('ValueCreate.Union: Cannot create Union with zero variants');
}
else {
return ValueCreate.Create(schema.anyOf[0], references);
}
}
function Uint8Array(schema, references) {
if ('default' in schema) {
return schema.default;
}
else if (schema.minByteLength !== undefined) {
return new globalThis.Uint8Array(schema.minByteLength);
}
else {
return new globalThis.Uint8Array(0);
}
}
function Unknown(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return {};
}
}
function Void(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
return void 0;
}
}
function UserDefined(schema, references) {
if ('default' in schema) {
return schema.default;
}
else {
throw new Error('ValueCreate.UserDefined: User defined types must specify a default value');
}
}
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit(schema, references) {
const references_ = IsString(schema.$id) ? [...references, schema] : references;
const schema_ = schema;
switch (schema_[Types.Kind]) {
case 'Any':
return Any(schema_, references_);
case 'Array':
return Array(schema_, references_);
case 'BigInt':
return BigInt(schema_, references_);
case 'Boolean':
return Boolean(schema_, references_);
case 'Constructor':
return Constructor(schema_, references_);
case 'Date':
return Date(schema_, references_);
case 'Function':
return Function(schema_, references_);
case 'Integer':
return Integer(schema_, references_);
case 'Intersect':
return Intersect(schema_, references_);
case 'Literal':
return Literal(schema_, references_);
case 'Never':
return Never(schema_, references_);
case 'Not':
return Not(schema_, references_);
case 'Null':
return Null(schema_, references_);
case 'Number':
return Number(schema_, references_);
case 'Object':
return Object(schema_, references_);
case 'Promise':
return Promise(schema_, references_);
case 'Record':
return Record(schema_, references_);
case 'Ref':
return Ref(schema_, references_);
case 'String':
return String(schema_, references_);
case 'Symbol':
return Symbol(schema_, references_);
case 'TemplateLiteral':
return TemplateLiteral(schema_, references_);
case 'This':
return This(schema_, references_);
case 'Tuple':
return Tuple(schema_, references_);
case 'Undefined':
return Undefined(schema_, references_);
case 'Union':
return Union(schema_, references_);
case 'Uint8Array':
return Uint8Array(schema_, references_);
case 'Unknown':
return Unknown(schema_, references_);
case 'Void':
return Void(schema_, references_);
default:
if (!Types.TypeRegistry.Has(schema_[Types.Kind]))
throw new ValueCreateUnknownTypeError(schema_);
return UserDefined(schema_, references_);
}
}
ValueCreate.Visit = Visit;
function Create(schema, references) {
return Visit(schema, references);
}
ValueCreate.Create = Create;
})(ValueCreate = exports.ValueCreate || (exports.ValueCreate = {}));

View file

@ -0,0 +1,43 @@
import { Static } from '../typebox';
export type Insert = Static<typeof Insert>;
export declare const Insert: import("../typebox").TObject<{
type: import("../typebox").TLiteral<"insert">;
path: import("../typebox").TString<string>;
value: import("../typebox").TUnknown;
}>;
export type Update = Static<typeof Update>;
export declare const Update: import("../typebox").TObject<{
type: import("../typebox").TLiteral<"update">;
path: import("../typebox").TString<string>;
value: import("../typebox").TUnknown;
}>;
export type Delete = Static<typeof Delete>;
export declare const Delete: import("../typebox").TObject<{
type: import("../typebox").TLiteral<"delete">;
path: import("../typebox").TString<string>;
}>;
export type Edit = Static<typeof Edit>;
export declare const Edit: import("../typebox").TUnion<[import("../typebox").TObject<{
type: import("../typebox").TLiteral<"insert">;
path: import("../typebox").TString<string>;
value: import("../typebox").TUnknown;
}>, import("../typebox").TObject<{
type: import("../typebox").TLiteral<"update">;
path: import("../typebox").TString<string>;
value: import("../typebox").TUnknown;
}>, import("../typebox").TObject<{
type: import("../typebox").TLiteral<"delete">;
path: import("../typebox").TString<string>;
}>]>;
export declare class ValueDeltaObjectWithSymbolKeyError extends Error {
readonly key: unknown;
constructor(key: unknown);
}
export declare class ValueDeltaUnableToDiffUnknownValue extends Error {
readonly value: unknown;
constructor(value: unknown);
}
export declare namespace ValueDelta {
function Diff(current: unknown, next: unknown): Edit[];
function Patch<T = any>(current: unknown, edits: Edit[]): T;
}

View file

@ -0,0 +1,204 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueDelta = exports.ValueDeltaUnableToDiffUnknownValue = exports.ValueDeltaObjectWithSymbolKeyError = exports.Edit = exports.Delete = exports.Update = exports.Insert = void 0;
const typebox_1 = require("../typebox");
const is_1 = require("./is");
const clone_1 = require("./clone");
const pointer_1 = require("./pointer");
exports.Insert = typebox_1.Type.Object({
type: typebox_1.Type.Literal('insert'),
path: typebox_1.Type.String(),
value: typebox_1.Type.Unknown(),
});
exports.Update = typebox_1.Type.Object({
type: typebox_1.Type.Literal('update'),
path: typebox_1.Type.String(),
value: typebox_1.Type.Unknown(),
});
exports.Delete = typebox_1.Type.Object({
type: typebox_1.Type.Literal('delete'),
path: typebox_1.Type.String(),
});
exports.Edit = typebox_1.Type.Union([exports.Insert, exports.Update, exports.Delete]);
// ---------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------
class ValueDeltaObjectWithSymbolKeyError extends Error {
constructor(key) {
super('ValueDelta: Cannot diff objects with symbol keys');
this.key = key;
}
}
exports.ValueDeltaObjectWithSymbolKeyError = ValueDeltaObjectWithSymbolKeyError;
class ValueDeltaUnableToDiffUnknownValue extends Error {
constructor(value) {
super('ValueDelta: Unable to create diff edits for unknown value');
this.value = value;
}
}
exports.ValueDeltaUnableToDiffUnknownValue = ValueDeltaUnableToDiffUnknownValue;
// ---------------------------------------------------------------------
// ValueDelta
// ---------------------------------------------------------------------
var ValueDelta;
(function (ValueDelta) {
// ---------------------------------------------------------------------
// Edits
// ---------------------------------------------------------------------
function Update(path, value) {
return { type: 'update', path, value };
}
function Insert(path, value) {
return { type: 'insert', path, value };
}
function Delete(path) {
return { type: 'delete', path };
}
// ---------------------------------------------------------------------
// Diff
// ---------------------------------------------------------------------
function* Object(path, current, next) {
if (!is_1.Is.Object(next))
return yield Update(path, next);
const currentKeys = [...globalThis.Object.keys(current), ...globalThis.Object.getOwnPropertySymbols(current)];
const nextKeys = [...globalThis.Object.keys(next), ...globalThis.Object.getOwnPropertySymbols(next)];
for (const key of currentKeys) {
if (typeof key === 'symbol')
throw new ValueDeltaObjectWithSymbolKeyError(key);
if (next[key] === undefined && nextKeys.includes(key))
yield Update(`${path}/${String(key)}`, undefined);
}
for (const key of nextKeys) {
if (current[key] === undefined || next[key] === undefined)
continue;
if (typeof key === 'symbol')
throw new ValueDeltaObjectWithSymbolKeyError(key);
yield* Visit(`${path}/${String(key)}`, current[key], next[key]);
}
for (const key of nextKeys) {
if (typeof key === 'symbol')
throw new ValueDeltaObjectWithSymbolKeyError(key);
if (current[key] === undefined)
yield Insert(`${path}/${String(key)}`, next[key]);
}
for (const key of currentKeys.reverse()) {
if (typeof key === 'symbol')
throw new ValueDeltaObjectWithSymbolKeyError(key);
if (next[key] === undefined && !nextKeys.includes(key))
yield Delete(`${path}/${String(key)}`);
}
}
function* Array(path, current, next) {
if (!is_1.Is.Array(next))
return yield Update(path, next);
for (let i = 0; i < Math.min(current.length, next.length); i++) {
yield* Visit(`${path}/${i}`, current[i], next[i]);
}
for (let i = 0; i < next.length; i++) {
if (i < current.length)
continue;
yield Insert(`${path}/${i}`, next[i]);
}
for (let i = current.length - 1; i >= 0; i--) {
if (i < next.length)
continue;
yield Delete(`${path}/${i}`);
}
}
function* TypedArray(path, current, next) {
if (!is_1.Is.TypedArray(next) || current.length !== next.length || globalThis.Object.getPrototypeOf(current).constructor.name !== globalThis.Object.getPrototypeOf(next).constructor.name)
return yield Update(path, next);
for (let i = 0; i < Math.min(current.length, next.length); i++) {
yield* Visit(`${path}/${i}`, current[i], next[i]);
}
}
function* Value(path, current, next) {
if (current === next)
return;
yield Update(path, next);
}
function* Visit(path, current, next) {
if (is_1.Is.Object(current)) {
return yield* Object(path, current, next);
}
else if (is_1.Is.Array(current)) {
return yield* Array(path, current, next);
}
else if (is_1.Is.TypedArray(current)) {
return yield* TypedArray(path, current, next);
}
else if (is_1.Is.Value(current)) {
return yield* Value(path, current, next);
}
else {
throw new ValueDeltaUnableToDiffUnknownValue(current);
}
}
function Diff(current, next) {
return [...Visit('', current, next)];
}
ValueDelta.Diff = Diff;
// ---------------------------------------------------------------------
// Patch
// ---------------------------------------------------------------------
function IsRootUpdate(edits) {
return edits.length > 0 && edits[0].path === '' && edits[0].type === 'update';
}
function IsIdentity(edits) {
return edits.length === 0;
}
function Patch(current, edits) {
if (IsRootUpdate(edits)) {
return clone_1.ValueClone.Clone(edits[0].value);
}
if (IsIdentity(edits)) {
return clone_1.ValueClone.Clone(current);
}
const clone = clone_1.ValueClone.Clone(current);
for (const edit of edits) {
switch (edit.type) {
case 'insert': {
pointer_1.ValuePointer.Set(clone, edit.path, edit.value);
break;
}
case 'update': {
pointer_1.ValuePointer.Set(clone, edit.path, edit.value);
break;
}
case 'delete': {
pointer_1.ValuePointer.Delete(clone, edit.path);
break;
}
}
}
return clone;
}
ValueDelta.Patch = Patch;
})(ValueDelta = exports.ValueDelta || (exports.ValueDelta = {}));

View file

@ -0,0 +1,3 @@
export declare namespace ValueEqual {
function Equal<T>(left: T, right: unknown): right is T;
}

View file

@ -0,0 +1,80 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2017-2023 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueEqual = void 0;
const is_1 = require("./is");
var ValueEqual;
(function (ValueEqual) {
function Object(left, right) {
if (!is_1.Is.Object(right))
return false;
const leftKeys = [...globalThis.Object.keys(left), ...globalThis.Object.getOwnPropertySymbols(left)];
const rightKeys = [...globalThis.Object.keys(right), ...globalThis.Object.getOwnPropertySymbols(right)];
if (leftKeys.length !== rightKeys.length)
return false;
return leftKeys.every((key) => Equal(left[key], right[key]));
}
function Date(left, right) {
return is_1.Is.Date(right) && left.getTime() === right.getTime();
}
function Array(left, right) {
if (!is_1.Is.Array(right) || left.length !== right.length)
return false;
return left.every((value, index) => Equal(value, right[index]));
}
function TypedArray(left, right) {
if (!is_1.Is.TypedArray(right) || left.length !== right.length || globalThis.Object.getPrototypeOf(left).constructor.name !== globalThis.Object.getPrototypeOf(right).constructor.name)
return false;
return left.every((value, index) => Equal(value, right[index]));
}
function Value(left, right) {
return left === right;
}
function Equal(left, right) {
if (is_1.Is.Object(left)) {
return Object(left, right);
}
else if (is_1.Is.Date(left)) {
return Date(left, right);
}
else if (is_1.Is.TypedArray(left)) {
return TypedArray(left, right);
}
else if (is_1.Is.Array(left)) {
return Array(left, right);
}
else if (is_1.Is.Value(left)) {
return Value(left, right);
}
else {
throw new Error('ValueEquals: Unable to compare value');
}
}
ValueEqual.Equal = Equal;
})(ValueEqual = exports.ValueEqual || (exports.ValueEqual = {}));

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