Compare commits

..

1 Commits

Author SHA1 Message Date
MoChilia
e15b166166 prepare release v1.6.0 2024-01-09 11:08:09 +08:00
204 changed files with 25826 additions and 25817 deletions

View File

@@ -560,9 +560,6 @@ jobs:
This action doesn't implement ```az logout``` by default at the end of execution. However, there is no way to tamper with the credentials or account information because the GitHub-hosted runner is on a VM that will get re-imaged for every customer run, which deletes everything. But if the runner is self-hosted (not provided by GitHub), it is recommended to manually log out at the end of the workflow, as shown below. More details on security of the runners can be found [here](https://docs.github.com/actions/learn-github-actions/security-hardening-for-github-actions#hardening-for-self-hosted-runners).
> [!WARNING]
> When using self hosted runners it is possible to have multiple runners on a single VM. Currently if your runners share a single user on the VM each runner will share the same credentials. That means in detail that each runner is able to change the permissions of another run. As a workaround we propose to use one single VM user per runner. If you start the runner as a service, do not forget to add the [optional user argument](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/configuring-the-self-hosted-runner-application-as-a-service#installing-the-service)
```yaml
- name: Azure CLI script
uses: azure/CLI@v1

View File

@@ -1,193 +1,193 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzureCliLogin = void 0;
const exec = __importStar(require("@actions/exec"));
const LoginConfig_1 = require("../common/LoginConfig");
const core = __importStar(require("@actions/core"));
const io = __importStar(require("@actions/io"));
class AzureCliLogin {
constructor(loginConfig) {
this.loginConfig = loginConfig;
this.loginOptions = defaultExecOptions();
}
login() {
return __awaiter(this, void 0, void 0, function* () {
core.info(`Running Azure CLI Login.`);
this.azPath = yield io.which("az", true);
core.debug(`Azure CLI path: ${this.azPath}`);
let output = "";
const execOptions = {
listeners: {
stdout: (data) => {
output += data.toString();
}
}
};
yield this.executeAzCliCommand(["--version"], true, execOptions);
core.debug(`Azure CLI version used:\n${output}`);
this.setAzurestackEnvIfNecessary();
yield this.executeAzCliCommand(["cloud", "set", "-n", this.loginConfig.environment], false);
core.info(`Done setting cloud: "${this.loginConfig.environment}"`);
if (this.loginConfig.authType === LoginConfig_1.LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
let args = ["--service-principal",
"--username", this.loginConfig.servicePrincipalId,
"--tenant", this.loginConfig.tenantId
];
if (this.loginConfig.servicePrincipalSecret) {
yield this.loginWithSecret(args);
}
else {
yield this.loginWithOIDC(args);
}
}
else {
let args = ["--identity"];
if (this.loginConfig.servicePrincipalId) {
yield this.loginWithUserAssignedIdentity(args);
}
else {
yield this.loginWithSystemAssignedIdentity(args);
}
}
});
}
setAzurestackEnvIfNecessary() {
return __awaiter(this, void 0, void 0, function* () {
if (this.loginConfig.environment != "azurestack") {
return;
}
if (!this.loginConfig.resourceManagerEndpointUrl) {
throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined.");
}
core.info(`Unregistering cloud: "${this.loginConfig.environment}" first if it exists`);
try {
yield this.executeAzCliCommand(["cloud", "set", "-n", "AzureCloud"], true);
yield this.executeAzCliCommand(["cloud", "unregister", "-n", this.loginConfig.environment], false);
}
catch (error) {
core.info(`Ignore cloud not registered error: "${error}"`);
}
core.info(`Registering cloud: "${this.loginConfig.environment}" with ARM endpoint: "${this.loginConfig.resourceManagerEndpointUrl}"`);
try {
let baseUri = this.loginConfig.resourceManagerEndpointUrl;
if (baseUri.endsWith('/')) {
baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below
}
let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with .
let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without .
let profileVersion = "2019-03-01-hybrid";
yield this.executeAzCliCommand(["cloud", "register", "-n", this.loginConfig.environment, "--endpoint-resource-manager", `"${this.loginConfig.resourceManagerEndpointUrl}"`, "--suffix-keyvault-dns", `"${suffixKeyvault}"`, "--suffix-storage-endpoint", `"${suffixStorage}"`, "--profile", `"${profileVersion}"`], false);
}
catch (error) {
core.error(`Error while trying to register cloud "${this.loginConfig.environment}"`);
throw error;
}
core.info(`Done registering cloud: "${this.loginConfig.environment}"`);
});
}
loginWithSecret(args) {
return __awaiter(this, void 0, void 0, function* () {
core.info("Note: Azure/login action also supports OIDC login mechanism. Refer https://github.com/azure/login#configure-a-service-principal-with-a-federated-credential-to-use-oidc-based-authentication for more details.");
args.push(`--password=${this.loginConfig.servicePrincipalSecret}`);
yield this.callCliLogin(args, 'service principal with secret');
});
}
loginWithOIDC(args) {
return __awaiter(this, void 0, void 0, function* () {
yield this.loginConfig.getFederatedToken();
args.push("--federated-token", this.loginConfig.federatedToken);
yield this.callCliLogin(args, 'OIDC');
});
}
loginWithUserAssignedIdentity(args) {
return __awaiter(this, void 0, void 0, function* () {
args.push("--username", this.loginConfig.servicePrincipalId);
yield this.callCliLogin(args, 'user-assigned managed identity');
});
}
loginWithSystemAssignedIdentity(args) {
return __awaiter(this, void 0, void 0, function* () {
yield this.callCliLogin(args, 'system-assigned managed identity');
});
}
callCliLogin(args, methodName) {
return __awaiter(this, void 0, void 0, function* () {
core.info(`Attempting Azure CLI login by using ${methodName}...`);
args.unshift("login");
if (this.loginConfig.allowNoSubscriptionsLogin) {
args.push("--allow-no-subscriptions");
}
yield this.executeAzCliCommand(args, true, this.loginOptions);
if (this.loginConfig.subscriptionId) {
yield this.setSubscription();
}
core.info(`Azure CLI login succeeds by using ${methodName}.`);
});
}
setSubscription() {
return __awaiter(this, void 0, void 0, function* () {
let args = ["account", "set", "--subscription", this.loginConfig.subscriptionId];
yield this.executeAzCliCommand(args, true, this.loginOptions);
core.info("Subscription is set successfully.");
});
}
executeAzCliCommand(args, silent, execOptions = {}) {
return __awaiter(this, void 0, void 0, function* () {
execOptions.silent = !!silent;
yield exec.exec(`"${this.azPath}"`, args, execOptions);
});
}
}
exports.AzureCliLogin = AzureCliLogin;
function defaultExecOptions() {
return {
silent: true,
listeners: {
stderr: (data) => {
let error = data.toString();
let startsWithWarning = error.toLowerCase().startsWith('warning');
let startsWithError = error.toLowerCase().startsWith('error');
// printing ERROR
if (error && error.trim().length !== 0 && !startsWithWarning) {
if (startsWithError) {
//removing the keyword 'ERROR' to avoid duplicates while throwing error
error = error.slice(7);
}
core.error(error);
}
}
}
};
}
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzureCliLogin = void 0;
const exec = __importStar(require("@actions/exec"));
const LoginConfig_1 = require("../common/LoginConfig");
const core = __importStar(require("@actions/core"));
const io = __importStar(require("@actions/io"));
class AzureCliLogin {
constructor(loginConfig) {
this.loginConfig = loginConfig;
this.loginOptions = defaultExecOptions();
}
login() {
return __awaiter(this, void 0, void 0, function* () {
core.info(`Running Azure CLI Login.`);
this.azPath = yield io.which("az", true);
core.debug(`Azure CLI path: ${this.azPath}`);
let output = "";
const execOptions = {
listeners: {
stdout: (data) => {
output += data.toString();
}
}
};
yield this.executeAzCliCommand(["--version"], true, execOptions);
core.debug(`Azure CLI version used:\n${output}`);
this.setAzurestackEnvIfNecessary();
yield this.executeAzCliCommand(["cloud", "set", "-n", this.loginConfig.environment], false);
core.info(`Done setting cloud: "${this.loginConfig.environment}"`);
if (this.loginConfig.authType === LoginConfig_1.LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
let args = ["--service-principal",
"--username", this.loginConfig.servicePrincipalId,
"--tenant", this.loginConfig.tenantId
];
if (this.loginConfig.servicePrincipalSecret) {
yield this.loginWithSecret(args);
}
else {
yield this.loginWithOIDC(args);
}
}
else {
let args = ["--identity"];
if (this.loginConfig.servicePrincipalId) {
yield this.loginWithUserAssignedIdentity(args);
}
else {
yield this.loginWithSystemAssignedIdentity(args);
}
}
});
}
setAzurestackEnvIfNecessary() {
return __awaiter(this, void 0, void 0, function* () {
if (this.loginConfig.environment != "azurestack") {
return;
}
if (!this.loginConfig.resourceManagerEndpointUrl) {
throw new Error("resourceManagerEndpointUrl is a required parameter when environment is defined.");
}
core.info(`Unregistering cloud: "${this.loginConfig.environment}" first if it exists`);
try {
yield this.executeAzCliCommand(["cloud", "set", "-n", "AzureCloud"], true);
yield this.executeAzCliCommand(["cloud", "unregister", "-n", this.loginConfig.environment], false);
}
catch (error) {
core.info(`Ignore cloud not registered error: "${error}"`);
}
core.info(`Registering cloud: "${this.loginConfig.environment}" with ARM endpoint: "${this.loginConfig.resourceManagerEndpointUrl}"`);
try {
let baseUri = this.loginConfig.resourceManagerEndpointUrl;
if (baseUri.endsWith('/')) {
baseUri = baseUri.substring(0, baseUri.length - 1); // need to remove trailing / from resourceManagerEndpointUrl to correctly derive suffixes below
}
let suffixKeyvault = ".vault" + baseUri.substring(baseUri.indexOf('.')); // keyvault suffix starts with .
let suffixStorage = baseUri.substring(baseUri.indexOf('.') + 1); // storage suffix starts without .
let profileVersion = "2019-03-01-hybrid";
yield this.executeAzCliCommand(["cloud", "register", "-n", this.loginConfig.environment, "--endpoint-resource-manager", `"${this.loginConfig.resourceManagerEndpointUrl}"`, "--suffix-keyvault-dns", `"${suffixKeyvault}"`, "--suffix-storage-endpoint", `"${suffixStorage}"`, "--profile", `"${profileVersion}"`], false);
}
catch (error) {
core.error(`Error while trying to register cloud "${this.loginConfig.environment}"`);
throw error;
}
core.info(`Done registering cloud: "${this.loginConfig.environment}"`);
});
}
loginWithSecret(args) {
return __awaiter(this, void 0, void 0, function* () {
core.info("Note: Azure/login action also supports OIDC login mechanism. Refer https://github.com/azure/login#configure-a-service-principal-with-a-federated-credential-to-use-oidc-based-authentication for more details.");
args.push(`--password=${this.loginConfig.servicePrincipalSecret}`);
yield this.callCliLogin(args, 'service principal with secret');
});
}
loginWithOIDC(args) {
return __awaiter(this, void 0, void 0, function* () {
yield this.loginConfig.getFederatedToken();
args.push("--federated-token", this.loginConfig.federatedToken);
yield this.callCliLogin(args, 'OIDC');
});
}
loginWithUserAssignedIdentity(args) {
return __awaiter(this, void 0, void 0, function* () {
args.push("--username", this.loginConfig.servicePrincipalId);
yield this.callCliLogin(args, 'user-assigned managed identity');
});
}
loginWithSystemAssignedIdentity(args) {
return __awaiter(this, void 0, void 0, function* () {
yield this.callCliLogin(args, 'system-assigned managed identity');
});
}
callCliLogin(args, methodName) {
return __awaiter(this, void 0, void 0, function* () {
core.info(`Attempting Azure CLI login by using ${methodName}...`);
args.unshift("login");
if (this.loginConfig.allowNoSubscriptionsLogin) {
args.push("--allow-no-subscriptions");
}
yield this.executeAzCliCommand(args, true, this.loginOptions);
if (this.loginConfig.subscriptionId) {
yield this.setSubscription();
}
core.info(`Azure CLI login succeeds by using ${methodName}.`);
});
}
setSubscription() {
return __awaiter(this, void 0, void 0, function* () {
let args = ["account", "set", "--subscription", this.loginConfig.subscriptionId];
yield this.executeAzCliCommand(args, true, this.loginOptions);
core.info("Subscription is set successfully.");
});
}
executeAzCliCommand(args, silent, execOptions = {}) {
return __awaiter(this, void 0, void 0, function* () {
execOptions.silent = !!silent;
yield exec.exec(`"${this.azPath}"`, args, execOptions);
});
}
}
exports.AzureCliLogin = AzureCliLogin;
function defaultExecOptions() {
return {
silent: true,
listeners: {
stderr: (data) => {
let error = data.toString();
let startsWithWarning = error.toLowerCase().startsWith('warning');
let startsWithError = error.toLowerCase().startsWith('error');
// printing ERROR
if (error && error.trim().length !== 0 && !startsWithWarning) {
if (startsWithError) {
//removing the keyword 'ERROR' to avoid duplicates while throwing error
error = error.slice(7);
}
core.error(error);
}
}
}
};
}

View File

@@ -1,59 +1,59 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzPSLogin = void 0;
const core = __importStar(require("@actions/core"));
const AzPSScriptBuilder_1 = __importDefault(require("./AzPSScriptBuilder"));
const AzPSUtils_1 = require("./AzPSUtils");
class AzPSLogin {
constructor(loginConfig) {
this.loginConfig = loginConfig;
}
login() {
return __awaiter(this, void 0, void 0, function* () {
core.info(`Running Azure PowerShell Login.`);
AzPSUtils_1.AzPSUtils.setPSModulePathForGitHubRunner();
yield AzPSUtils_1.AzPSUtils.importLatestAzAccounts();
const [loginMethod, loginScript] = yield AzPSScriptBuilder_1.default.getAzPSLoginScript(this.loginConfig);
core.info(`Attempting Azure PowerShell login by using ${loginMethod}...`);
core.debug(`Azure PowerShell Login Script: ${loginScript}`);
yield AzPSUtils_1.AzPSUtils.runPSScript(loginScript);
console.log(`Running Azure PowerShell Login successfully.`);
});
}
}
exports.AzPSLogin = AzPSLogin;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzPSLogin = void 0;
const core = __importStar(require("@actions/core"));
const AzPSScriptBuilder_1 = __importDefault(require("./AzPSScriptBuilder"));
const AzPSUtils_1 = require("./AzPSUtils");
class AzPSLogin {
constructor(loginConfig) {
this.loginConfig = loginConfig;
}
login() {
return __awaiter(this, void 0, void 0, function* () {
core.info(`Running Azure PowerShell Login.`);
AzPSUtils_1.AzPSUtils.setPSModulePathForGitHubRunner();
yield AzPSUtils_1.AzPSUtils.importLatestAzAccounts();
const [loginMethod, loginScript] = yield AzPSScriptBuilder_1.default.getAzPSLoginScript(this.loginConfig);
core.info(`Attempting Azure PowerShell login by using ${loginMethod}...`);
core.debug(`Azure PowerShell Login Script: ${loginScript}`);
yield AzPSUtils_1.AzPSUtils.runPSScript(loginScript);
console.log(`Running Azure PowerShell Login successfully.`);
});
}
}
exports.AzPSLogin = AzPSLogin;

View File

@@ -1,116 +1,116 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const LoginConfig_1 = require("../common/LoginConfig");
class AzPSScriptBuilder {
static getImportLatestModuleScript(moduleName) {
let script = `try {
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
$latestModulePath = (Get-Module -Name '${moduleName}' -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1).Path
Import-Module -Name $latestModulePath
$output['Success'] = $true
$output['Result'] = $latestModulePath
}
catch {
$output['Success'] = $false
$output['Error'] = $_.exception.Message
}
return ConvertTo-Json $output`;
return script;
}
static getAzPSLoginScript(loginConfig) {
return __awaiter(this, void 0, void 0, function* () {
let loginMethodName = "";
let commands = "";
if (loginConfig.environment.toLowerCase() == "azurestack") {
commands += `Add-AzEnvironment -Name '${loginConfig.environment}' -ARMEndpoint '${loginConfig.resourceManagerEndpointUrl}' | out-null;`;
}
if (loginConfig.authType === LoginConfig_1.LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
if (loginConfig.servicePrincipalSecret) {
commands += AzPSScriptBuilder.loginWithSecret(loginConfig);
loginMethodName = 'service principal with secret';
}
else {
commands += yield AzPSScriptBuilder.loginWithOIDC(loginConfig);
loginMethodName = "OIDC";
}
}
else {
if (loginConfig.servicePrincipalId) {
commands += AzPSScriptBuilder.loginWithUserAssignedIdentity(loginConfig);
loginMethodName = 'user-assigned managed identity';
}
else {
commands += AzPSScriptBuilder.loginWithSystemAssignedIdentity(loginConfig);
loginMethodName = 'system-assigned managed identity';
}
}
let script = `try {
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
${commands}
$output['Success'] = $true
$output['Result'] = ""
}
catch {
$output['Success'] = $false
$output['Error'] = $_.exception.Message
}
return ConvertTo-Json $output`;
return [loginMethodName, script];
});
}
static loginWithSecret(loginConfig) {
let servicePrincipalSecret = loginConfig.servicePrincipalSecret.split("'").join("''");
let loginCmdlet = `$psLoginSecrets = ConvertTo-SecureString '${servicePrincipalSecret}' -AsPlainText -Force; `;
loginCmdlet += `$psLoginCredential = New-Object System.Management.Automation.PSCredential('${loginConfig.servicePrincipalId}', $psLoginSecrets); `;
let cmdletSuffix = "-Credential $psLoginCredential";
loginCmdlet += AzPSScriptBuilder.psLoginCmdlet(loginConfig.authType, loginConfig.environment, loginConfig.tenantId, loginConfig.subscriptionId, cmdletSuffix);
return loginCmdlet;
}
static loginWithOIDC(loginConfig) {
return __awaiter(this, void 0, void 0, function* () {
yield loginConfig.getFederatedToken();
let cmdletSuffix = `-ApplicationId '${loginConfig.servicePrincipalId}' -FederatedToken '${loginConfig.federatedToken}'`;
return AzPSScriptBuilder.psLoginCmdlet(loginConfig.authType, loginConfig.environment, loginConfig.tenantId, loginConfig.subscriptionId, cmdletSuffix);
});
}
static loginWithSystemAssignedIdentity(loginConfig) {
let cmdletSuffix = "";
return AzPSScriptBuilder.psLoginCmdlet(loginConfig.authType, loginConfig.environment, loginConfig.tenantId, loginConfig.subscriptionId, cmdletSuffix);
}
static loginWithUserAssignedIdentity(loginConfig) {
let cmdletSuffix = `-AccountId '${loginConfig.servicePrincipalId}'`;
return AzPSScriptBuilder.psLoginCmdlet(loginConfig.authType, loginConfig.environment, loginConfig.tenantId, loginConfig.subscriptionId, cmdletSuffix);
}
static psLoginCmdlet(authType, environment, tenantId, subscriptionId, cmdletSuffix) {
let loginCmdlet = `Connect-AzAccount `;
if (authType === LoginConfig_1.LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
loginCmdlet += "-ServicePrincipal ";
}
else {
loginCmdlet += "-Identity ";
}
loginCmdlet += `-Environment '${environment}' `;
if (tenantId) {
loginCmdlet += `-Tenant '${tenantId}' `;
}
if (subscriptionId) {
loginCmdlet += `-Subscription '${subscriptionId}' `;
}
loginCmdlet += `${cmdletSuffix} | out-null;`;
return loginCmdlet;
}
}
exports.default = AzPSScriptBuilder;
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const LoginConfig_1 = require("../common/LoginConfig");
class AzPSScriptBuilder {
static getImportLatestModuleScript(moduleName) {
let script = `try {
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
$latestModulePath = (Get-Module -Name '${moduleName}' -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1).Path
Import-Module -Name $latestModulePath
$output['Success'] = $true
$output['Result'] = $latestModulePath
}
catch {
$output['Success'] = $false
$output['Error'] = $_.exception.Message
}
return ConvertTo-Json $output`;
return script;
}
static getAzPSLoginScript(loginConfig) {
return __awaiter(this, void 0, void 0, function* () {
let loginMethodName = "";
let commands = "";
if (loginConfig.environment.toLowerCase() == "azurestack") {
commands += `Add-AzEnvironment -Name '${loginConfig.environment}' -ARMEndpoint '${loginConfig.resourceManagerEndpointUrl}' | out-null;`;
}
if (loginConfig.authType === LoginConfig_1.LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
if (loginConfig.servicePrincipalSecret) {
commands += AzPSScriptBuilder.loginWithSecret(loginConfig);
loginMethodName = 'service principal with secret';
}
else {
commands += yield AzPSScriptBuilder.loginWithOIDC(loginConfig);
loginMethodName = "OIDC";
}
}
else {
if (loginConfig.servicePrincipalId) {
commands += AzPSScriptBuilder.loginWithUserAssignedIdentity(loginConfig);
loginMethodName = 'user-assigned managed identity';
}
else {
commands += AzPSScriptBuilder.loginWithSystemAssignedIdentity(loginConfig);
loginMethodName = 'system-assigned managed identity';
}
}
let script = `try {
$ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue"
$output = @{}
${commands}
$output['Success'] = $true
$output['Result'] = ""
}
catch {
$output['Success'] = $false
$output['Error'] = $_.exception.Message
}
return ConvertTo-Json $output`;
return [loginMethodName, script];
});
}
static loginWithSecret(loginConfig) {
let servicePrincipalSecret = loginConfig.servicePrincipalSecret.split("'").join("''");
let loginCmdlet = `$psLoginSecrets = ConvertTo-SecureString '${servicePrincipalSecret}' -AsPlainText -Force; `;
loginCmdlet += `$psLoginCredential = New-Object System.Management.Automation.PSCredential('${loginConfig.servicePrincipalId}', $psLoginSecrets); `;
let cmdletSuffix = "-Credential $psLoginCredential";
loginCmdlet += AzPSScriptBuilder.psLoginCmdlet(loginConfig.authType, loginConfig.environment, loginConfig.tenantId, loginConfig.subscriptionId, cmdletSuffix);
return loginCmdlet;
}
static loginWithOIDC(loginConfig) {
return __awaiter(this, void 0, void 0, function* () {
yield loginConfig.getFederatedToken();
let cmdletSuffix = `-ApplicationId '${loginConfig.servicePrincipalId}' -FederatedToken '${loginConfig.federatedToken}'`;
return AzPSScriptBuilder.psLoginCmdlet(loginConfig.authType, loginConfig.environment, loginConfig.tenantId, loginConfig.subscriptionId, cmdletSuffix);
});
}
static loginWithSystemAssignedIdentity(loginConfig) {
let cmdletSuffix = "";
return AzPSScriptBuilder.psLoginCmdlet(loginConfig.authType, loginConfig.environment, loginConfig.tenantId, loginConfig.subscriptionId, cmdletSuffix);
}
static loginWithUserAssignedIdentity(loginConfig) {
let cmdletSuffix = `-AccountId '${loginConfig.servicePrincipalId}'`;
return AzPSScriptBuilder.psLoginCmdlet(loginConfig.authType, loginConfig.environment, loginConfig.tenantId, loginConfig.subscriptionId, cmdletSuffix);
}
static psLoginCmdlet(authType, environment, tenantId, subscriptionId, cmdletSuffix) {
let loginCmdlet = `Connect-AzAccount `;
if (authType === LoginConfig_1.LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
loginCmdlet += "-ServicePrincipal ";
}
else {
loginCmdlet += "-Identity ";
}
loginCmdlet += `-Environment '${environment}' `;
if (tenantId) {
loginCmdlet += `-Tenant '${tenantId}' `;
}
if (subscriptionId) {
loginCmdlet += `-Subscription '${subscriptionId}' `;
}
loginCmdlet += `${cmdletSuffix} | out-null;`;
return loginCmdlet;
}
}
exports.default = AzPSScriptBuilder;

View File

@@ -1,119 +1,119 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzPSUtils = exports.AzPSConstants = void 0;
const core = __importStar(require("@actions/core"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const exec = __importStar(require("@actions/exec"));
const io = __importStar(require("@actions/io"));
const AzPSScriptBuilder_1 = __importDefault(require("./AzPSScriptBuilder"));
class AzPSConstants {
}
exports.AzPSConstants = AzPSConstants;
AzPSConstants.DEFAULT_AZ_PATH_ON_LINUX = '/usr/share';
AzPSConstants.DEFAULT_AZ_PATH_ON_WINDOWS = 'C:\\Modules';
AzPSConstants.AzAccounts = "Az.Accounts";
AzPSConstants.PowerShell_CmdName = "pwsh";
class AzPSUtils {
static setPSModulePathForGitHubRunner() {
return __awaiter(this, void 0, void 0, function* () {
const runner = process.env.RUNNER_OS || os.type();
switch (runner.toLowerCase()) {
case "linux":
AzPSUtils.pushPSModulePath(AzPSConstants.DEFAULT_AZ_PATH_ON_LINUX);
break;
case "windows":
case "windows_nt":
AzPSUtils.pushPSModulePath(AzPSConstants.DEFAULT_AZ_PATH_ON_WINDOWS);
break;
case "macos":
case "darwin":
core.warning(`Skip setting the default PowerShell module path for OS ${runner.toLowerCase()}.`);
break;
default:
core.warning(`Skip setting the default PowerShell module path for unknown OS ${runner.toLowerCase()}.`);
break;
}
});
}
static pushPSModulePath(psModulePath) {
process.env.PSModulePath = `${psModulePath}${path.delimiter}${process.env.PSModulePath}`;
core.debug(`Set PSModulePath as ${process.env.PSModulePath}`);
}
static importLatestAzAccounts() {
return __awaiter(this, void 0, void 0, function* () {
let importLatestAccountsScript = AzPSScriptBuilder_1.default.getImportLatestModuleScript(AzPSConstants.AzAccounts);
core.debug(`The script to import the latest Az.Accounts: ${importLatestAccountsScript}`);
let azAccountsPath = yield AzPSUtils.runPSScript(importLatestAccountsScript);
core.debug(`The latest Az.Accounts used: ${azAccountsPath}`);
});
}
static runPSScript(psScript) {
return __awaiter(this, void 0, void 0, function* () {
let outputString = "";
let commandStdErr = false;
const options = {
silent: true,
listeners: {
stdout: (data) => {
outputString += data.toString();
},
stderr: (data) => {
let error = data.toString();
if (error && error.trim().length !== 0) {
commandStdErr = true;
core.error(error);
}
}
}
};
let psPath = yield io.which(AzPSConstants.PowerShell_CmdName, true);
yield exec.exec(`"${psPath}"`, ["-Command", psScript], options);
if (commandStdErr) {
throw new Error('Azure PowerShell login failed with errors.');
}
const result = JSON.parse(outputString.trim());
console.log(result);
if (!(result.Success)) {
throw new Error(`Azure PowerShell login failed with error: ${result.Error}`);
}
return result.Result;
});
}
}
exports.AzPSUtils = AzPSUtils;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AzPSUtils = exports.AzPSConstants = void 0;
const core = __importStar(require("@actions/core"));
const os = __importStar(require("os"));
const path = __importStar(require("path"));
const exec = __importStar(require("@actions/exec"));
const io = __importStar(require("@actions/io"));
const AzPSScriptBuilder_1 = __importDefault(require("./AzPSScriptBuilder"));
class AzPSConstants {
}
exports.AzPSConstants = AzPSConstants;
AzPSConstants.DEFAULT_AZ_PATH_ON_LINUX = '/usr/share';
AzPSConstants.DEFAULT_AZ_PATH_ON_WINDOWS = 'C:\\Modules';
AzPSConstants.AzAccounts = "Az.Accounts";
AzPSConstants.PowerShell_CmdName = "pwsh";
class AzPSUtils {
static setPSModulePathForGitHubRunner() {
return __awaiter(this, void 0, void 0, function* () {
const runner = process.env.RUNNER_OS || os.type();
switch (runner.toLowerCase()) {
case "linux":
AzPSUtils.pushPSModulePath(AzPSConstants.DEFAULT_AZ_PATH_ON_LINUX);
break;
case "windows":
case "windows_nt":
AzPSUtils.pushPSModulePath(AzPSConstants.DEFAULT_AZ_PATH_ON_WINDOWS);
break;
case "macos":
case "darwin":
core.warning(`Skip setting the default PowerShell module path for OS ${runner.toLowerCase()}.`);
break;
default:
core.warning(`Skip setting the default PowerShell module path for unknown OS ${runner.toLowerCase()}.`);
break;
}
});
}
static pushPSModulePath(psModulePath) {
process.env.PSModulePath = `${psModulePath}${path.delimiter}${process.env.PSModulePath}`;
core.debug(`Set PSModulePath as ${process.env.PSModulePath}`);
}
static importLatestAzAccounts() {
return __awaiter(this, void 0, void 0, function* () {
let importLatestAccountsScript = AzPSScriptBuilder_1.default.getImportLatestModuleScript(AzPSConstants.AzAccounts);
core.debug(`The script to import the latest Az.Accounts: ${importLatestAccountsScript}`);
let azAccountsPath = yield AzPSUtils.runPSScript(importLatestAccountsScript);
core.debug(`The latest Az.Accounts used: ${azAccountsPath}`);
});
}
static runPSScript(psScript) {
return __awaiter(this, void 0, void 0, function* () {
let outputString = "";
let commandStdErr = false;
const options = {
silent: true,
listeners: {
stdout: (data) => {
outputString += data.toString();
},
stderr: (data) => {
let error = data.toString();
if (error && error.trim().length !== 0) {
commandStdErr = true;
core.error(error);
}
}
}
};
let psPath = yield io.which(AzPSConstants.PowerShell_CmdName, true);
yield exec.exec(`"${psPath}"`, ["-Command", psScript], options);
if (commandStdErr) {
throw new Error('Azure PowerShell login failed with errors.');
}
const result = JSON.parse(outputString.trim());
console.log(result);
if (!(result.Success)) {
throw new Error(`Azure PowerShell login failed with error: ${result.Error}`);
}
return result.Result;
});
}
}
exports.AzPSUtils = AzPSUtils;

View File

@@ -1,52 +1,52 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const Utils_1 = require("./common/Utils");
function cleanup() {
return __awaiter(this, void 0, void 0, function* () {
try {
(0, Utils_1.setUserAgent)();
yield (0, Utils_1.cleanupAzCLIAccounts)();
if (core.getInput('enable-AzPSSession').toLowerCase() === "true") {
yield (0, Utils_1.cleanupAzPSAccounts)();
}
}
catch (error) {
core.warning(`Login cleanup failed with ${error}. Cleanup will be skipped.`);
core.debug(error.stack);
}
});
}
cleanup();
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const Utils_1 = require("./common/Utils");
function cleanup() {
return __awaiter(this, void 0, void 0, function* () {
try {
(0, Utils_1.setUserAgent)();
yield (0, Utils_1.cleanupAzCLIAccounts)();
if (core.getInput('enable-AzPSSession').toLowerCase() === "true") {
yield (0, Utils_1.cleanupAzPSAccounts)();
}
}
catch (error) {
core.setFailed(`Login cleanup failed with ${error}. Make sure 'az' is installed on the runner. If 'enable-AzPSSession' is true, make sure 'pwsh' is installed on the runner together with Azure PowerShell module.`);
core.debug(error.stack);
}
});
}
cleanup();

View File

@@ -1,136 +1,136 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoginConfig = void 0;
const core = __importStar(require("@actions/core"));
const actions_secret_parser_1 = require("actions-secret-parser");
class LoginConfig {
initialize() {
return __awaiter(this, void 0, void 0, function* () {
this.environment = core.getInput("environment").toLowerCase();
this.enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true";
this.allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true";
this.authType = core.getInput('auth-type').toUpperCase();
this.servicePrincipalId = core.getInput('client-id', { required: false });
this.servicePrincipalSecret = null;
this.tenantId = core.getInput('tenant-id', { required: false });
this.subscriptionId = core.getInput('subscription-id', { required: false });
this.readParametersFromCreds();
this.audience = core.getInput('audience', { required: false });
this.federatedToken = null;
this.mask(this.servicePrincipalId);
this.mask(this.servicePrincipalSecret);
});
}
readParametersFromCreds() {
let creds = core.getInput('creds', { required: false });
let secrets = creds ? new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON) : null;
if (!secrets) {
return;
}
if (this.authType != LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
return;
}
if (this.servicePrincipalId || this.tenantId || this.subscriptionId) {
core.warning("At least one of the parameters 'client-id', 'subscription-id' or 'tenant-id' is set. 'creds' will be ignored.");
return;
}
core.debug('Reading creds in JSON...');
this.servicePrincipalId = this.servicePrincipalId ? this.servicePrincipalId : secrets.getSecret("$.clientId", false);
this.servicePrincipalSecret = secrets.getSecret("$.clientSecret", false);
this.tenantId = this.tenantId ? this.tenantId : secrets.getSecret("$.tenantId", false);
this.subscriptionId = this.subscriptionId ? this.subscriptionId : secrets.getSecret("$.subscriptionId", false);
this.resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false);
if (!this.servicePrincipalId || !this.servicePrincipalSecret || !this.tenantId) {
throw new Error("Not all parameters are provided in 'creds'. Double-check if all keys are defined in 'creds': 'clientId', 'clientSecret', 'tenantId'.");
}
}
getFederatedToken() {
return __awaiter(this, void 0, void 0, function* () {
try {
this.federatedToken = yield core.getIDToken(this.audience);
this.mask(this.federatedToken);
}
catch (error) {
core.error(`Please make sure to give write permissions to id-token in the workflow.`);
throw error;
}
let [issuer, subjectClaim] = yield jwtParser(this.federatedToken);
core.info("Federated token details:\n issuer - " + issuer + "\n subject claim - " + subjectClaim);
});
}
validate() {
if (!LoginConfig.azureSupportedCloudName.has(this.environment)) {
throw new Error(`Unsupported value '${this.environment}' for environment is passed. The list of supported values for environment are '${Array.from(LoginConfig.azureSupportedCloudName).join("', '")}'. `);
}
if (!LoginConfig.azureSupportedAuthType.has(this.authType)) {
throw new Error(`Unsupported value '${this.authType}' for authentication type is passed. The list of supported values for auth-type are '${Array.from(LoginConfig.azureSupportedAuthType).join("', '")}'.`);
}
if (this.authType === LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
if (!this.servicePrincipalId || !this.tenantId) {
throw new Error(`Using auth-type: ${LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL}. Not all values are present. Ensure 'client-id' and 'tenant-id' are supplied.`);
}
}
if (!this.subscriptionId && !this.allowNoSubscriptionsLogin) {
throw new Error("Ensure subscriptionId is supplied.");
}
}
mask(parameterValue) {
if (parameterValue) {
core.setSecret(parameterValue);
}
}
}
exports.LoginConfig = LoginConfig;
LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL = "SERVICE_PRINCIPAL";
LoginConfig.AUTH_TYPE_IDENTITY = "IDENTITY";
LoginConfig.azureSupportedCloudName = new Set([
"azureusgovernment",
"azurechinacloud",
"azuregermancloud",
"azurecloud",
"azurestack"
]);
LoginConfig.azureSupportedAuthType = new Set([
LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL,
LoginConfig.AUTH_TYPE_IDENTITY
]);
function jwtParser(federatedToken) {
return __awaiter(this, void 0, void 0, function* () {
let tokenPayload = federatedToken.split('.')[1];
let bufferObj = Buffer.from(tokenPayload, "base64");
let decodedPayload = JSON.parse(bufferObj.toString("utf8"));
return [decodedPayload['iss'], decodedPayload['sub']];
});
}
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoginConfig = void 0;
const core = __importStar(require("@actions/core"));
const actions_secret_parser_1 = require("actions-secret-parser");
class LoginConfig {
initialize() {
return __awaiter(this, void 0, void 0, function* () {
this.environment = core.getInput("environment").toLowerCase();
this.enableAzPSSession = core.getInput('enable-AzPSSession').toLowerCase() === "true";
this.allowNoSubscriptionsLogin = core.getInput('allow-no-subscriptions').toLowerCase() === "true";
this.authType = core.getInput('auth-type').toUpperCase();
this.servicePrincipalId = core.getInput('client-id', { required: false });
this.servicePrincipalSecret = null;
this.tenantId = core.getInput('tenant-id', { required: false });
this.subscriptionId = core.getInput('subscription-id', { required: false });
this.readParametersFromCreds();
this.audience = core.getInput('audience', { required: false });
this.federatedToken = null;
this.mask(this.servicePrincipalId);
this.mask(this.servicePrincipalSecret);
});
}
readParametersFromCreds() {
let creds = core.getInput('creds', { required: false });
let secrets = creds ? new actions_secret_parser_1.SecretParser(creds, actions_secret_parser_1.FormatType.JSON) : null;
if (!secrets) {
return;
}
if (this.authType != LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
return;
}
if (this.servicePrincipalId || this.tenantId || this.subscriptionId) {
core.warning("At least one of the parameters 'client-id', 'subscription-id' or 'tenant-id' is set. 'creds' will be ignored.");
return;
}
core.debug('Reading creds in JSON...');
this.servicePrincipalId = this.servicePrincipalId ? this.servicePrincipalId : secrets.getSecret("$.clientId", false);
this.servicePrincipalSecret = secrets.getSecret("$.clientSecret", false);
this.tenantId = this.tenantId ? this.tenantId : secrets.getSecret("$.tenantId", false);
this.subscriptionId = this.subscriptionId ? this.subscriptionId : secrets.getSecret("$.subscriptionId", false);
this.resourceManagerEndpointUrl = secrets.getSecret("$.resourceManagerEndpointUrl", false);
if (!this.servicePrincipalId || !this.servicePrincipalSecret || !this.tenantId) {
throw new Error("Not all parameters are provided in 'creds'. Double-check if all keys are defined in 'creds': 'clientId', 'clientSecret', 'tenantId'.");
}
}
getFederatedToken() {
return __awaiter(this, void 0, void 0, function* () {
try {
this.federatedToken = yield core.getIDToken(this.audience);
this.mask(this.federatedToken);
}
catch (error) {
core.error(`Please make sure to give write permissions to id-token in the workflow.`);
throw error;
}
let [issuer, subjectClaim] = yield jwtParser(this.federatedToken);
core.info("Federated token details:\n issuer - " + issuer + "\n subject claim - " + subjectClaim);
});
}
validate() {
if (!LoginConfig.azureSupportedCloudName.has(this.environment)) {
throw new Error(`Unsupported value '${this.environment}' for environment is passed. The list of supported values for environment are '${Array.from(LoginConfig.azureSupportedCloudName).join("', '")}'. `);
}
if (!LoginConfig.azureSupportedAuthType.has(this.authType)) {
throw new Error(`Unsupported value '${this.authType}' for authentication type is passed. The list of supported values for auth-type are '${Array.from(LoginConfig.azureSupportedAuthType).join("', '")}'.`);
}
if (this.authType === LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL) {
if (!this.servicePrincipalId || !this.tenantId) {
throw new Error(`Using auth-type: ${LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL}. Not all values are present. Ensure 'client-id' and 'tenant-id' are supplied.`);
}
}
if (!this.subscriptionId && !this.allowNoSubscriptionsLogin) {
throw new Error("Ensure subscriptionId is supplied.");
}
}
mask(parameterValue) {
if (parameterValue) {
core.setSecret(parameterValue);
}
}
}
exports.LoginConfig = LoginConfig;
LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL = "SERVICE_PRINCIPAL";
LoginConfig.AUTH_TYPE_IDENTITY = "IDENTITY";
LoginConfig.azureSupportedCloudName = new Set([
"azureusgovernment",
"azurechinacloud",
"azuregermancloud",
"azurecloud",
"azurestack"
]);
LoginConfig.azureSupportedAuthType = new Set([
LoginConfig.AUTH_TYPE_SERVICE_PRINCIPAL,
LoginConfig.AUTH_TYPE_IDENTITY
]);
function jwtParser(federatedToken) {
return __awaiter(this, void 0, void 0, function* () {
let tokenPayload = federatedToken.split('.')[1];
let bufferObj = Buffer.from(tokenPayload, "base64");
let decodedPayload = JSON.parse(bufferObj.toString("utf8"));
return [decodedPayload['iss'], decodedPayload['sub']];
});
}

View File

@@ -1,69 +1,75 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanupAzPSAccounts = exports.cleanupAzCLIAccounts = exports.setUserAgent = void 0;
const core = __importStar(require("@actions/core"));
const exec = __importStar(require("@actions/exec"));
const io = __importStar(require("@actions/io"));
const crypto = __importStar(require("crypto"));
const AzPSUtils_1 = require("../PowerShell/AzPSUtils");
function setUserAgent() {
let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex');
let actionName = 'AzureLogin';
process.env.AZURE_HTTP_USER_AGENT = (!!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT} ` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`;
process.env.AZUREPS_HOST_ENVIRONMENT = (!!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT} ` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`;
}
exports.setUserAgent = setUserAgent;
function cleanupAzCLIAccounts() {
return __awaiter(this, void 0, void 0, function* () {
let azPath = yield io.which("az", true);
core.debug(`Azure CLI path: ${azPath}`);
core.info("Clearing azure cli accounts from the local cache.");
yield exec.exec(`"${azPath}"`, ["account", "clear"]);
});
}
exports.cleanupAzCLIAccounts = cleanupAzCLIAccounts;
function cleanupAzPSAccounts() {
return __awaiter(this, void 0, void 0, function* () {
let psPath = yield io.which(AzPSUtils_1.AzPSConstants.PowerShell_CmdName, true);
core.debug(`PowerShell path: ${psPath}`);
core.debug("Importing Azure PowerShell module.");
AzPSUtils_1.AzPSUtils.setPSModulePathForGitHubRunner();
yield AzPSUtils_1.AzPSUtils.importLatestAzAccounts();
core.info("Clearing azure powershell accounts from the local cache.");
yield exec.exec(`"${psPath}"`, ["-Command", "Clear-AzContext", "-Scope", "Process"]);
yield exec.exec(`"${psPath}"`, ["-Command", "Clear-AzContext", "-Scope", "CurrentUser", "-Force", "-ErrorAction", "SilentlyContinue"]);
});
}
exports.cleanupAzPSAccounts = cleanupAzPSAccounts;
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cleanupAzPSAccounts = exports.cleanupAzCLIAccounts = exports.setUserAgent = void 0;
const core = __importStar(require("@actions/core"));
const exec = __importStar(require("@actions/exec"));
const io = __importStar(require("@actions/io"));
const crypto = __importStar(require("crypto"));
const AzPSUtils_1 = require("../PowerShell/AzPSUtils");
function setUserAgent() {
let usrAgentRepo = crypto.createHash('sha256').update(`${process.env.GITHUB_REPOSITORY}`).digest('hex');
let actionName = 'AzureLogin';
process.env.AZURE_HTTP_USER_AGENT = (!!process.env.AZURE_HTTP_USER_AGENT ? `${process.env.AZURE_HTTP_USER_AGENT} ` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`;
process.env.AZUREPS_HOST_ENVIRONMENT = (!!process.env.AZUREPS_HOST_ENVIRONMENT ? `${process.env.AZUREPS_HOST_ENVIRONMENT} ` : '') + `GITHUBACTIONS/${actionName}@v1_${usrAgentRepo}`;
}
exports.setUserAgent = setUserAgent;
function cleanupAzCLIAccounts() {
return __awaiter(this, void 0, void 0, function* () {
let azPath = yield io.which("az", true);
if (!azPath) {
throw new Error("Azure CLI is not found in the runner.");
}
core.debug(`Azure CLI path: ${azPath}`);
core.info("Clearing azure cli accounts from the local cache.");
yield exec.exec(`"${azPath}"`, ["account", "clear"]);
});
}
exports.cleanupAzCLIAccounts = cleanupAzCLIAccounts;
function cleanupAzPSAccounts() {
return __awaiter(this, void 0, void 0, function* () {
let psPath = yield io.which(AzPSUtils_1.AzPSConstants.PowerShell_CmdName, true);
if (!psPath) {
throw new Error("PowerShell is not found in the runner.");
}
core.debug(`PowerShell path: ${psPath}`);
core.debug("Importing Azure PowerShell module.");
AzPSUtils_1.AzPSUtils.setPSModulePathForGitHubRunner();
yield AzPSUtils_1.AzPSUtils.importLatestAzAccounts();
core.info("Clearing azure powershell accounts from the local cache.");
yield exec.exec(`"${psPath}"`, ["-Command", "Clear-AzContext", "-Scope", "Process"]);
yield exec.exec(`"${psPath}"`, ["-Command", "Clear-AzContext", "-Scope", "CurrentUser", "-Force", "-ErrorAction", "SilentlyContinue"]);
});
}
exports.cleanupAzPSAccounts = cleanupAzPSAccounts;

View File

@@ -1,63 +1,63 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const Utils_1 = require("./common/Utils");
const AzPSLogin_1 = require("./PowerShell/AzPSLogin");
const LoginConfig_1 = require("./common/LoginConfig");
const AzureCliLogin_1 = require("./Cli/AzureCliLogin");
function main() {
return __awaiter(this, void 0, void 0, function* () {
try {
(0, Utils_1.setUserAgent)();
// prepare the login configuration
var loginConfig = new LoginConfig_1.LoginConfig();
yield loginConfig.initialize();
yield loginConfig.validate();
// login to Azure CLI
var cliLogin = new AzureCliLogin_1.AzureCliLogin(loginConfig);
yield cliLogin.login();
//login to Azure PowerShell
if (loginConfig.enableAzPSSession) {
var psLogin = new AzPSLogin_1.AzPSLogin(loginConfig);
yield psLogin.login();
}
}
catch (error) {
core.setFailed(`Login failed with ${error}. Double check if the 'auth-type' is correct. Refer to https://github.com/Azure/login#readme for more information.`);
core.debug(error.stack);
}
});
}
main();
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const Utils_1 = require("./common/Utils");
const AzPSLogin_1 = require("./PowerShell/AzPSLogin");
const LoginConfig_1 = require("./common/LoginConfig");
const AzureCliLogin_1 = require("./Cli/AzureCliLogin");
function main() {
return __awaiter(this, void 0, void 0, function* () {
try {
(0, Utils_1.setUserAgent)();
// prepare the login configuration
var loginConfig = new LoginConfig_1.LoginConfig();
yield loginConfig.initialize();
yield loginConfig.validate();
// login to Azure CLI
var cliLogin = new AzureCliLogin_1.AzureCliLogin(loginConfig);
yield cliLogin.login();
//login to Azure PowerShell
if (loginConfig.enableAzPSSession) {
var psLogin = new AzPSLogin_1.AzPSLogin(loginConfig);
yield psLogin.login();
}
}
catch (error) {
core.setFailed(`Login failed with ${error}. Double check if the 'auth-type' is correct. Refer to https://github.com/Azure/login#readme for more information.`);
core.debug(error.stack);
}
});
}
main();

View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\update-browserslist-db\cli.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\update-browserslist-db\cli.js" %*

34
node_modules/.bin/browserslist.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\browserslist\cli.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\browserslist\cli.js" %*

34
node_modules/.bin/esparse.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esprima\bin\esparse.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esprima\bin\esparse.js" %*

34
node_modules/.bin/esvalidate.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esprima\bin\esvalidate.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esprima\bin\esvalidate.js" %*

View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\import-local\fixtures\cli.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\import-local\fixtures\cli.js" %*

34
node_modules/.bin/jest.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\jest\bin\jest.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\jest\bin\jest.js" %*

34
node_modules/.bin/js-yaml.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\js-yaml\bin\js-yaml.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\js-yaml\bin\js-yaml.js" %*

34
node_modules/.bin/jsesc.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\jsesc\bin\jsesc" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\jsesc\bin\jsesc" %*

34
node_modules/.bin/json5.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\json5\lib\cli.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\json5\lib\cli.js" %*

34
node_modules/.bin/node-which.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %*

34
node_modules/.bin/package-lock.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\package-lock\bin\package-lock.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\package-lock\bin\package-lock.js" %*

34
node_modules/.bin/parser.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\@babel\parser\bin\babel-parser.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\@babel\parser\bin\babel-parser.js" %*

34
node_modules/.bin/resolve.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\resolve\bin\resolve" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\resolve\bin\resolve" %*

34
node_modules/.bin/semver.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %*

34
node_modules/.bin/ts-jest.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-jest\cli.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-jest\cli.js" %*

34
node_modules/.bin/tsc.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsc" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsc" %*

34
node_modules/.bin/tsserver.cmd generated vendored
View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsserver" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsserver" %*

View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\bin\uuid" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\bin\uuid" %*

View File

@@ -1,107 +1,107 @@
//this will affect all the git repos
git config --global core.excludesfile ~/.gitignore
//update files since .ignore won't if already tracked
git rm --cached <file>
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
# Icon?
ehthumbs.db
Thumbs.db
.cache
.project
.settings
.tmproj
*.esproj
nbproject
# Numerous always-ignore extensions #
#####################################
*.diff
*.err
*.orig
*.rej
*.swn
*.swo
*.swp
*.vi
*~
*.sass-cache
*.grunt
*.tmp
# Dreamweaver added files #
###########################
_notes
dwsync.xml
# Komodo #
###########################
*.komodoproject
.komodotools
# Node #
#####################
node_modules
# Bower #
#####################
bower_components
# Folders to ignore #
#####################
.hg
.svn
.CVS
intermediate
publish
.idea
.graphics
_test
_archive
uploads
tmp
# Vim files to ignore #
#######################
.VimballRecord
.netrwhist
bundle.*
//this will affect all the git repos
git config --global core.excludesfile ~/.gitignore
//update files since .ignore won't if already tracked
git rm --cached <file>
# Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
*.sql
*.sqlite
# OS generated files #
######################
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
# Icon?
ehthumbs.db
Thumbs.db
.cache
.project
.settings
.tmproj
*.esproj
nbproject
# Numerous always-ignore extensions #
#####################################
*.diff
*.err
*.orig
*.rej
*.swn
*.swo
*.swp
*.vi
*~
*.sass-cache
*.grunt
*.tmp
# Dreamweaver added files #
###########################
_notes
dwsync.xml
# Komodo #
###########################
*.komodoproject
.komodotools
# Node #
#####################
node_modules
# Bower #
#####################
bower_components
# Folders to ignore #
#####################
.hg
.svn
.CVS
intermediate
publish
.idea
.graphics
_test
_archive
uploads
tmp
# Vim files to ignore #
#######################
.VimballRecord
.netrwhist
bundle.*
_demo

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
'use strict'
var names = require('./');
var assert = require('assert');
assert.deepEqual(names.red, [255,0,0]);
assert.deepEqual(names.aliceblue, [240,248,255]);
'use strict'
var names = require('./');
var assert = require('assert');
assert.deepEqual(names.red, [255,0,0]);
assert.deepEqual(names.aliceblue, [240,248,255]);

View File

@@ -1,28 +1,28 @@
import { ValueError } from '../errors/index';
import * as Types from '../typebox';
export declare 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 validation code used to validate this type. */
Code(): string;
/** Returns an iterator for each error in this value. */
Errors(value: unknown): IterableIterator<ValueError>;
/** Returns true if the value matches the given type. */
Check(value: unknown): value is Types.Static<T>;
}
export declare namespace Property {
function Check(propertyName: string): boolean;
}
export declare class TypeCompilerUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
/** Compiles Types for Runtime Type Checking */
export declare namespace TypeCompiler {
/** 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>;
}
import { ValueError } from '../errors/index';
import * as Types from '../typebox';
export declare 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 validation code used to validate this type. */
Code(): string;
/** Returns an iterator for each error in this value. */
Errors(value: unknown): IterableIterator<ValueError>;
/** Returns true if the value matches the given type. */
Check(value: unknown): value is Types.Static<T>;
}
export declare namespace Property {
function Check(propertyName: string): boolean;
}
export declare class TypeCompilerUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
/** Compiles Types for Runtime Type Checking */
export declare namespace TypeCompiler {
/** 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

@@ -1,409 +1,409 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/compiler
The MIT License (MIT)
Copyright (c) 2022 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.TypeCompilerUnknownTypeError = exports.Property = exports.TypeCheck = void 0;
const index_1 = require("../errors/index");
const index_2 = require("../guard/index");
const index_3 = require("../format/index");
const Types = require("../typebox");
// -------------------------------------------------------------------
// TypeCheck
// -------------------------------------------------------------------
class TypeCheck {
constructor(schema, references, checkFunc, code) {
this.schema = schema;
this.references = references;
this.checkFunc = checkFunc;
this.code = code;
}
/** Returns the generated validation 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 given type. */
Check(value) {
return this.checkFunc(value);
}
}
exports.TypeCheck = TypeCheck;
// -------------------------------------------------------------------
// Property
// -------------------------------------------------------------------
var Property;
(function (Property) {
function DollarSign(code) {
return code === 36;
}
function Underscore(code) {
return code === 95;
}
function Numeric(code) {
return code >= 48 && code <= 57;
}
function Alpha(code) {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
function Check(propertyName) {
if (propertyName.length === 0)
return false;
{
const code = propertyName.charCodeAt(0);
if (!(DollarSign(code) || Underscore(code) || Alpha(code))) {
return false;
}
}
for (let i = 1; i < propertyName.length; i++) {
const code = propertyName.charCodeAt(i);
if (!(DollarSign(code) || Underscore(code) || Alpha(code) || Numeric(code))) {
return false;
}
}
return true;
}
Property.Check = Check;
})(Property = exports.Property || (exports.Property = {}));
// -------------------------------------------------------------------
// TypeCompiler
// -------------------------------------------------------------------
class TypeCompilerUnknownTypeError extends Error {
constructor(schema) {
super('TypeCompiler: Unknown type');
this.schema = schema;
}
}
exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
/** Compiles Types for Runtime Type Checking */
var TypeCompiler;
(function (TypeCompiler) {
// -------------------------------------------------------------------
// Types
// -------------------------------------------------------------------
function* Any(schema, value) {
yield '(true)';
}
function* Array(schema, value) {
const expression = CreateExpression(schema.items, 'value');
if (schema.minItems !== undefined)
yield `(${value}.length >= ${schema.minItems})`;
if (schema.maxItems !== undefined)
yield `(${value}.length <= ${schema.maxItems})`;
if (schema.uniqueItems !== undefined)
yield `(new Set(${value}).size === ${value}.length)`;
yield `(Array.isArray(${value}) && ${value}.every(value => ${expression}))`;
}
function* Boolean(schema, value) {
yield `(typeof ${value} === 'boolean')`;
}
function* Constructor(schema, value) {
yield* Visit(schema.returns, `${value}.prototype`);
}
function* Function(schema, value) {
yield `(typeof ${value} === 'function')`;
}
function* Integer(schema, value) {
yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
if (schema.multipleOf !== undefined)
yield `(${value} % ${schema.multipleOf} === 0)`;
if (schema.exclusiveMinimum !== undefined)
yield `(${value} > ${schema.exclusiveMinimum})`;
if (schema.exclusiveMaximum !== undefined)
yield `(${value} < ${schema.exclusiveMaximum})`;
if (schema.minimum !== undefined)
yield `(${value} >= ${schema.minimum})`;
if (schema.maximum !== undefined)
yield `(${value} <= ${schema.maximum})`;
}
function* Literal(schema, value) {
if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
yield `(${value} === ${schema.const})`;
}
else {
yield `(${value} === '${schema.const}')`;
}
}
function* Never(schema, value) {
yield `(false)`;
}
function* Null(schema, value) {
yield `(${value} === null)`;
}
function* Number(schema, value) {
yield `(typeof ${value} === 'number')`;
if (schema.multipleOf !== undefined)
yield `(${value} % ${schema.multipleOf} === 0)`;
if (schema.exclusiveMinimum !== undefined)
yield `(${value} > ${schema.exclusiveMinimum})`;
if (schema.exclusiveMaximum !== undefined)
yield `(${value} < ${schema.exclusiveMaximum})`;
if (schema.minimum !== undefined)
yield `(${value} >= ${schema.minimum})`;
if (schema.maximum !== undefined)
yield `(${value} <= ${schema.maximum})`;
}
function* Object(schema, value) {
yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
if (schema.minProperties !== undefined)
yield `(Object.keys(${value}).length >= ${schema.minProperties})`;
if (schema.maxProperties !== undefined)
yield `(Object.keys(${value}).length <= ${schema.maxProperties})`;
const propertyKeys = globalThis.Object.keys(schema.properties);
if (schema.additionalProperties === false) {
// Optimization: If the property key length matches the required keys length
// then we only need check that the values property key length matches that
// of the property key length. This is because exhaustive testing for values
// will occur in subsequent property tests.
if (schema.required && schema.required.length === propertyKeys.length) {
yield `(Object.keys(${value}).length === ${propertyKeys.length})`;
}
else {
const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `(Object.keys(${value}).every(key => ${keys}.includes(key)))`;
}
}
if (index_2.TypeGuard.TSchema(schema.additionalProperties)) {
const expression = CreateExpression(schema.additionalProperties, 'value[key]');
const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `(Object.keys(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
}
for (const propertyKey of propertyKeys) {
const memberExpression = Property.Check(propertyKey) ? `${value}.${propertyKey}` : `${value}['${propertyKey}']`;
const propertySchema = schema.properties[propertyKey];
if (schema.required && schema.required.includes(propertyKey)) {
yield* Visit(propertySchema, memberExpression);
}
else {
const expression = CreateExpression(propertySchema, memberExpression);
yield `(${memberExpression} === undefined ? true : (${expression}))`;
}
}
}
function* Promise(schema, value) {
yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
}
function* Record(schema, value) {
yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const local = PushLocal(`new RegExp(/${keyPattern}/)`);
yield `(Object.keys(${value}).every(key => ${local}.test(key)))`;
const expression = CreateExpression(valueSchema, 'value');
yield `(Object.values(${value}).every(value => ${expression}))`;
}
function* Ref(schema, value) {
// 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 (names.has(schema.$ref))
return yield `(${CreateFunctionName(schema.$ref)}(${value}))`;
if (!referenceMap.has(schema.$ref))
throw Error(`TypeCompiler.Ref: Cannot de-reference schema with $id '${schema.$ref}'`);
const reference = referenceMap.get(schema.$ref);
yield* Visit(reference, value);
}
function* Self(schema, value) {
const func = CreateFunctionName(schema.$ref);
yield `(${func}(${value}))`;
}
function* String(schema, value) {
yield `(typeof ${value} === 'string')`;
if (schema.minLength !== undefined) {
yield `(${value}.length >= ${schema.minLength})`;
}
if (schema.maxLength !== undefined) {
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* Tuple(schema, 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], `${value}[${i}]`);
yield `(${expression})`;
}
}
function* Undefined(schema, value) {
yield `(${value} === undefined)`;
}
function* Union(schema, value) {
const expressions = schema.anyOf.map((schema) => CreateExpression(schema, value));
yield `(${expressions.join(' || ')})`;
}
function* Uint8Array(schema, value) {
yield `(${value} instanceof Uint8Array)`;
if (schema.maxByteLength)
yield `(${value}.length <= ${schema.maxByteLength})`;
if (schema.minByteLength)
yield `(${value}.length >= ${schema.minByteLength})`;
}
function* Unknown(schema, value) {
yield '(true)';
}
function* Void(schema, value) {
yield `(${value} === null)`;
}
function* Visit(schema, value) {
// 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 (schema.$id && !names.has(schema.$id)) {
names.add(schema.$id);
const name = CreateFunctionName(schema.$id);
const body = CreateFunction(name, schema, 'value');
PushFunction(body);
yield `(${name}(${value}))`;
return;
}
const anySchema = schema;
switch (anySchema[Types.Kind]) {
case 'Any':
return yield* Any(anySchema, value);
case 'Array':
return yield* Array(anySchema, value);
case 'Boolean':
return yield* Boolean(anySchema, value);
case 'Constructor':
return yield* Constructor(anySchema, value);
case 'Function':
return yield* Function(anySchema, value);
case 'Integer':
return yield* Integer(anySchema, value);
case 'Literal':
return yield* Literal(anySchema, value);
case 'Never':
return yield* Never(anySchema, value);
case 'Null':
return yield* Null(anySchema, value);
case 'Number':
return yield* Number(anySchema, value);
case 'Object':
return yield* Object(anySchema, value);
case 'Promise':
return yield* Promise(anySchema, value);
case 'Record':
return yield* Record(anySchema, value);
case 'Ref':
return yield* Ref(anySchema, value);
case 'Self':
return yield* Self(anySchema, value);
case 'String':
return yield* String(anySchema, value);
case 'Tuple':
return yield* Tuple(anySchema, value);
case 'Undefined':
return yield* Undefined(anySchema, value);
case 'Union':
return yield* Union(anySchema, value);
case 'Uint8Array':
return yield* Uint8Array(anySchema, value);
case 'Unknown':
return yield* Unknown(anySchema, value);
case 'Void':
return yield* Void(anySchema, value);
default:
throw new TypeCompilerUnknownTypeError(schema);
}
}
// -------------------------------------------------------------------
// Compile State
// -------------------------------------------------------------------
const referenceMap = new Map();
const locals = new Set(); // local variables and functions
const names = new Set(); // cache of local functions
function ResetCompiler() {
referenceMap.clear();
locals.clear();
names.clear();
}
function AddReferences(schemas = []) {
for (const schema of schemas) {
if (!schema.$id)
throw new Error(`TypeCompiler: Referenced schemas must specify an $id.`);
if (referenceMap.has(schema.$id))
throw new Error(`TypeCompiler: Duplicate schema $id found for '${schema.$id}'`);
referenceMap.set(schema.$id, schema);
}
}
function CreateExpression(schema, value) {
return [...Visit(schema, value)].join(' && ');
}
function CreateFunctionName($id) {
return `check_${$id.replace(/-/g, '_')}`;
}
function CreateFunction(name, schema, value) {
const expression = [...Visit(schema, value)].map((condition) => ` ${condition}`).join(' &&\n');
return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
}
function PushFunction(functionBody) {
locals.add(functionBody);
}
function PushLocal(expression) {
const local = `local_${locals.size}`;
locals.add(`const ${local} = ${expression}`);
return local;
}
function GetLocals() {
return [...locals.values()];
}
// -------------------------------------------------------------------
// Compile
// -------------------------------------------------------------------
function Build(schema, references = []) {
ResetCompiler();
AddReferences(references);
const check = CreateFunction('check', schema, 'value');
const locals = GetLocals();
return `${locals.join('\n')}\nreturn ${check}`;
}
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
function Compile(schema, references = []) {
index_2.TypeGuard.Assert(schema, references);
const code = Build(schema, references);
const func1 = globalThis.Function('format', code);
const func2 = func1((format, value) => {
if (!index_3.Format.Has(format))
return false;
const func = index_3.Format.Get(format);
return func(value);
});
return new TypeCheck(schema, references, func2, code);
}
TypeCompiler.Compile = Compile;
})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/compiler
The MIT License (MIT)
Copyright (c) 2022 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.TypeCompilerUnknownTypeError = exports.Property = exports.TypeCheck = void 0;
const index_1 = require("../errors/index");
const index_2 = require("../guard/index");
const index_3 = require("../format/index");
const Types = require("../typebox");
// -------------------------------------------------------------------
// TypeCheck
// -------------------------------------------------------------------
class TypeCheck {
constructor(schema, references, checkFunc, code) {
this.schema = schema;
this.references = references;
this.checkFunc = checkFunc;
this.code = code;
}
/** Returns the generated validation 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 given type. */
Check(value) {
return this.checkFunc(value);
}
}
exports.TypeCheck = TypeCheck;
// -------------------------------------------------------------------
// Property
// -------------------------------------------------------------------
var Property;
(function (Property) {
function DollarSign(code) {
return code === 36;
}
function Underscore(code) {
return code === 95;
}
function Numeric(code) {
return code >= 48 && code <= 57;
}
function Alpha(code) {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
}
function Check(propertyName) {
if (propertyName.length === 0)
return false;
{
const code = propertyName.charCodeAt(0);
if (!(DollarSign(code) || Underscore(code) || Alpha(code))) {
return false;
}
}
for (let i = 1; i < propertyName.length; i++) {
const code = propertyName.charCodeAt(i);
if (!(DollarSign(code) || Underscore(code) || Alpha(code) || Numeric(code))) {
return false;
}
}
return true;
}
Property.Check = Check;
})(Property = exports.Property || (exports.Property = {}));
// -------------------------------------------------------------------
// TypeCompiler
// -------------------------------------------------------------------
class TypeCompilerUnknownTypeError extends Error {
constructor(schema) {
super('TypeCompiler: Unknown type');
this.schema = schema;
}
}
exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
/** Compiles Types for Runtime Type Checking */
var TypeCompiler;
(function (TypeCompiler) {
// -------------------------------------------------------------------
// Types
// -------------------------------------------------------------------
function* Any(schema, value) {
yield '(true)';
}
function* Array(schema, value) {
const expression = CreateExpression(schema.items, 'value');
if (schema.minItems !== undefined)
yield `(${value}.length >= ${schema.minItems})`;
if (schema.maxItems !== undefined)
yield `(${value}.length <= ${schema.maxItems})`;
if (schema.uniqueItems !== undefined)
yield `(new Set(${value}).size === ${value}.length)`;
yield `(Array.isArray(${value}) && ${value}.every(value => ${expression}))`;
}
function* Boolean(schema, value) {
yield `(typeof ${value} === 'boolean')`;
}
function* Constructor(schema, value) {
yield* Visit(schema.returns, `${value}.prototype`);
}
function* Function(schema, value) {
yield `(typeof ${value} === 'function')`;
}
function* Integer(schema, value) {
yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
if (schema.multipleOf !== undefined)
yield `(${value} % ${schema.multipleOf} === 0)`;
if (schema.exclusiveMinimum !== undefined)
yield `(${value} > ${schema.exclusiveMinimum})`;
if (schema.exclusiveMaximum !== undefined)
yield `(${value} < ${schema.exclusiveMaximum})`;
if (schema.minimum !== undefined)
yield `(${value} >= ${schema.minimum})`;
if (schema.maximum !== undefined)
yield `(${value} <= ${schema.maximum})`;
}
function* Literal(schema, value) {
if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
yield `(${value} === ${schema.const})`;
}
else {
yield `(${value} === '${schema.const}')`;
}
}
function* Never(schema, value) {
yield `(false)`;
}
function* Null(schema, value) {
yield `(${value} === null)`;
}
function* Number(schema, value) {
yield `(typeof ${value} === 'number')`;
if (schema.multipleOf !== undefined)
yield `(${value} % ${schema.multipleOf} === 0)`;
if (schema.exclusiveMinimum !== undefined)
yield `(${value} > ${schema.exclusiveMinimum})`;
if (schema.exclusiveMaximum !== undefined)
yield `(${value} < ${schema.exclusiveMaximum})`;
if (schema.minimum !== undefined)
yield `(${value} >= ${schema.minimum})`;
if (schema.maximum !== undefined)
yield `(${value} <= ${schema.maximum})`;
}
function* Object(schema, value) {
yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
if (schema.minProperties !== undefined)
yield `(Object.keys(${value}).length >= ${schema.minProperties})`;
if (schema.maxProperties !== undefined)
yield `(Object.keys(${value}).length <= ${schema.maxProperties})`;
const propertyKeys = globalThis.Object.keys(schema.properties);
if (schema.additionalProperties === false) {
// Optimization: If the property key length matches the required keys length
// then we only need check that the values property key length matches that
// of the property key length. This is because exhaustive testing for values
// will occur in subsequent property tests.
if (schema.required && schema.required.length === propertyKeys.length) {
yield `(Object.keys(${value}).length === ${propertyKeys.length})`;
}
else {
const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `(Object.keys(${value}).every(key => ${keys}.includes(key)))`;
}
}
if (index_2.TypeGuard.TSchema(schema.additionalProperties)) {
const expression = CreateExpression(schema.additionalProperties, 'value[key]');
const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `(Object.keys(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
}
for (const propertyKey of propertyKeys) {
const memberExpression = Property.Check(propertyKey) ? `${value}.${propertyKey}` : `${value}['${propertyKey}']`;
const propertySchema = schema.properties[propertyKey];
if (schema.required && schema.required.includes(propertyKey)) {
yield* Visit(propertySchema, memberExpression);
}
else {
const expression = CreateExpression(propertySchema, memberExpression);
yield `(${memberExpression} === undefined ? true : (${expression}))`;
}
}
}
function* Promise(schema, value) {
yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
}
function* Record(schema, value) {
yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const local = PushLocal(`new RegExp(/${keyPattern}/)`);
yield `(Object.keys(${value}).every(key => ${local}.test(key)))`;
const expression = CreateExpression(valueSchema, 'value');
yield `(Object.values(${value}).every(value => ${expression}))`;
}
function* Ref(schema, value) {
// 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 (names.has(schema.$ref))
return yield `(${CreateFunctionName(schema.$ref)}(${value}))`;
if (!referenceMap.has(schema.$ref))
throw Error(`TypeCompiler.Ref: Cannot de-reference schema with $id '${schema.$ref}'`);
const reference = referenceMap.get(schema.$ref);
yield* Visit(reference, value);
}
function* Self(schema, value) {
const func = CreateFunctionName(schema.$ref);
yield `(${func}(${value}))`;
}
function* String(schema, value) {
yield `(typeof ${value} === 'string')`;
if (schema.minLength !== undefined) {
yield `(${value}.length >= ${schema.minLength})`;
}
if (schema.maxLength !== undefined) {
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* Tuple(schema, 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], `${value}[${i}]`);
yield `(${expression})`;
}
}
function* Undefined(schema, value) {
yield `(${value} === undefined)`;
}
function* Union(schema, value) {
const expressions = schema.anyOf.map((schema) => CreateExpression(schema, value));
yield `(${expressions.join(' || ')})`;
}
function* Uint8Array(schema, value) {
yield `(${value} instanceof Uint8Array)`;
if (schema.maxByteLength)
yield `(${value}.length <= ${schema.maxByteLength})`;
if (schema.minByteLength)
yield `(${value}.length >= ${schema.minByteLength})`;
}
function* Unknown(schema, value) {
yield '(true)';
}
function* Void(schema, value) {
yield `(${value} === null)`;
}
function* Visit(schema, value) {
// 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 (schema.$id && !names.has(schema.$id)) {
names.add(schema.$id);
const name = CreateFunctionName(schema.$id);
const body = CreateFunction(name, schema, 'value');
PushFunction(body);
yield `(${name}(${value}))`;
return;
}
const anySchema = schema;
switch (anySchema[Types.Kind]) {
case 'Any':
return yield* Any(anySchema, value);
case 'Array':
return yield* Array(anySchema, value);
case 'Boolean':
return yield* Boolean(anySchema, value);
case 'Constructor':
return yield* Constructor(anySchema, value);
case 'Function':
return yield* Function(anySchema, value);
case 'Integer':
return yield* Integer(anySchema, value);
case 'Literal':
return yield* Literal(anySchema, value);
case 'Never':
return yield* Never(anySchema, value);
case 'Null':
return yield* Null(anySchema, value);
case 'Number':
return yield* Number(anySchema, value);
case 'Object':
return yield* Object(anySchema, value);
case 'Promise':
return yield* Promise(anySchema, value);
case 'Record':
return yield* Record(anySchema, value);
case 'Ref':
return yield* Ref(anySchema, value);
case 'Self':
return yield* Self(anySchema, value);
case 'String':
return yield* String(anySchema, value);
case 'Tuple':
return yield* Tuple(anySchema, value);
case 'Undefined':
return yield* Undefined(anySchema, value);
case 'Union':
return yield* Union(anySchema, value);
case 'Uint8Array':
return yield* Uint8Array(anySchema, value);
case 'Unknown':
return yield* Unknown(anySchema, value);
case 'Void':
return yield* Void(anySchema, value);
default:
throw new TypeCompilerUnknownTypeError(schema);
}
}
// -------------------------------------------------------------------
// Compile State
// -------------------------------------------------------------------
const referenceMap = new Map();
const locals = new Set(); // local variables and functions
const names = new Set(); // cache of local functions
function ResetCompiler() {
referenceMap.clear();
locals.clear();
names.clear();
}
function AddReferences(schemas = []) {
for (const schema of schemas) {
if (!schema.$id)
throw new Error(`TypeCompiler: Referenced schemas must specify an $id.`);
if (referenceMap.has(schema.$id))
throw new Error(`TypeCompiler: Duplicate schema $id found for '${schema.$id}'`);
referenceMap.set(schema.$id, schema);
}
}
function CreateExpression(schema, value) {
return [...Visit(schema, value)].join(' && ');
}
function CreateFunctionName($id) {
return `check_${$id.replace(/-/g, '_')}`;
}
function CreateFunction(name, schema, value) {
const expression = [...Visit(schema, value)].map((condition) => ` ${condition}`).join(' &&\n');
return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
}
function PushFunction(functionBody) {
locals.add(functionBody);
}
function PushLocal(expression) {
const local = `local_${locals.size}`;
locals.add(`const ${local} = ${expression}`);
return local;
}
function GetLocals() {
return [...locals.values()];
}
// -------------------------------------------------------------------
// Compile
// -------------------------------------------------------------------
function Build(schema, references = []) {
ResetCompiler();
AddReferences(references);
const check = CreateFunction('check', schema, 'value');
const locals = GetLocals();
return `${locals.join('\n')}\nreturn ${check}`;
}
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
function Compile(schema, references = []) {
index_2.TypeGuard.Assert(schema, references);
const code = Build(schema, references);
const func1 = globalThis.Function('format', code);
const func2 = func1((format, value) => {
if (!index_3.Format.Has(format))
return false;
const func = index_3.Format.Get(format);
return func(value);
});
return new TypeCheck(schema, references, func2, code);
}
TypeCompiler.Compile = Compile;
})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));

View File

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

View File

@@ -1,47 +1,47 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/compiler
The MIT License (MIT)
Copyright (c) 2022 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);
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/compiler
The MIT License (MIT)
Copyright (c) 2022 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

@@ -1,17 +1,17 @@
import * as Types from '../typebox';
export declare type TExtends<L extends Types.TSchema, R extends Types.TSchema, T extends Types.TSchema, U extends Types.TSchema> = Types.Static<L> extends Types.Static<R> ? T : U;
export interface TExclude<T extends Types.TUnion, U extends Types.TUnion> extends Types.TUnion<any[]> {
static: Exclude<Types.Static<T, this['params']>, Types.Static<U, this['params']>>;
}
export interface TExtract<T extends Types.TSchema, U extends Types.TUnion> extends Types.TUnion<any[]> {
static: Extract<Types.Static<T, this['params']>, Types.Static<U, this['params']>>;
}
/** Conditional Types */
export declare namespace Conditional {
/** (Experimental) Creates a conditional expression type */
function Extends<L extends Types.TSchema, R extends Types.TSchema, T extends Types.TSchema, U extends Types.TSchema>(left: L, right: R, ok: T, fail: U): TExtends<L, R, T, U>;
/** (Experimental) Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers. */
function Exclude<T extends Types.TUnion, U extends Types.TUnion>(unionType: T, excludedMembers: U, options?: Types.SchemaOptions): TExclude<T, U>;
/** (Experimental) Constructs a type by extracting from Type all union members that are assignable to Union. */
function Extract<T extends Types.TSchema, U extends Types.TUnion>(type: T, union: U, options?: Types.SchemaOptions): TExtract<T, U>;
}
import * as Types from '../typebox';
export declare type TExtends<L extends Types.TSchema, R extends Types.TSchema, T extends Types.TSchema, U extends Types.TSchema> = Types.Static<L> extends Types.Static<R> ? T : U;
export interface TExclude<T extends Types.TUnion, U extends Types.TUnion> extends Types.TUnion<any[]> {
static: Exclude<Types.Static<T, this['params']>, Types.Static<U, this['params']>>;
}
export interface TExtract<T extends Types.TSchema, U extends Types.TUnion> extends Types.TUnion<any[]> {
static: Extract<Types.Static<T, this['params']>, Types.Static<U, this['params']>>;
}
/** Conditional Types */
export declare namespace Conditional {
/** (Experimental) Creates a conditional expression type */
function Extends<L extends Types.TSchema, R extends Types.TSchema, T extends Types.TSchema, U extends Types.TSchema>(left: L, right: R, ok: T, fail: U): TExtends<L, R, T, U>;
/** (Experimental) Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers. */
function Exclude<T extends Types.TUnion, U extends Types.TUnion>(unionType: T, excludedMembers: U, options?: Types.SchemaOptions): TExclude<T, U>;
/** (Experimental) Constructs a type by extracting from Type all union members that are assignable to Union. */
function Extract<T extends Types.TSchema, U extends Types.TUnion>(type: T, union: U, options?: Types.SchemaOptions): TExtract<T, U>;
}

View File

@@ -1,91 +1,91 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/conditional
The MIT License (MIT)
Copyright (c) 2022 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.Conditional = void 0;
const Types = require("../typebox");
const structural_1 = require("./structural");
const index_1 = require("../guard/index");
/** Conditional Types */
var Conditional;
(function (Conditional) {
/** (Experimental) Creates a conditional expression type */
function Extends(left, right, ok, fail) {
switch (structural_1.Structural.Check(left, right)) {
case structural_1.StructuralResult.Union:
return Types.Type.Union([Clone(ok), Clone(fail)]);
case structural_1.StructuralResult.True:
return Clone(ok);
case structural_1.StructuralResult.False:
return Clone(fail);
}
}
Conditional.Extends = Extends;
/** (Experimental) Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers. */
function Exclude(unionType, excludedMembers, options = {}) {
const anyOf = unionType.anyOf
.filter((schema) => {
const check = structural_1.Structural.Check(schema, excludedMembers);
return !(check === structural_1.StructuralResult.True || check === structural_1.StructuralResult.Union);
})
.map((schema) => Clone(schema));
return { ...options, [Types.Kind]: 'Union', anyOf };
}
Conditional.Exclude = Exclude;
/** (Experimental) Constructs a type by extracting from Type all union members that are assignable to Union. */
function Extract(type, union, options = {}) {
if (index_1.TypeGuard.TUnion(type)) {
const anyOf = type.anyOf.filter((schema) => structural_1.Structural.Check(schema, union) === structural_1.StructuralResult.True).map((schema) => Clone(schema));
return { ...options, [Types.Kind]: 'Union', anyOf };
}
else {
const anyOf = union.anyOf.filter((schema) => structural_1.Structural.Check(type, schema) === structural_1.StructuralResult.True).map((schema) => Clone(schema));
return { ...options, [Types.Kind]: 'Union', anyOf };
}
}
Conditional.Extract = Extract;
function Clone(value) {
const isObject = (object) => typeof object === 'object' && object !== null && !Array.isArray(object);
const isArray = (object) => typeof object === 'object' && object !== null && Array.isArray(object);
if (isObject(value)) {
return Object.keys(value).reduce((acc, key) => ({
...acc,
[key]: Clone(value[key]),
}), Object.getOwnPropertySymbols(value).reduce((acc, key) => ({
...acc,
[key]: Clone(value[key]),
}), {}));
}
else if (isArray(value)) {
return value.map((item) => Clone(item));
}
else {
return value;
}
}
})(Conditional = exports.Conditional || (exports.Conditional = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/conditional
The MIT License (MIT)
Copyright (c) 2022 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.Conditional = void 0;
const Types = require("../typebox");
const structural_1 = require("./structural");
const index_1 = require("../guard/index");
/** Conditional Types */
var Conditional;
(function (Conditional) {
/** (Experimental) Creates a conditional expression type */
function Extends(left, right, ok, fail) {
switch (structural_1.Structural.Check(left, right)) {
case structural_1.StructuralResult.Union:
return Types.Type.Union([Clone(ok), Clone(fail)]);
case structural_1.StructuralResult.True:
return Clone(ok);
case structural_1.StructuralResult.False:
return Clone(fail);
}
}
Conditional.Extends = Extends;
/** (Experimental) Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers. */
function Exclude(unionType, excludedMembers, options = {}) {
const anyOf = unionType.anyOf
.filter((schema) => {
const check = structural_1.Structural.Check(schema, excludedMembers);
return !(check === structural_1.StructuralResult.True || check === structural_1.StructuralResult.Union);
})
.map((schema) => Clone(schema));
return { ...options, [Types.Kind]: 'Union', anyOf };
}
Conditional.Exclude = Exclude;
/** (Experimental) Constructs a type by extracting from Type all union members that are assignable to Union. */
function Extract(type, union, options = {}) {
if (index_1.TypeGuard.TUnion(type)) {
const anyOf = type.anyOf.filter((schema) => structural_1.Structural.Check(schema, union) === structural_1.StructuralResult.True).map((schema) => Clone(schema));
return { ...options, [Types.Kind]: 'Union', anyOf };
}
else {
const anyOf = union.anyOf.filter((schema) => structural_1.Structural.Check(type, schema) === structural_1.StructuralResult.True).map((schema) => Clone(schema));
return { ...options, [Types.Kind]: 'Union', anyOf };
}
}
Conditional.Extract = Extract;
function Clone(value) {
const isObject = (object) => typeof object === 'object' && object !== null && !Array.isArray(object);
const isArray = (object) => typeof object === 'object' && object !== null && Array.isArray(object);
if (isObject(value)) {
return Object.keys(value).reduce((acc, key) => ({
...acc,
[key]: Clone(value[key]),
}), Object.getOwnPropertySymbols(value).reduce((acc, key) => ({
...acc,
[key]: Clone(value[key]),
}), {}));
}
else if (isArray(value)) {
return value.map((item) => Clone(item));
}
else {
return value;
}
}
})(Conditional = exports.Conditional || (exports.Conditional = {}));

View File

@@ -1,2 +1,2 @@
export * from './conditional';
export * from './structural';
export * from './conditional';
export * from './structural';

View File

@@ -1,45 +1,45 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/conditional
The MIT License (MIT)
Copyright (c) 2022 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("./conditional"), exports);
__exportStar(require("./structural"), exports);
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/conditional
The MIT License (MIT)
Copyright (c) 2022 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("./conditional"), exports);
__exportStar(require("./structural"), exports);

View File

@@ -1,11 +1,11 @@
import * as Types from '../typebox';
export declare enum StructuralResult {
Union = 0,
True = 1,
False = 2
}
/** Performs structural equivalence checks against TypeBox types. */
export declare namespace Structural {
/** Structurally tests if the left schema extends the right. */
function Check(left: Types.TSchema, right: Types.TSchema): StructuralResult;
}
import * as Types from '../typebox';
export declare enum StructuralResult {
Union = 0,
True = 1,
False = 2
}
/** Performs structural equivalence checks against TypeBox types. */
export declare namespace Structural {
/** Structurally tests if the left schema extends the right. */
function Check(left: Types.TSchema, right: Types.TSchema): StructuralResult;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,60 +1,60 @@
import * as Types from '../typebox';
export declare enum ValueErrorType {
Array = 0,
ArrayMinItems = 1,
ArrayMaxItems = 2,
ArrayUniqueItems = 3,
Boolean = 4,
Function = 5,
Integer = 6,
IntegerMultipleOf = 7,
IntegerExclusiveMinimum = 8,
IntegerExclusiveMaximum = 9,
IntegerMinimum = 10,
IntegerMaximum = 11,
Literal = 12,
Never = 13,
Null = 14,
Number = 15,
NumberMultipleOf = 16,
NumberExclusiveMinimum = 17,
NumberExclusiveMaximum = 18,
NumberMinumum = 19,
NumberMaximum = 20,
Object = 21,
ObjectMinProperties = 22,
ObjectMaxProperties = 23,
ObjectAdditionalProperties = 24,
ObjectRequiredProperties = 25,
Promise = 26,
RecordKeyNumeric = 27,
RecordKeyString = 28,
String = 29,
StringMinLength = 30,
StringMaxLength = 31,
StringPattern = 32,
StringFormatUnknown = 33,
StringFormat = 34,
TupleZeroLength = 35,
TupleLength = 36,
Undefined = 37,
Union = 38,
Uint8Array = 39,
Uint8ArrayMinByteLength = 40,
Uint8ArrayMaxByteLength = 41,
Void = 42
}
export interface ValueError {
type: ValueErrorType;
schema: Types.TSchema;
path: string;
value: unknown;
message: string;
}
export declare class ValueErrorsUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare namespace ValueErrors {
function Errors<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): IterableIterator<ValueError>;
}
import * as Types from '../typebox';
export declare enum ValueErrorType {
Array = 0,
ArrayMinItems = 1,
ArrayMaxItems = 2,
ArrayUniqueItems = 3,
Boolean = 4,
Function = 5,
Integer = 6,
IntegerMultipleOf = 7,
IntegerExclusiveMinimum = 8,
IntegerExclusiveMaximum = 9,
IntegerMinimum = 10,
IntegerMaximum = 11,
Literal = 12,
Never = 13,
Null = 14,
Number = 15,
NumberMultipleOf = 16,
NumberExclusiveMinimum = 17,
NumberExclusiveMaximum = 18,
NumberMinumum = 19,
NumberMaximum = 20,
Object = 21,
ObjectMinProperties = 22,
ObjectMaxProperties = 23,
ObjectAdditionalProperties = 24,
ObjectRequiredProperties = 25,
Promise = 26,
RecordKeyNumeric = 27,
RecordKeyString = 28,
String = 29,
StringMinLength = 30,
StringMaxLength = 31,
StringPattern = 32,
StringFormatUnknown = 33,
StringFormat = 34,
TupleZeroLength = 35,
TupleLength = 36,
Undefined = 37,
Union = 38,
Uint8Array = 39,
Uint8ArrayMinByteLength = 40,
Uint8ArrayMaxByteLength = 41,
Void = 42
}
export interface ValueError {
type: ValueErrorType;
schema: Types.TSchema;
path: string;
value: unknown;
message: string;
}
export declare class ValueErrorsUnknownTypeError extends Error {
readonly schema: Types.TSchema;
constructor(schema: Types.TSchema);
}
export declare namespace ValueErrors {
function Errors<T extends Types.TSchema>(schema: T, references: Types.TSchema[], value: any): IterableIterator<ValueError>;
}

View File

@@ -1,398 +1,398 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/errors
The MIT License (MIT)
Copyright (c) 2022 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.ValueErrors = exports.ValueErrorsUnknownTypeError = exports.ValueErrorType = void 0;
const Types = require("../typebox");
const index_1 = require("../format/index");
// -------------------------------------------------------------------
// 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["Boolean"] = 4] = "Boolean";
ValueErrorType[ValueErrorType["Function"] = 5] = "Function";
ValueErrorType[ValueErrorType["Integer"] = 6] = "Integer";
ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 7] = "IntegerMultipleOf";
ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 8] = "IntegerExclusiveMinimum";
ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 9] = "IntegerExclusiveMaximum";
ValueErrorType[ValueErrorType["IntegerMinimum"] = 10] = "IntegerMinimum";
ValueErrorType[ValueErrorType["IntegerMaximum"] = 11] = "IntegerMaximum";
ValueErrorType[ValueErrorType["Literal"] = 12] = "Literal";
ValueErrorType[ValueErrorType["Never"] = 13] = "Never";
ValueErrorType[ValueErrorType["Null"] = 14] = "Null";
ValueErrorType[ValueErrorType["Number"] = 15] = "Number";
ValueErrorType[ValueErrorType["NumberMultipleOf"] = 16] = "NumberMultipleOf";
ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 17] = "NumberExclusiveMinimum";
ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 18] = "NumberExclusiveMaximum";
ValueErrorType[ValueErrorType["NumberMinumum"] = 19] = "NumberMinumum";
ValueErrorType[ValueErrorType["NumberMaximum"] = 20] = "NumberMaximum";
ValueErrorType[ValueErrorType["Object"] = 21] = "Object";
ValueErrorType[ValueErrorType["ObjectMinProperties"] = 22] = "ObjectMinProperties";
ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 23] = "ObjectMaxProperties";
ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 24] = "ObjectAdditionalProperties";
ValueErrorType[ValueErrorType["ObjectRequiredProperties"] = 25] = "ObjectRequiredProperties";
ValueErrorType[ValueErrorType["Promise"] = 26] = "Promise";
ValueErrorType[ValueErrorType["RecordKeyNumeric"] = 27] = "RecordKeyNumeric";
ValueErrorType[ValueErrorType["RecordKeyString"] = 28] = "RecordKeyString";
ValueErrorType[ValueErrorType["String"] = 29] = "String";
ValueErrorType[ValueErrorType["StringMinLength"] = 30] = "StringMinLength";
ValueErrorType[ValueErrorType["StringMaxLength"] = 31] = "StringMaxLength";
ValueErrorType[ValueErrorType["StringPattern"] = 32] = "StringPattern";
ValueErrorType[ValueErrorType["StringFormatUnknown"] = 33] = "StringFormatUnknown";
ValueErrorType[ValueErrorType["StringFormat"] = 34] = "StringFormat";
ValueErrorType[ValueErrorType["TupleZeroLength"] = 35] = "TupleZeroLength";
ValueErrorType[ValueErrorType["TupleLength"] = 36] = "TupleLength";
ValueErrorType[ValueErrorType["Undefined"] = 37] = "Undefined";
ValueErrorType[ValueErrorType["Union"] = 38] = "Union";
ValueErrorType[ValueErrorType["Uint8Array"] = 39] = "Uint8Array";
ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 40] = "Uint8ArrayMinByteLength";
ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 41] = "Uint8ArrayMaxByteLength";
ValueErrorType[ValueErrorType["Void"] = 42] = "Void";
})(ValueErrorType = exports.ValueErrorType || (exports.ValueErrorType = {}));
// -------------------------------------------------------------------
// ValueErrors
// -------------------------------------------------------------------
class ValueErrorsUnknownTypeError extends Error {
constructor(schema) {
super('ValueErrors: Unknown type');
this.schema = schema;
}
}
exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError;
var ValueErrors;
(function (ValueErrors) {
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 (schema.minItems !== undefined && !(value.length >= schema.minItems)) {
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be greater or equal to ${schema.minItems}` };
}
if (schema.maxItems !== undefined && !(value.length <= schema.maxItems)) {
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be less or equal to ${schema.maxItems}` };
}
if (schema.uniqueItems === true && !(new Set(value).size === value.length)) {
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* 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* 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 (!(typeof value === 'number')) {
return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` };
}
if (!globalThis.Number.isInteger(value)) {
yield { type: ValueErrorType.Integer, schema, path, value, message: `Expected integer` };
}
if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
yield { type: ValueErrorType.IntegerMultipleOf, schema, path, value, message: `Expected integer to be a multiple of ${schema.multipleOf}` };
}
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.IntegerExclusiveMinimum, schema, path, value, message: `Expected integer to be greater than ${schema.exclusiveMinimum}` };
}
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.IntegerExclusiveMaximum, schema, path, value, message: `Expected integer to be less than ${schema.exclusiveMaximum}` };
}
if (schema.minimum && !(value >= schema.minimum)) {
yield { type: ValueErrorType.IntegerMinimum, schema, path, value, message: `Expected integer to be greater or equal to ${schema.minimum}` };
}
if (schema.maximum && !(value <= schema.maximum)) {
yield { type: ValueErrorType.IntegerMaximum, schema, path, value, message: `Expected integer to be less or equal to ${schema.maximum}` };
}
}
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* 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 (!(typeof value === 'number')) {
return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` };
}
if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
yield { type: ValueErrorType.NumberMultipleOf, schema, path, value, message: `Expected number to be a multiple of ${schema.multipleOf}` };
}
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.NumberExclusiveMinimum, schema, path, value, message: `Expected number to be greater than ${schema.exclusiveMinimum}` };
}
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.NumberExclusiveMaximum, schema, path, value, message: `Expected number to be less than ${schema.exclusiveMaximum}` };
}
if (schema.minimum && !(value >= schema.minimum)) {
yield { type: ValueErrorType.NumberMaximum, schema, path, value, message: `Expected number to be greater or equal to ${schema.minimum}` };
}
if (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 (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` };
}
if (schema.minProperties !== undefined && !(globalThis.Object.keys(value).length >= schema.minProperties)) {
yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` };
}
if (schema.maxProperties !== undefined && !(globalThis.Object.keys(value).length <= schema.maxProperties)) {
yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
}
const propertyKeys = globalThis.Object.keys(schema.properties);
if (schema.additionalProperties === false) {
for (const objectKey of globalThis.Object.keys(value)) {
if (!propertyKeys.includes(objectKey)) {
yield { type: ValueErrorType.ObjectAdditionalProperties, schema, path: `${path}/${objectKey}`, value: value[objectKey], message: `Unexpected property` };
}
}
}
if (schema.required && schema.required.length > 0) {
const objectKeys = globalThis.Object.keys(value);
for (const requiredKey of schema.required) {
if (objectKeys.includes(requiredKey))
continue;
yield { type: ValueErrorType.ObjectRequiredProperties, schema: schema.properties[requiredKey], path: `${path}/${requiredKey}`, value: undefined, message: `Expected required property` };
}
}
if (typeof schema.additionalProperties === 'object') {
for (const objectKey of globalThis.Object.keys(value)) {
if (propertyKeys.includes(objectKey))
continue;
yield* Visit(schema.additionalProperties, references, `${path}/${objectKey}`, value[objectKey]);
}
}
for (const propertyKey of propertyKeys) {
const propertySchema = schema.properties[propertyKey];
if (schema.required && schema.required.includes(propertyKey)) {
yield* Visit(propertySchema, references, `${path}/${propertyKey}`, value[propertyKey]);
}
else {
if (value[propertyKey] !== undefined) {
yield* Visit(propertySchema, references, `${path}/${propertyKey}`, value[propertyKey]);
}
}
}
}
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 (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` };
}
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern);
if (!globalThis.Object.keys(value).every((key) => regex.test(key))) {
const numeric = keyPattern === '^(0|[1-9][0-9]*)$';
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 reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueErrors.Ref: Cannot find schema with $id '${schema.$ref}'.`);
yield* Visit(reference, references, path, value);
}
function* Self(schema, references, path, value) {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueErrors.Self: Cannot find schema with $id '${schema.$ref}'.`);
yield* Visit(reference, references, path, value);
}
function* String(schema, references, path, value) {
if (!(typeof value === 'string')) {
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
}
if (schema.minLength !== undefined && !(value.length >= schema.minLength)) {
yield { type: ValueErrorType.StringMinLength, schema, path, value, message: `Expected string length greater or equal to ${schema.minLength}` };
}
if (schema.maxLength !== undefined && !(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 (!index_1.Format.Has(schema.format)) {
yield { type: ValueErrorType.StringFormatUnknown, schema, path, value, message: `Unknown string format '${schema.format}'` };
}
else {
const format = index_1.Format.Get(schema.format);
if (!format(value)) {
yield { type: ValueErrorType.StringFormat, schema, path, value, message: `Expected string to match format '${schema.format}'` };
}
}
}
}
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);
}
for (const error of errors) {
yield error;
}
if (errors.length > 0) {
yield { type: ValueErrorType.Union, schema, path, value, message: 'Expected value of union' };
}
}
function* Uint8Array(schema, references, path, value) {
if (!(value instanceof globalThis.Uint8Array)) {
return yield { type: ValueErrorType.Uint8Array, schema, path, value, message: `Expected Uint8Array` };
}
if (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 (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 (!(value === null)) {
return yield { type: ValueErrorType.Void, schema, path, value, message: `Expected null` };
}
}
function* Visit(schema, references, path, value) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema;
switch (anySchema[Types.Kind]) {
case 'Any':
return yield* Any(anySchema, anyReferences, path, value);
case 'Array':
return yield* Array(anySchema, anyReferences, path, value);
case 'Boolean':
return yield* Boolean(anySchema, anyReferences, path, value);
case 'Constructor':
return yield* Constructor(anySchema, anyReferences, path, value);
case 'Function':
return yield* Function(anySchema, anyReferences, path, value);
case 'Integer':
return yield* Integer(anySchema, anyReferences, path, value);
case 'Literal':
return yield* Literal(anySchema, anyReferences, path, value);
case 'Never':
return yield* Never(anySchema, anyReferences, path, value);
case 'Null':
return yield* Null(anySchema, anyReferences, path, value);
case 'Number':
return yield* Number(anySchema, anyReferences, path, value);
case 'Object':
return yield* Object(anySchema, anyReferences, path, value);
case 'Promise':
return yield* Promise(anySchema, anyReferences, path, value);
case 'Record':
return yield* Record(anySchema, anyReferences, path, value);
case 'Ref':
return yield* Ref(anySchema, anyReferences, path, value);
case 'Self':
return yield* Self(anySchema, anyReferences, path, value);
case 'String':
return yield* String(anySchema, anyReferences, path, value);
case 'Tuple':
return yield* Tuple(anySchema, anyReferences, path, value);
case 'Undefined':
return yield* Undefined(anySchema, anyReferences, path, value);
case 'Union':
return yield* Union(anySchema, anyReferences, path, value);
case 'Uint8Array':
return yield* Uint8Array(anySchema, anyReferences, path, value);
case 'Unknown':
return yield* Unknown(anySchema, anyReferences, path, value);
case 'Void':
return yield* Void(anySchema, anyReferences, path, value);
default:
throw new ValueErrorsUnknownTypeError(schema);
}
}
function* Errors(schema, references, value) {
yield* Visit(schema, references, '', value);
}
ValueErrors.Errors = Errors;
})(ValueErrors = exports.ValueErrors || (exports.ValueErrors = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/errors
The MIT License (MIT)
Copyright (c) 2022 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.ValueErrors = exports.ValueErrorsUnknownTypeError = exports.ValueErrorType = void 0;
const Types = require("../typebox");
const index_1 = require("../format/index");
// -------------------------------------------------------------------
// 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["Boolean"] = 4] = "Boolean";
ValueErrorType[ValueErrorType["Function"] = 5] = "Function";
ValueErrorType[ValueErrorType["Integer"] = 6] = "Integer";
ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 7] = "IntegerMultipleOf";
ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 8] = "IntegerExclusiveMinimum";
ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 9] = "IntegerExclusiveMaximum";
ValueErrorType[ValueErrorType["IntegerMinimum"] = 10] = "IntegerMinimum";
ValueErrorType[ValueErrorType["IntegerMaximum"] = 11] = "IntegerMaximum";
ValueErrorType[ValueErrorType["Literal"] = 12] = "Literal";
ValueErrorType[ValueErrorType["Never"] = 13] = "Never";
ValueErrorType[ValueErrorType["Null"] = 14] = "Null";
ValueErrorType[ValueErrorType["Number"] = 15] = "Number";
ValueErrorType[ValueErrorType["NumberMultipleOf"] = 16] = "NumberMultipleOf";
ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 17] = "NumberExclusiveMinimum";
ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 18] = "NumberExclusiveMaximum";
ValueErrorType[ValueErrorType["NumberMinumum"] = 19] = "NumberMinumum";
ValueErrorType[ValueErrorType["NumberMaximum"] = 20] = "NumberMaximum";
ValueErrorType[ValueErrorType["Object"] = 21] = "Object";
ValueErrorType[ValueErrorType["ObjectMinProperties"] = 22] = "ObjectMinProperties";
ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 23] = "ObjectMaxProperties";
ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 24] = "ObjectAdditionalProperties";
ValueErrorType[ValueErrorType["ObjectRequiredProperties"] = 25] = "ObjectRequiredProperties";
ValueErrorType[ValueErrorType["Promise"] = 26] = "Promise";
ValueErrorType[ValueErrorType["RecordKeyNumeric"] = 27] = "RecordKeyNumeric";
ValueErrorType[ValueErrorType["RecordKeyString"] = 28] = "RecordKeyString";
ValueErrorType[ValueErrorType["String"] = 29] = "String";
ValueErrorType[ValueErrorType["StringMinLength"] = 30] = "StringMinLength";
ValueErrorType[ValueErrorType["StringMaxLength"] = 31] = "StringMaxLength";
ValueErrorType[ValueErrorType["StringPattern"] = 32] = "StringPattern";
ValueErrorType[ValueErrorType["StringFormatUnknown"] = 33] = "StringFormatUnknown";
ValueErrorType[ValueErrorType["StringFormat"] = 34] = "StringFormat";
ValueErrorType[ValueErrorType["TupleZeroLength"] = 35] = "TupleZeroLength";
ValueErrorType[ValueErrorType["TupleLength"] = 36] = "TupleLength";
ValueErrorType[ValueErrorType["Undefined"] = 37] = "Undefined";
ValueErrorType[ValueErrorType["Union"] = 38] = "Union";
ValueErrorType[ValueErrorType["Uint8Array"] = 39] = "Uint8Array";
ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 40] = "Uint8ArrayMinByteLength";
ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 41] = "Uint8ArrayMaxByteLength";
ValueErrorType[ValueErrorType["Void"] = 42] = "Void";
})(ValueErrorType = exports.ValueErrorType || (exports.ValueErrorType = {}));
// -------------------------------------------------------------------
// ValueErrors
// -------------------------------------------------------------------
class ValueErrorsUnknownTypeError extends Error {
constructor(schema) {
super('ValueErrors: Unknown type');
this.schema = schema;
}
}
exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError;
var ValueErrors;
(function (ValueErrors) {
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 (schema.minItems !== undefined && !(value.length >= schema.minItems)) {
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be greater or equal to ${schema.minItems}` };
}
if (schema.maxItems !== undefined && !(value.length <= schema.maxItems)) {
yield { type: ValueErrorType.ArrayMinItems, schema, path, value, message: `Expected array length to be less or equal to ${schema.maxItems}` };
}
if (schema.uniqueItems === true && !(new Set(value).size === value.length)) {
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* 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* 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 (!(typeof value === 'number')) {
return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` };
}
if (!globalThis.Number.isInteger(value)) {
yield { type: ValueErrorType.Integer, schema, path, value, message: `Expected integer` };
}
if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
yield { type: ValueErrorType.IntegerMultipleOf, schema, path, value, message: `Expected integer to be a multiple of ${schema.multipleOf}` };
}
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.IntegerExclusiveMinimum, schema, path, value, message: `Expected integer to be greater than ${schema.exclusiveMinimum}` };
}
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.IntegerExclusiveMaximum, schema, path, value, message: `Expected integer to be less than ${schema.exclusiveMaximum}` };
}
if (schema.minimum && !(value >= schema.minimum)) {
yield { type: ValueErrorType.IntegerMinimum, schema, path, value, message: `Expected integer to be greater or equal to ${schema.minimum}` };
}
if (schema.maximum && !(value <= schema.maximum)) {
yield { type: ValueErrorType.IntegerMaximum, schema, path, value, message: `Expected integer to be less or equal to ${schema.maximum}` };
}
}
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* 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 (!(typeof value === 'number')) {
return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` };
}
if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
yield { type: ValueErrorType.NumberMultipleOf, schema, path, value, message: `Expected number to be a multiple of ${schema.multipleOf}` };
}
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.NumberExclusiveMinimum, schema, path, value, message: `Expected number to be greater than ${schema.exclusiveMinimum}` };
}
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.NumberExclusiveMaximum, schema, path, value, message: `Expected number to be less than ${schema.exclusiveMaximum}` };
}
if (schema.minimum && !(value >= schema.minimum)) {
yield { type: ValueErrorType.NumberMaximum, schema, path, value, message: `Expected number to be greater or equal to ${schema.minimum}` };
}
if (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 (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` };
}
if (schema.minProperties !== undefined && !(globalThis.Object.keys(value).length >= schema.minProperties)) {
yield { type: ValueErrorType.ObjectMinProperties, schema, path, value, message: `Expected object to have at least ${schema.minProperties} properties` };
}
if (schema.maxProperties !== undefined && !(globalThis.Object.keys(value).length <= schema.maxProperties)) {
yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
}
const propertyKeys = globalThis.Object.keys(schema.properties);
if (schema.additionalProperties === false) {
for (const objectKey of globalThis.Object.keys(value)) {
if (!propertyKeys.includes(objectKey)) {
yield { type: ValueErrorType.ObjectAdditionalProperties, schema, path: `${path}/${objectKey}`, value: value[objectKey], message: `Unexpected property` };
}
}
}
if (schema.required && schema.required.length > 0) {
const objectKeys = globalThis.Object.keys(value);
for (const requiredKey of schema.required) {
if (objectKeys.includes(requiredKey))
continue;
yield { type: ValueErrorType.ObjectRequiredProperties, schema: schema.properties[requiredKey], path: `${path}/${requiredKey}`, value: undefined, message: `Expected required property` };
}
}
if (typeof schema.additionalProperties === 'object') {
for (const objectKey of globalThis.Object.keys(value)) {
if (propertyKeys.includes(objectKey))
continue;
yield* Visit(schema.additionalProperties, references, `${path}/${objectKey}`, value[objectKey]);
}
}
for (const propertyKey of propertyKeys) {
const propertySchema = schema.properties[propertyKey];
if (schema.required && schema.required.includes(propertyKey)) {
yield* Visit(propertySchema, references, `${path}/${propertyKey}`, value[propertyKey]);
}
else {
if (value[propertyKey] !== undefined) {
yield* Visit(propertySchema, references, `${path}/${propertyKey}`, value[propertyKey]);
}
}
}
}
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 (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` };
}
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern);
if (!globalThis.Object.keys(value).every((key) => regex.test(key))) {
const numeric = keyPattern === '^(0|[1-9][0-9]*)$';
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 reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueErrors.Ref: Cannot find schema with $id '${schema.$ref}'.`);
yield* Visit(reference, references, path, value);
}
function* Self(schema, references, path, value) {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueErrors.Self: Cannot find schema with $id '${schema.$ref}'.`);
yield* Visit(reference, references, path, value);
}
function* String(schema, references, path, value) {
if (!(typeof value === 'string')) {
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
}
if (schema.minLength !== undefined && !(value.length >= schema.minLength)) {
yield { type: ValueErrorType.StringMinLength, schema, path, value, message: `Expected string length greater or equal to ${schema.minLength}` };
}
if (schema.maxLength !== undefined && !(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 (!index_1.Format.Has(schema.format)) {
yield { type: ValueErrorType.StringFormatUnknown, schema, path, value, message: `Unknown string format '${schema.format}'` };
}
else {
const format = index_1.Format.Get(schema.format);
if (!format(value)) {
yield { type: ValueErrorType.StringFormat, schema, path, value, message: `Expected string to match format '${schema.format}'` };
}
}
}
}
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);
}
for (const error of errors) {
yield error;
}
if (errors.length > 0) {
yield { type: ValueErrorType.Union, schema, path, value, message: 'Expected value of union' };
}
}
function* Uint8Array(schema, references, path, value) {
if (!(value instanceof globalThis.Uint8Array)) {
return yield { type: ValueErrorType.Uint8Array, schema, path, value, message: `Expected Uint8Array` };
}
if (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 (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 (!(value === null)) {
return yield { type: ValueErrorType.Void, schema, path, value, message: `Expected null` };
}
}
function* Visit(schema, references, path, value) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema;
switch (anySchema[Types.Kind]) {
case 'Any':
return yield* Any(anySchema, anyReferences, path, value);
case 'Array':
return yield* Array(anySchema, anyReferences, path, value);
case 'Boolean':
return yield* Boolean(anySchema, anyReferences, path, value);
case 'Constructor':
return yield* Constructor(anySchema, anyReferences, path, value);
case 'Function':
return yield* Function(anySchema, anyReferences, path, value);
case 'Integer':
return yield* Integer(anySchema, anyReferences, path, value);
case 'Literal':
return yield* Literal(anySchema, anyReferences, path, value);
case 'Never':
return yield* Never(anySchema, anyReferences, path, value);
case 'Null':
return yield* Null(anySchema, anyReferences, path, value);
case 'Number':
return yield* Number(anySchema, anyReferences, path, value);
case 'Object':
return yield* Object(anySchema, anyReferences, path, value);
case 'Promise':
return yield* Promise(anySchema, anyReferences, path, value);
case 'Record':
return yield* Record(anySchema, anyReferences, path, value);
case 'Ref':
return yield* Ref(anySchema, anyReferences, path, value);
case 'Self':
return yield* Self(anySchema, anyReferences, path, value);
case 'String':
return yield* String(anySchema, anyReferences, path, value);
case 'Tuple':
return yield* Tuple(anySchema, anyReferences, path, value);
case 'Undefined':
return yield* Undefined(anySchema, anyReferences, path, value);
case 'Union':
return yield* Union(anySchema, anyReferences, path, value);
case 'Uint8Array':
return yield* Uint8Array(anySchema, anyReferences, path, value);
case 'Unknown':
return yield* Unknown(anySchema, anyReferences, path, value);
case 'Void':
return yield* Void(anySchema, anyReferences, path, value);
default:
throw new ValueErrorsUnknownTypeError(schema);
}
}
function* Errors(schema, references, value) {
yield* Visit(schema, references, '', value);
}
ValueErrors.Errors = Errors;
})(ValueErrors = exports.ValueErrors || (exports.ValueErrors = {}));

View File

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

View File

@@ -1,44 +1,44 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/errors
The MIT License (MIT)
Copyright (c) 2022 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);
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/errors
The MIT License (MIT)
Copyright (c) 2022 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

@@ -1,12 +1,12 @@
export declare type FormatValidationFunction = (value: string) => boolean;
/** Shared string formats used by the TypeCompiler and Value modules */
export declare namespace Format {
/** Clears all formats */
function Clear(): void;
/** Returns true if the string format exists */
function Has(format: string): boolean;
/** Sets a string format validation function */
function Set(format: string, func: FormatValidationFunction): void;
/** Gets a string format validation function */
function Get(format: string): FormatValidationFunction | undefined;
}
export declare type FormatValidationFunction = (value: string) => boolean;
/** Shared string formats used by the TypeCompiler and Value modules */
export declare namespace Format {
/** Clears all formats */
function Clear(): void;
/** Returns true if the string format exists */
function Has(format: string): boolean;
/** Sets a string format validation function */
function Set(format: string, func: FormatValidationFunction): void;
/** Gets a string format validation function */
function Get(format: string): FormatValidationFunction | undefined;
}

View File

@@ -1,55 +1,55 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/format
The MIT License (MIT)
Copyright (c) 2022 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.Format = void 0;
/** Shared string formats used by the TypeCompiler and Value modules */
var Format;
(function (Format) {
const formats = new Map();
/** Clears all formats */
function Clear() {
return formats.clear();
}
Format.Clear = Clear;
/** Returns true if the string format exists */
function Has(format) {
return formats.has(format);
}
Format.Has = Has;
/** Sets a string format validation function */
function Set(format, func) {
formats.set(format, func);
}
Format.Set = Set;
/** Gets a string format validation function */
function Get(format) {
return formats.get(format);
}
Format.Get = Get;
})(Format = exports.Format || (exports.Format = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/format
The MIT License (MIT)
Copyright (c) 2022 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.Format = void 0;
/** Shared string formats used by the TypeCompiler and Value modules */
var Format;
(function (Format) {
const formats = new Map();
/** Clears all formats */
function Clear() {
return formats.clear();
}
Format.Clear = Clear;
/** Returns true if the string format exists */
function Has(format) {
return formats.has(format);
}
Format.Has = Has;
/** Sets a string format validation function */
function Set(format, func) {
formats.set(format, func);
}
Format.Set = Set;
/** Gets a string format validation function */
function Get(format) {
return formats.get(format);
}
Format.Get = Get;
})(Format = exports.Format || (exports.Format = {}));

View File

@@ -1 +1 @@
export * from './format';
export * from './format';

View File

@@ -1,44 +1,44 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/format
The MIT License (MIT)
Copyright (c) 2022 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("./format"), exports);
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/format
The MIT License (MIT)
Copyright (c) 2022 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("./format"), exports);

View File

@@ -1,56 +1,56 @@
import * as Types from '../typebox';
export declare class TypeGuardInvalidTypeError extends Error {
readonly schema: unknown;
constructor(schema: unknown);
}
/** TypeGuard tests that values conform to a known TypeBox type specification */
export declare namespace TypeGuard {
/** Returns true if the given schema is TAny */
function TAny(schema: unknown): schema is Types.TAny;
/** Returns true if the given schema is TArray */
function TArray(schema: unknown): schema is Types.TArray;
/** Returns true if the given schema is TBoolean */
function TBoolean(schema: unknown): schema is Types.TBoolean;
/** Returns true if the given schema is TConstructor */
function TConstructor(schema: unknown): schema is Types.TConstructor;
/** Returns true if the given schema is TFunction */
function TFunction(schema: unknown): schema is Types.TFunction;
/** Returns true if the given schema is TInteger */
function TInteger(schema: unknown): schema is Types.TInteger;
/** Returns true if the given schema is TLiteral */
function TLiteral(schema: unknown): schema is Types.TLiteral;
/** Returns true if the given schema is TNever */
function TNever(schema: unknown): schema is Types.TNever;
/** Returns true if the given schema is TNull */
function TNull(schema: unknown): schema is Types.TNull;
/** Returns true if the given schema is TNumber */
function TNumber(schema: unknown): schema is Types.TNumber;
/** Returns true if the given schema is TObject */
function TObject(schema: unknown): schema is Types.TObject;
/** Returns true if the given schema is TPromise */
function TPromise(schema: unknown): schema is Types.TPromise;
/** Returns true if the given schema is TRecord */
function TRecord(schema: unknown): schema is Types.TRecord;
/** Returns true if the given schema is TSelf */
function TSelf(schema: unknown): schema is Types.TSelf;
/** Returns true if the given schema is TRef */
function TRef(schema: unknown): schema is Types.TRef;
/** Returns true if the given schema is TString */
function TString(schema: unknown): schema is Types.TString;
/** Returns true if the given schema is TTuple */
function TTuple(schema: unknown): schema is Types.TTuple;
/** Returns true if the given schema is TUndefined */
function TUndefined(schema: unknown): schema is Types.TUndefined;
/** Returns true if the given schema is TUnion */
function TUnion(schema: unknown): schema is Types.TUnion;
/** Returns true if the given schema is TUint8Array */
function TUint8Array(schema: unknown): schema is Types.TUint8Array;
/** Returns true if the given schema is TUnknown */
function TUnknown(schema: unknown): schema is Types.TUnknown;
/** Returns true if the given schema is TVoid */
function TVoid(schema: unknown): schema is Types.TVoid;
/** Returns true if the given schema is TSchema */
function TSchema(schema: unknown): schema is Types.TSchema;
/** Asserts if this schema and associated references are valid. */
function Assert<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): void;
}
import * as Types from '../typebox';
export declare class TypeGuardInvalidTypeError extends Error {
readonly schema: unknown;
constructor(schema: unknown);
}
/** TypeGuard tests that values conform to a known TypeBox type specification */
export declare namespace TypeGuard {
/** Returns true if the given schema is TAny */
function TAny(schema: unknown): schema is Types.TAny;
/** Returns true if the given schema is TArray */
function TArray(schema: unknown): schema is Types.TArray;
/** Returns true if the given schema is TBoolean */
function TBoolean(schema: unknown): schema is Types.TBoolean;
/** Returns true if the given schema is TConstructor */
function TConstructor(schema: unknown): schema is Types.TConstructor;
/** Returns true if the given schema is TFunction */
function TFunction(schema: unknown): schema is Types.TFunction;
/** Returns true if the given schema is TInteger */
function TInteger(schema: unknown): schema is Types.TInteger;
/** Returns true if the given schema is TLiteral */
function TLiteral(schema: unknown): schema is Types.TLiteral;
/** Returns true if the given schema is TNever */
function TNever(schema: unknown): schema is Types.TNever;
/** Returns true if the given schema is TNull */
function TNull(schema: unknown): schema is Types.TNull;
/** Returns true if the given schema is TNumber */
function TNumber(schema: unknown): schema is Types.TNumber;
/** Returns true if the given schema is TObject */
function TObject(schema: unknown): schema is Types.TObject;
/** Returns true if the given schema is TPromise */
function TPromise(schema: unknown): schema is Types.TPromise;
/** Returns true if the given schema is TRecord */
function TRecord(schema: unknown): schema is Types.TRecord;
/** Returns true if the given schema is TSelf */
function TSelf(schema: unknown): schema is Types.TSelf;
/** Returns true if the given schema is TRef */
function TRef(schema: unknown): schema is Types.TRef;
/** Returns true if the given schema is TString */
function TString(schema: unknown): schema is Types.TString;
/** Returns true if the given schema is TTuple */
function TTuple(schema: unknown): schema is Types.TTuple;
/** Returns true if the given schema is TUndefined */
function TUndefined(schema: unknown): schema is Types.TUndefined;
/** Returns true if the given schema is TUnion */
function TUnion(schema: unknown): schema is Types.TUnion;
/** Returns true if the given schema is TUint8Array */
function TUint8Array(schema: unknown): schema is Types.TUint8Array;
/** Returns true if the given schema is TUnknown */
function TUnknown(schema: unknown): schema is Types.TUnknown;
/** Returns true if the given schema is TVoid */
function TVoid(schema: unknown): schema is Types.TVoid;
/** Returns true if the given schema is TSchema */
function TSchema(schema: unknown): schema is Types.TSchema;
/** Asserts if this schema and associated references are valid. */
function Assert<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): void;
}

View File

@@ -1,351 +1,351 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/guard
The MIT License (MIT)
Copyright (c) 2022 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, dTribute, 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.TypeGuard = exports.TypeGuardInvalidTypeError = void 0;
const Types = require("../typebox");
class TypeGuardInvalidTypeError extends Error {
constructor(schema) {
super('TypeGuard: Invalid type');
this.schema = schema;
}
}
exports.TypeGuardInvalidTypeError = TypeGuardInvalidTypeError;
/** TypeGuard tests that values conform to a known TypeBox type specification */
var TypeGuard;
(function (TypeGuard) {
function IsObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function IsArray(value) {
return typeof value === 'object' && value !== null && Array.isArray(value);
}
function IsPattern(value) {
try {
new RegExp(value);
return true;
}
catch {
return false;
}
}
function IsControlCharacterFree(value) {
if (typeof value !== 'string')
return false;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if ((code >= 7 && code <= 13) || code === 27 || code === 127) {
return false;
}
}
return true;
}
function IsString(value) {
return typeof value === 'string';
}
function IsNumber(value) {
return typeof value === 'number';
}
function IsBoolean(value) {
return typeof value === 'boolean';
}
function IsOptionalNumber(value) {
return value === undefined || (value !== undefined && IsNumber(value));
}
function IsOptionalBoolean(value) {
return value === undefined || (value !== undefined && IsBoolean(value));
}
function IsOptionalString(value) {
return value === undefined || (value !== undefined && IsString(value));
}
function IsOptionalPattern(value) {
return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value) && IsPattern(value));
}
function IsOptionalFormat(value) {
return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value));
}
function IsOptionalSchema(value) {
return value === undefined || TSchema(value);
}
/** Returns true if the given schema is TAny */
function TAny(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Any' && IsOptionalString(schema.$id);
}
TypeGuard.TAny = TAny;
/** Returns true if the given schema is TArray */
function TArray(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'Array' &&
schema.type === 'array' &&
IsOptionalString(schema.$id) &&
TSchema(schema.items) &&
IsOptionalNumber(schema.minItems) &&
IsOptionalNumber(schema.maxItems) &&
IsOptionalBoolean(schema.uniqueItems));
}
TypeGuard.TArray = TArray;
/** Returns true if the given schema is TBoolean */
function TBoolean(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Boolean' && schema.type === 'boolean' && IsOptionalString(schema.$id);
}
TypeGuard.TBoolean = TBoolean;
/** Returns true if the given schema is TConstructor */
function TConstructor(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Constructor' && schema.type === 'constructor' && IsOptionalString(schema.$id) && IsArray(schema.parameters) && TSchema(schema.returns))) {
return false;
}
for (const parameter of schema.parameters) {
if (!TSchema(parameter))
return false;
}
return true;
}
TypeGuard.TConstructor = TConstructor;
/** Returns true if the given schema is TFunction */
function TFunction(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Function' && schema.type === 'function' && IsOptionalString(schema.$id) && IsArray(schema.parameters) && TSchema(schema.returns))) {
return false;
}
for (const parameter of schema.parameters) {
if (!TSchema(parameter))
return false;
}
return true;
}
TypeGuard.TFunction = TFunction;
/** Returns true if the given schema is TInteger */
function TInteger(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'Integer' &&
schema.type === 'integer' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.multipleOf) &&
IsOptionalNumber(schema.minimum) &&
IsOptionalNumber(schema.maximum) &&
IsOptionalNumber(schema.exclusiveMinimum) &&
IsOptionalNumber(schema.exclusiveMaximum));
}
TypeGuard.TInteger = TInteger;
/** Returns true if the given schema is TLiteral */
function TLiteral(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Literal' && IsOptionalString(schema.$id) && (IsString(schema.const) || IsNumber(schema.const) || IsBoolean(schema.const));
}
TypeGuard.TLiteral = TLiteral;
/** Returns true if the given schema is TNever */
function TNever(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'Never' &&
IsArray(schema.allOf) &&
schema.allOf.length === 2 &&
IsObject(schema.allOf[0]) &&
IsString(schema.allOf[0].type) &&
schema.allOf[0].type === 'boolean' &&
schema.allOf[0].const === false &&
IsObject(schema.allOf[1]) &&
IsString(schema.allOf[1].type) &&
schema.allOf[1].type === 'boolean' &&
schema.allOf[1].const === true);
}
TypeGuard.TNever = TNever;
/** Returns true if the given schema is TNull */
function TNull(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Null' && schema.type === 'null' && IsOptionalString(schema.$id);
}
TypeGuard.TNull = TNull;
/** Returns true if the given schema is TNumber */
function TNumber(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'Number' &&
schema.type === 'number' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.multipleOf) &&
IsOptionalNumber(schema.minimum) &&
IsOptionalNumber(schema.maximum) &&
IsOptionalNumber(schema.exclusiveMinimum) &&
IsOptionalNumber(schema.exclusiveMaximum));
}
TypeGuard.TNumber = TNumber;
/** Returns true if the given schema is TObject */
function TObject(schema) {
if (!(IsObject(schema) &&
schema[Types.Kind] === 'Object' &&
schema.type === 'object' &&
IsOptionalString(schema.$id) &&
IsObject(schema.properties) &&
(IsOptionalBoolean(schema.additionalProperties) || IsOptionalSchema(schema.additionalProperties)) &&
IsOptionalNumber(schema.minProperties) &&
IsOptionalNumber(schema.maxProperties))) {
return false;
}
for (const [key, value] of Object.entries(schema.properties)) {
if (!IsControlCharacterFree(key))
return false;
if (!TSchema(value))
return false;
}
return true;
}
TypeGuard.TObject = TObject;
/** Returns true if the given schema is TPromise */
function TPromise(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Promise' && schema.type === 'promise' && IsOptionalString(schema.$id) && TSchema(schema.item);
}
TypeGuard.TPromise = TPromise;
/** Returns true if the given schema is TRecord */
function TRecord(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Record' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.additionalProperties === false && IsObject(schema.patternProperties))) {
return false;
}
const keys = Object.keys(schema.patternProperties);
if (keys.length !== 1) {
return false;
}
if (!IsPattern(keys[0])) {
return false;
}
if (!TSchema(schema.patternProperties[keys[0]])) {
return false;
}
return true;
}
TypeGuard.TRecord = TRecord;
/** Returns true if the given schema is TSelf */
function TSelf(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Self' && IsOptionalString(schema.$id) && IsString(schema.$ref);
}
TypeGuard.TSelf = TSelf;
/** Returns true if the given schema is TRef */
function TRef(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Ref' && IsOptionalString(schema.$id) && IsString(schema.$ref);
}
TypeGuard.TRef = TRef;
/** Returns true if the given schema is TString */
function TString(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'String' &&
schema.type === 'string' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.minLength) &&
IsOptionalNumber(schema.maxLength) &&
IsOptionalPattern(schema.pattern) &&
IsOptionalFormat(schema.format));
}
TypeGuard.TString = TString;
/** Returns true if the given schema is TTuple */
function TTuple(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Tuple' && schema.type === 'array' && IsOptionalString(schema.$id) && IsNumber(schema.minItems) && IsNumber(schema.maxItems) && schema.minItems === schema.maxItems)) {
return false;
}
if (schema.items === undefined && schema.additionalItems === undefined && schema.minItems === 0) {
return true;
}
if (!IsArray(schema.items)) {
return false;
}
for (const inner of schema.items) {
if (!TSchema(inner))
return false;
}
return true;
}
TypeGuard.TTuple = TTuple;
/** Returns true if the given schema is TUndefined */
function TUndefined(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Undefined' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.specialized === 'Undefined';
}
TypeGuard.TUndefined = TUndefined;
/** Returns true if the given schema is TUnion */
function TUnion(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Union' && IsArray(schema.anyOf) && IsOptionalString(schema.$id))) {
return false;
}
for (const inner of schema.anyOf) {
if (!TSchema(inner))
return false;
}
return true;
}
TypeGuard.TUnion = TUnion;
/** Returns true if the given schema is TUint8Array */
function TUint8Array(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'Uint8Array' &&
schema.type === 'object' &&
IsOptionalString(schema.$id) &&
schema.specialized === 'Uint8Array' &&
IsOptionalNumber(schema.minByteLength) &&
IsOptionalNumber(schema.maxByteLength));
}
TypeGuard.TUint8Array = TUint8Array;
/** Returns true if the given schema is TUnknown */
function TUnknown(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Unknown' && IsOptionalString(schema.$id);
}
TypeGuard.TUnknown = TUnknown;
/** Returns true if the given schema is TVoid */
function TVoid(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Void' && schema.type === 'null' && IsOptionalString(schema.$id);
}
TypeGuard.TVoid = TVoid;
/** Returns true if the given schema is TSchema */
function TSchema(schema) {
return (TAny(schema) ||
TArray(schema) ||
TBoolean(schema) ||
TConstructor(schema) ||
TFunction(schema) ||
TInteger(schema) ||
TLiteral(schema) ||
TNever(schema) ||
TNull(schema) ||
TNumber(schema) ||
TObject(schema) ||
TPromise(schema) ||
TRecord(schema) ||
TSelf(schema) ||
TRef(schema) ||
TString(schema) ||
TTuple(schema) ||
TUndefined(schema) ||
TUnion(schema) ||
TUint8Array(schema) ||
TUnknown(schema) ||
TVoid(schema));
}
TypeGuard.TSchema = TSchema;
/** Asserts if this schema and associated references are valid. */
function Assert(schema, references = []) {
if (!TSchema(schema))
throw new TypeGuardInvalidTypeError(schema);
for (const schema of references) {
if (!TSchema(schema))
throw new TypeGuardInvalidTypeError(schema);
}
}
TypeGuard.Assert = Assert;
})(TypeGuard = exports.TypeGuard || (exports.TypeGuard = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/guard
The MIT License (MIT)
Copyright (c) 2022 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, dTribute, 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.TypeGuard = exports.TypeGuardInvalidTypeError = void 0;
const Types = require("../typebox");
class TypeGuardInvalidTypeError extends Error {
constructor(schema) {
super('TypeGuard: Invalid type');
this.schema = schema;
}
}
exports.TypeGuardInvalidTypeError = TypeGuardInvalidTypeError;
/** TypeGuard tests that values conform to a known TypeBox type specification */
var TypeGuard;
(function (TypeGuard) {
function IsObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function IsArray(value) {
return typeof value === 'object' && value !== null && Array.isArray(value);
}
function IsPattern(value) {
try {
new RegExp(value);
return true;
}
catch {
return false;
}
}
function IsControlCharacterFree(value) {
if (typeof value !== 'string')
return false;
for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i);
if ((code >= 7 && code <= 13) || code === 27 || code === 127) {
return false;
}
}
return true;
}
function IsString(value) {
return typeof value === 'string';
}
function IsNumber(value) {
return typeof value === 'number';
}
function IsBoolean(value) {
return typeof value === 'boolean';
}
function IsOptionalNumber(value) {
return value === undefined || (value !== undefined && IsNumber(value));
}
function IsOptionalBoolean(value) {
return value === undefined || (value !== undefined && IsBoolean(value));
}
function IsOptionalString(value) {
return value === undefined || (value !== undefined && IsString(value));
}
function IsOptionalPattern(value) {
return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value) && IsPattern(value));
}
function IsOptionalFormat(value) {
return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value));
}
function IsOptionalSchema(value) {
return value === undefined || TSchema(value);
}
/** Returns true if the given schema is TAny */
function TAny(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Any' && IsOptionalString(schema.$id);
}
TypeGuard.TAny = TAny;
/** Returns true if the given schema is TArray */
function TArray(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'Array' &&
schema.type === 'array' &&
IsOptionalString(schema.$id) &&
TSchema(schema.items) &&
IsOptionalNumber(schema.minItems) &&
IsOptionalNumber(schema.maxItems) &&
IsOptionalBoolean(schema.uniqueItems));
}
TypeGuard.TArray = TArray;
/** Returns true if the given schema is TBoolean */
function TBoolean(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Boolean' && schema.type === 'boolean' && IsOptionalString(schema.$id);
}
TypeGuard.TBoolean = TBoolean;
/** Returns true if the given schema is TConstructor */
function TConstructor(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Constructor' && schema.type === 'constructor' && IsOptionalString(schema.$id) && IsArray(schema.parameters) && TSchema(schema.returns))) {
return false;
}
for (const parameter of schema.parameters) {
if (!TSchema(parameter))
return false;
}
return true;
}
TypeGuard.TConstructor = TConstructor;
/** Returns true if the given schema is TFunction */
function TFunction(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Function' && schema.type === 'function' && IsOptionalString(schema.$id) && IsArray(schema.parameters) && TSchema(schema.returns))) {
return false;
}
for (const parameter of schema.parameters) {
if (!TSchema(parameter))
return false;
}
return true;
}
TypeGuard.TFunction = TFunction;
/** Returns true if the given schema is TInteger */
function TInteger(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'Integer' &&
schema.type === 'integer' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.multipleOf) &&
IsOptionalNumber(schema.minimum) &&
IsOptionalNumber(schema.maximum) &&
IsOptionalNumber(schema.exclusiveMinimum) &&
IsOptionalNumber(schema.exclusiveMaximum));
}
TypeGuard.TInteger = TInteger;
/** Returns true if the given schema is TLiteral */
function TLiteral(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Literal' && IsOptionalString(schema.$id) && (IsString(schema.const) || IsNumber(schema.const) || IsBoolean(schema.const));
}
TypeGuard.TLiteral = TLiteral;
/** Returns true if the given schema is TNever */
function TNever(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'Never' &&
IsArray(schema.allOf) &&
schema.allOf.length === 2 &&
IsObject(schema.allOf[0]) &&
IsString(schema.allOf[0].type) &&
schema.allOf[0].type === 'boolean' &&
schema.allOf[0].const === false &&
IsObject(schema.allOf[1]) &&
IsString(schema.allOf[1].type) &&
schema.allOf[1].type === 'boolean' &&
schema.allOf[1].const === true);
}
TypeGuard.TNever = TNever;
/** Returns true if the given schema is TNull */
function TNull(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Null' && schema.type === 'null' && IsOptionalString(schema.$id);
}
TypeGuard.TNull = TNull;
/** Returns true if the given schema is TNumber */
function TNumber(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'Number' &&
schema.type === 'number' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.multipleOf) &&
IsOptionalNumber(schema.minimum) &&
IsOptionalNumber(schema.maximum) &&
IsOptionalNumber(schema.exclusiveMinimum) &&
IsOptionalNumber(schema.exclusiveMaximum));
}
TypeGuard.TNumber = TNumber;
/** Returns true if the given schema is TObject */
function TObject(schema) {
if (!(IsObject(schema) &&
schema[Types.Kind] === 'Object' &&
schema.type === 'object' &&
IsOptionalString(schema.$id) &&
IsObject(schema.properties) &&
(IsOptionalBoolean(schema.additionalProperties) || IsOptionalSchema(schema.additionalProperties)) &&
IsOptionalNumber(schema.minProperties) &&
IsOptionalNumber(schema.maxProperties))) {
return false;
}
for (const [key, value] of Object.entries(schema.properties)) {
if (!IsControlCharacterFree(key))
return false;
if (!TSchema(value))
return false;
}
return true;
}
TypeGuard.TObject = TObject;
/** Returns true if the given schema is TPromise */
function TPromise(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Promise' && schema.type === 'promise' && IsOptionalString(schema.$id) && TSchema(schema.item);
}
TypeGuard.TPromise = TPromise;
/** Returns true if the given schema is TRecord */
function TRecord(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Record' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.additionalProperties === false && IsObject(schema.patternProperties))) {
return false;
}
const keys = Object.keys(schema.patternProperties);
if (keys.length !== 1) {
return false;
}
if (!IsPattern(keys[0])) {
return false;
}
if (!TSchema(schema.patternProperties[keys[0]])) {
return false;
}
return true;
}
TypeGuard.TRecord = TRecord;
/** Returns true if the given schema is TSelf */
function TSelf(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Self' && IsOptionalString(schema.$id) && IsString(schema.$ref);
}
TypeGuard.TSelf = TSelf;
/** Returns true if the given schema is TRef */
function TRef(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Ref' && IsOptionalString(schema.$id) && IsString(schema.$ref);
}
TypeGuard.TRef = TRef;
/** Returns true if the given schema is TString */
function TString(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'String' &&
schema.type === 'string' &&
IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.minLength) &&
IsOptionalNumber(schema.maxLength) &&
IsOptionalPattern(schema.pattern) &&
IsOptionalFormat(schema.format));
}
TypeGuard.TString = TString;
/** Returns true if the given schema is TTuple */
function TTuple(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Tuple' && schema.type === 'array' && IsOptionalString(schema.$id) && IsNumber(schema.minItems) && IsNumber(schema.maxItems) && schema.minItems === schema.maxItems)) {
return false;
}
if (schema.items === undefined && schema.additionalItems === undefined && schema.minItems === 0) {
return true;
}
if (!IsArray(schema.items)) {
return false;
}
for (const inner of schema.items) {
if (!TSchema(inner))
return false;
}
return true;
}
TypeGuard.TTuple = TTuple;
/** Returns true if the given schema is TUndefined */
function TUndefined(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Undefined' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.specialized === 'Undefined';
}
TypeGuard.TUndefined = TUndefined;
/** Returns true if the given schema is TUnion */
function TUnion(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Union' && IsArray(schema.anyOf) && IsOptionalString(schema.$id))) {
return false;
}
for (const inner of schema.anyOf) {
if (!TSchema(inner))
return false;
}
return true;
}
TypeGuard.TUnion = TUnion;
/** Returns true if the given schema is TUint8Array */
function TUint8Array(schema) {
return (IsObject(schema) &&
schema[Types.Kind] === 'Uint8Array' &&
schema.type === 'object' &&
IsOptionalString(schema.$id) &&
schema.specialized === 'Uint8Array' &&
IsOptionalNumber(schema.minByteLength) &&
IsOptionalNumber(schema.maxByteLength));
}
TypeGuard.TUint8Array = TUint8Array;
/** Returns true if the given schema is TUnknown */
function TUnknown(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Unknown' && IsOptionalString(schema.$id);
}
TypeGuard.TUnknown = TUnknown;
/** Returns true if the given schema is TVoid */
function TVoid(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Void' && schema.type === 'null' && IsOptionalString(schema.$id);
}
TypeGuard.TVoid = TVoid;
/** Returns true if the given schema is TSchema */
function TSchema(schema) {
return (TAny(schema) ||
TArray(schema) ||
TBoolean(schema) ||
TConstructor(schema) ||
TFunction(schema) ||
TInteger(schema) ||
TLiteral(schema) ||
TNever(schema) ||
TNull(schema) ||
TNumber(schema) ||
TObject(schema) ||
TPromise(schema) ||
TRecord(schema) ||
TSelf(schema) ||
TRef(schema) ||
TString(schema) ||
TTuple(schema) ||
TUndefined(schema) ||
TUnion(schema) ||
TUint8Array(schema) ||
TUnknown(schema) ||
TVoid(schema));
}
TypeGuard.TSchema = TSchema;
/** Asserts if this schema and associated references are valid. */
function Assert(schema, references = []) {
if (!TSchema(schema))
throw new TypeGuardInvalidTypeError(schema);
for (const schema of references) {
if (!TSchema(schema))
throw new TypeGuardInvalidTypeError(schema);
}
}
TypeGuard.Assert = Assert;
})(TypeGuard = exports.TypeGuard || (exports.TypeGuard = {}));

View File

@@ -1 +1 @@
export * from './guard';
export * from './guard';

View File

@@ -1,44 +1,44 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/guards
The MIT License (MIT)
Copyright (c) 2022 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("./guard"), exports);
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/guards
The MIT License (MIT)
Copyright (c) 2022 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("./guard"), exports);

View File

@@ -1,23 +1,23 @@
TypeBox: JSON Schema Type Builder with Static Type Resolution for TypeScript
The MIT License (MIT)
Copyright (c) 2022 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
TypeBox: JSON Schema Type Builder with Static Type Resolution for TypeScript
The MIT License (MIT)
Copyright (c) 2022 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

@@ -1,40 +1,40 @@
{
"name": "@sinclair/typebox",
"version": "0.24.51",
"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",
"repository": {
"type": "git",
"url": "https://github.com/sinclairzx81/typebox"
},
"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",
"publish": "hammer task publish"
},
"devDependencies": {
"@sinclair/hammer": "^0.17.1",
"@types/chai": "^4.3.3",
"@types/mocha": "^9.1.1",
"@types/node": "^18.7.13",
"ajv": "^8.11.0",
"ajv-formats": "^2.1.1",
"chai": "^4.3.6",
"mocha": "^9.2.2",
"prettier": "^2.7.1",
"typescript": "^4.8.2"
}
}
{
"name": "@sinclair/typebox",
"version": "0.24.51",
"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",
"repository": {
"type": "git",
"url": "https://github.com/sinclairzx81/typebox"
},
"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",
"publish": "hammer task publish"
},
"devDependencies": {
"@sinclair/hammer": "^0.17.1",
"@types/chai": "^4.3.3",
"@types/mocha": "^9.1.1",
"@types/node": "^18.7.13",
"ajv": "^8.11.0",
"ajv-formats": "^2.1.1",
"chai": "^4.3.6",
"mocha": "^9.2.2",
"prettier": "^2.7.1",
"typescript": "^4.8.2"
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,408 +1,408 @@
export declare const Kind: unique symbol;
export declare const Hint: unique symbol;
export declare const Modifier: unique symbol;
export declare type TModifier = TReadonlyOptional<TSchema> | TOptional<TSchema> | TReadonly<TSchema>;
export declare type TReadonly<T extends TSchema> = T & {
[Modifier]: 'Readonly';
};
export declare type TOptional<T extends TSchema> = T & {
[Modifier]: 'Optional';
};
export declare 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 TSchema extends SchemaOptions {
[Kind]: string;
[Hint]?: string;
[Modifier]?: string;
params: unknown[];
static: unknown;
}
export declare type TAnySchema = TSchema | TAny | TArray | TBoolean | TConstructor | TEnum | TFunction | TInteger | TLiteral | TNull | TNumber | TObject | TPromise | TRecord | TSelf | TRef | TString | TTuple | TUndefined | TUnion | TUint8Array | TUnknown | TVoid;
export interface NumericOptions extends SchemaOptions {
exclusiveMaximum?: number;
exclusiveMinimum?: number;
maximum?: number;
minimum?: number;
multipleOf?: number;
}
export declare type TNumeric = TInteger | TNumber;
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: Array<Static<T, this['params']>>;
type: 'array';
items: T;
}
export interface TBoolean extends TSchema {
[Kind]: 'Boolean';
static: boolean;
type: 'boolean';
}
export declare type TConstructorParameters<T extends TConstructor<TSchema[], TSchema>> = TTuple<T['parameters']>;
export declare type TInstanceType<T extends TConstructor<TSchema[], TSchema>> = T['returns'];
export declare type StaticContructorParameters<T extends readonly TSchema[], P extends unknown[]> = [...{
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never;
}];
export interface TConstructor<T extends TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Constructor';
static: new (...param: StaticContructorParameters<T, this['params']>) => Static<U, this['params']>;
type: 'constructor';
parameters: T;
returns: U;
}
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 declare type TParameters<T extends TFunction> = TTuple<T['parameters']>;
export declare type TReturnType<T extends TFunction> = T['returns'];
export declare type StaticFunctionParameters<T extends readonly TSchema[], P extends unknown[]> = [...{
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never;
}];
export interface TFunction<T extends readonly TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Function';
static: (...param: StaticFunctionParameters<T, this['params']>) => Static<U, this['params']>;
type: 'function';
parameters: T;
returns: U;
}
export interface TInteger extends TSchema, NumericOptions {
[Kind]: 'Integer';
static: number;
type: 'integer';
}
export declare type IntersectReduce<I extends unknown, T extends readonly any[]> = T extends [infer A, ...infer B] ? IntersectReduce<I & A, B> : I extends object ? I : {};
export declare type IntersectEvaluate<T extends readonly TSchema[], P extends unknown[]> = {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never;
};
export declare type IntersectProperties<T extends readonly TObject[]> = {
[K in keyof T]: T[K] extends TObject<infer P> ? P : {};
};
export interface TIntersect<T extends TObject[] = TObject[]> extends TObject {
static: IntersectReduce<unknown, IntersectEvaluate<T, this['params']>>;
properties: IntersectReduce<unknown, IntersectProperties<T>>;
}
export declare type UnionToIntersect<U> = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never;
export declare type UnionLast<U> = UnionToIntersect<U extends unknown ? (x: U) => 0 : never> extends (x: infer L) => 0 ? L : never;
export declare type UnionToTuple<U, L = UnionLast<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, L>>, L];
export declare type UnionStringLiteralToTuple<T> = T extends TUnion<infer L> ? {
[I in keyof L]: L[I] extends TLiteral<infer C> ? C : never;
} : never;
export declare type UnionLiteralsFromObject<T extends TObject> = {
[K in ObjectPropertyKeys<T>]: TLiteral<K>;
} extends infer R ? UnionToTuple<R[keyof R]> : never;
export interface TKeyOf<T extends TObject> extends TUnion<UnionLiteralsFromObject<T>> {
}
export declare 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;
allOf: [{
type: 'boolean';
const: false;
}, {
type: 'boolean';
const: true;
}];
}
export interface TNull extends TSchema {
[Kind]: 'Null';
static: null;
type: 'null';
}
export interface TNumber extends TSchema, NumericOptions {
[Kind]: 'Number';
static: number;
type: 'number';
}
export declare type ReadonlyOptionalPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TReadonlyOptional<TSchema> ? K : never;
}[keyof T];
export declare type ReadonlyPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TReadonly<TSchema> ? K : never;
}[keyof T];
export declare type OptionalPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TOptional<TSchema> ? K : never;
}[keyof T];
export declare type RequiredPropertyKeys<T extends TProperties> = keyof Omit<T, ReadonlyOptionalPropertyKeys<T> | ReadonlyPropertyKeys<T> | OptionalPropertyKeys<T>>;
export declare type PropertiesReduce<T extends TProperties, P extends unknown[]> = {
readonly [K in ReadonlyOptionalPropertyKeys<T>]?: Static<T[K], P>;
} & {
readonly [K in ReadonlyPropertyKeys<T>]: Static<T[K], P>;
} & {
[K in OptionalPropertyKeys<T>]?: Static<T[K], P>;
} & {
[K in RequiredPropertyKeys<T>]: Static<T[K], P>;
} extends infer R ? {
[K in keyof R]: R[K];
} : never;
export declare type TRecordProperties<K extends TUnion<TLiteral[]>, T extends TSchema> = Static<K> extends string ? {
[X in Static<K>]: T;
} : never;
export interface TProperties {
[key: string]: TSchema;
}
export declare type ObjectProperties<T> = T extends TObject<infer U> ? U : never;
export declare type ObjectPropertyKeys<T> = T extends TObject<infer U> ? keyof U : never;
export declare 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 interface TOmit<T extends TObject, Properties extends ObjectPropertyKeys<T>[]> extends TObject, ObjectOptions {
static: Omit<Static<T, this['params']>, Properties[number]>;
properties: T extends TObject ? Omit<T['properties'], Properties[number]> : never;
}
export interface TPartial<T extends TObject> extends TObject {
static: Partial<Static<T, this['params']>>;
properties: {
[K in keyof T['properties']]: T['properties'][K] extends TReadonlyOptional<infer U> ? TReadonlyOptional<U> : T['properties'][K] extends TReadonly<infer U> ? TReadonlyOptional<U> : T['properties'][K] extends TOptional<infer U> ? TOptional<U> : TOptional<T['properties'][K]>;
};
}
export declare type TPick<T extends TObject, Properties extends ObjectPropertyKeys<T>[]> = TObject<{
[K in Properties[number]]: T['properties'][K];
}>;
export interface TPromise<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Promise';
static: Promise<Static<T, this['params']>>;
type: 'promise';
item: TSchema;
}
export declare type TRecordKey = TString | TNumeric | TUnion<TLiteral<any>[]>;
export interface TRecord<K extends TRecordKey = TRecordKey, 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 TSelf extends TSchema {
[Kind]: 'Self';
static: this['params'][0];
$ref: string;
}
export declare type TRecursiveReduce<T extends TSchema> = Static<T, [TRecursiveReduce<T>]>;
export interface TRecursive<T extends TSchema> extends TSchema {
static: TRecursiveReduce<T>;
}
export interface TRef<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Ref';
static: Static<T, this['params']>;
$ref: string;
}
export interface TRequired<T extends TObject | TRef<TObject>> extends TObject {
static: Required<Static<T, this['params']>>;
properties: {
[K in keyof T['properties']]: T['properties'][K] extends TReadonlyOptional<infer U> ? TReadonly<U> : T['properties'][K] extends TReadonly<infer U> ? TReadonly<U> : T['properties'][K] extends TOptional<infer U> ? U : T['properties'][K];
};
}
export declare 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 declare type TupleToArray<T extends TTuple<TSchema[]>> = T extends TTuple<infer R> ? R : 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';
specialized: 'Undefined';
static: undefined;
type: 'object';
}
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;
specialized: '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';
}
/** Creates a static type from a TypeBox type */
export declare type Static<T extends TSchema, P extends unknown[] = []> = (T & {
params: P;
})['static'];
export declare class TypeBuilder {
/** Creates a readonly optional property */
ReadonlyOptional<T extends TSchema>(item: T): TReadonlyOptional<T>;
/** Creates a readonly property */
Readonly<T extends TSchema>(item: T): TReadonly<T>;
/** Creates a optional property */
Optional<T extends TSchema>(item: T): TOptional<T>;
/** Creates a any type */
Any(options?: SchemaOptions): TAny;
/** Creates a array type */
Array<T extends TSchema>(items: T, options?: ArrayOptions): TArray<T>;
/** Creates a boolean type */
Boolean(options?: SchemaOptions): TBoolean;
/** Creates a tuple type from this constructors parameters */
ConstructorParameters<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TConstructorParameters<T>;
/** Creates a constructor type */
Constructor<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TConstructor<TupleToArray<T>, U>;
/** Creates a constructor type */
Constructor<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TConstructor<T, U>;
/** Creates a enum type */
Enum<T extends Record<string, string | number>>(item: T, options?: SchemaOptions): TEnum<T>;
/** Creates a function type */
Function<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TFunction<TupleToArray<T>, U>;
/** Creates a function type */
Function<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TFunction<T, U>;
/** Creates a type from this constructors instance type */
InstanceType<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TInstanceType<T>;
/** Creates a integer type */
Integer(options?: NumericOptions): TInteger;
/** Creates a intersect type. */
Intersect<T extends TObject[]>(objects: [...T], options?: ObjectOptions): TIntersect<T>;
/** Creates a keyof type */
KeyOf<T extends TObject>(object: T, options?: SchemaOptions): TKeyOf<T>;
/** Creates a literal type. */
Literal<T extends TLiteralValue>(value: T, options?: SchemaOptions): TLiteral<T>;
/** Creates a never type */
Never(options?: SchemaOptions): TNever;
/** Creates a null type */
Null(options?: SchemaOptions): TNull;
/** Creates a number type */
Number(options?: NumericOptions): TNumber;
/** Creates an object type with the given properties */
Object<T extends TProperties>(properties: T, options?: ObjectOptions): TObject<T>;
/** Creates a new object whose properties are omitted from the given object */
Omit<T extends TObject, K extends TUnion<TLiteral<string>[]>>(schema: T, keys: K, options?: ObjectOptions): TOmit<T, UnionStringLiteralToTuple<K>>;
/** Creates a new object whose properties are omitted from the given object */
Omit<T extends TObject, K extends ObjectPropertyKeys<T>[]>(schema: T, keys: readonly [...K], options?: ObjectOptions): TOmit<T, K>;
/** Creates a tuple type from this functions parameters */
Parameters<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TParameters<T>;
/** Creates an object type whose properties are all optional */
Partial<T extends TObject>(schema: T, options?: ObjectOptions): TPartial<T>;
/** Creates a object whose properties are picked from the given object */
Pick<T extends TObject, K extends TUnion<TLiteral<string>[]>>(schema: T, keys: K, options?: ObjectOptions): TPick<T, UnionStringLiteralToTuple<K>>;
/** Creates a object whose properties are picked from the given object */
Pick<T extends TObject, K extends ObjectPropertyKeys<T>[]>(schema: T, keys: readonly [...K], options?: ObjectOptions): TPick<T, K>;
/** Creates a promise type. This type cannot be represented in schema. */
Promise<T extends TSchema>(item: T, options?: SchemaOptions): TPromise<T>;
/** Creates an object whose properties are derived from the given string literal union. */
Record<K extends TUnion<TLiteral[]>, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): TObject<TRecordProperties<K, T>>;
/** Creates a record type */
Record<K extends TString | TNumeric, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): TRecord<K, T>;
/** Creates a recursive object type */
Recursive<T extends TSchema>(callback: (self: TSelf) => T, options?: SchemaOptions): TRecursive<T>;
/** Creates a reference schema */
Ref<T extends TSchema>(schema: T, options?: SchemaOptions): TRef<T>;
/** Creates a string type from a regular expression */
RegEx(regex: RegExp, options?: SchemaOptions): TString;
/** Creates an object type whose properties are all required */
Required<T extends TObject>(schema: T, options?: SchemaOptions): TRequired<T>;
/** Creates a type from this functions return type */
ReturnType<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TReturnType<T>;
/** Removes Kind and Modifier symbol property keys from this schema */
Strict<T extends TSchema>(schema: T): T;
/** Creates a string type */
String<Format extends string>(options?: StringOptions<StringFormatOption | Format>): TString<Format>;
/** Creates a tuple type */
Tuple<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TTuple<T>;
/** Creates a undefined type */
Undefined(options?: SchemaOptions): TUndefined;
/** Creates a union type */
Union(items: [], options?: SchemaOptions): TNever;
Union<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TUnion<T>;
/** Creates a Uint8Array type */
Uint8Array(options?: Uint8ArrayOptions): TUint8Array;
/** Creates an unknown type */
Unknown(options?: SchemaOptions): TUnknown;
/** Creates a user defined schema that infers as type T */
Unsafe<T>(options?: UnsafeOptions): TUnsafe<T>;
/** Creates a void type */
Void(options?: SchemaOptions): TVoid;
/** Use this function to return TSchema with static and params omitted */
protected Create<T>(schema: Omit<T, 'static' | 'params'>): T;
/** Clones the given value */
protected Clone(value: any): any;
}
/** JSON Schema Type Builder with Static Type Resolution for TypeScript */
export declare const Type: TypeBuilder;
export declare const Kind: unique symbol;
export declare const Hint: unique symbol;
export declare const Modifier: unique symbol;
export declare type TModifier = TReadonlyOptional<TSchema> | TOptional<TSchema> | TReadonly<TSchema>;
export declare type TReadonly<T extends TSchema> = T & {
[Modifier]: 'Readonly';
};
export declare type TOptional<T extends TSchema> = T & {
[Modifier]: 'Optional';
};
export declare 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 TSchema extends SchemaOptions {
[Kind]: string;
[Hint]?: string;
[Modifier]?: string;
params: unknown[];
static: unknown;
}
export declare type TAnySchema = TSchema | TAny | TArray | TBoolean | TConstructor | TEnum | TFunction | TInteger | TLiteral | TNull | TNumber | TObject | TPromise | TRecord | TSelf | TRef | TString | TTuple | TUndefined | TUnion | TUint8Array | TUnknown | TVoid;
export interface NumericOptions extends SchemaOptions {
exclusiveMaximum?: number;
exclusiveMinimum?: number;
maximum?: number;
minimum?: number;
multipleOf?: number;
}
export declare type TNumeric = TInteger | TNumber;
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: Array<Static<T, this['params']>>;
type: 'array';
items: T;
}
export interface TBoolean extends TSchema {
[Kind]: 'Boolean';
static: boolean;
type: 'boolean';
}
export declare type TConstructorParameters<T extends TConstructor<TSchema[], TSchema>> = TTuple<T['parameters']>;
export declare type TInstanceType<T extends TConstructor<TSchema[], TSchema>> = T['returns'];
export declare type StaticContructorParameters<T extends readonly TSchema[], P extends unknown[]> = [...{
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never;
}];
export interface TConstructor<T extends TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Constructor';
static: new (...param: StaticContructorParameters<T, this['params']>) => Static<U, this['params']>;
type: 'constructor';
parameters: T;
returns: U;
}
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 declare type TParameters<T extends TFunction> = TTuple<T['parameters']>;
export declare type TReturnType<T extends TFunction> = T['returns'];
export declare type StaticFunctionParameters<T extends readonly TSchema[], P extends unknown[]> = [...{
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never;
}];
export interface TFunction<T extends readonly TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Function';
static: (...param: StaticFunctionParameters<T, this['params']>) => Static<U, this['params']>;
type: 'function';
parameters: T;
returns: U;
}
export interface TInteger extends TSchema, NumericOptions {
[Kind]: 'Integer';
static: number;
type: 'integer';
}
export declare type IntersectReduce<I extends unknown, T extends readonly any[]> = T extends [infer A, ...infer B] ? IntersectReduce<I & A, B> : I extends object ? I : {};
export declare type IntersectEvaluate<T extends readonly TSchema[], P extends unknown[]> = {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never;
};
export declare type IntersectProperties<T extends readonly TObject[]> = {
[K in keyof T]: T[K] extends TObject<infer P> ? P : {};
};
export interface TIntersect<T extends TObject[] = TObject[]> extends TObject {
static: IntersectReduce<unknown, IntersectEvaluate<T, this['params']>>;
properties: IntersectReduce<unknown, IntersectProperties<T>>;
}
export declare type UnionToIntersect<U> = (U extends unknown ? (arg: U) => 0 : never) extends (arg: infer I) => 0 ? I : never;
export declare type UnionLast<U> = UnionToIntersect<U extends unknown ? (x: U) => 0 : never> extends (x: infer L) => 0 ? L : never;
export declare type UnionToTuple<U, L = UnionLast<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, L>>, L];
export declare type UnionStringLiteralToTuple<T> = T extends TUnion<infer L> ? {
[I in keyof L]: L[I] extends TLiteral<infer C> ? C : never;
} : never;
export declare type UnionLiteralsFromObject<T extends TObject> = {
[K in ObjectPropertyKeys<T>]: TLiteral<K>;
} extends infer R ? UnionToTuple<R[keyof R]> : never;
export interface TKeyOf<T extends TObject> extends TUnion<UnionLiteralsFromObject<T>> {
}
export declare 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;
allOf: [{
type: 'boolean';
const: false;
}, {
type: 'boolean';
const: true;
}];
}
export interface TNull extends TSchema {
[Kind]: 'Null';
static: null;
type: 'null';
}
export interface TNumber extends TSchema, NumericOptions {
[Kind]: 'Number';
static: number;
type: 'number';
}
export declare type ReadonlyOptionalPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TReadonlyOptional<TSchema> ? K : never;
}[keyof T];
export declare type ReadonlyPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TReadonly<TSchema> ? K : never;
}[keyof T];
export declare type OptionalPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TOptional<TSchema> ? K : never;
}[keyof T];
export declare type RequiredPropertyKeys<T extends TProperties> = keyof Omit<T, ReadonlyOptionalPropertyKeys<T> | ReadonlyPropertyKeys<T> | OptionalPropertyKeys<T>>;
export declare type PropertiesReduce<T extends TProperties, P extends unknown[]> = {
readonly [K in ReadonlyOptionalPropertyKeys<T>]?: Static<T[K], P>;
} & {
readonly [K in ReadonlyPropertyKeys<T>]: Static<T[K], P>;
} & {
[K in OptionalPropertyKeys<T>]?: Static<T[K], P>;
} & {
[K in RequiredPropertyKeys<T>]: Static<T[K], P>;
} extends infer R ? {
[K in keyof R]: R[K];
} : never;
export declare type TRecordProperties<K extends TUnion<TLiteral[]>, T extends TSchema> = Static<K> extends string ? {
[X in Static<K>]: T;
} : never;
export interface TProperties {
[key: string]: TSchema;
}
export declare type ObjectProperties<T> = T extends TObject<infer U> ? U : never;
export declare type ObjectPropertyKeys<T> = T extends TObject<infer U> ? keyof U : never;
export declare 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 interface TOmit<T extends TObject, Properties extends ObjectPropertyKeys<T>[]> extends TObject, ObjectOptions {
static: Omit<Static<T, this['params']>, Properties[number]>;
properties: T extends TObject ? Omit<T['properties'], Properties[number]> : never;
}
export interface TPartial<T extends TObject> extends TObject {
static: Partial<Static<T, this['params']>>;
properties: {
[K in keyof T['properties']]: T['properties'][K] extends TReadonlyOptional<infer U> ? TReadonlyOptional<U> : T['properties'][K] extends TReadonly<infer U> ? TReadonlyOptional<U> : T['properties'][K] extends TOptional<infer U> ? TOptional<U> : TOptional<T['properties'][K]>;
};
}
export declare type TPick<T extends TObject, Properties extends ObjectPropertyKeys<T>[]> = TObject<{
[K in Properties[number]]: T['properties'][K];
}>;
export interface TPromise<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Promise';
static: Promise<Static<T, this['params']>>;
type: 'promise';
item: TSchema;
}
export declare type TRecordKey = TString | TNumeric | TUnion<TLiteral<any>[]>;
export interface TRecord<K extends TRecordKey = TRecordKey, 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 TSelf extends TSchema {
[Kind]: 'Self';
static: this['params'][0];
$ref: string;
}
export declare type TRecursiveReduce<T extends TSchema> = Static<T, [TRecursiveReduce<T>]>;
export interface TRecursive<T extends TSchema> extends TSchema {
static: TRecursiveReduce<T>;
}
export interface TRef<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Ref';
static: Static<T, this['params']>;
$ref: string;
}
export interface TRequired<T extends TObject | TRef<TObject>> extends TObject {
static: Required<Static<T, this['params']>>;
properties: {
[K in keyof T['properties']]: T['properties'][K] extends TReadonlyOptional<infer U> ? TReadonly<U> : T['properties'][K] extends TReadonly<infer U> ? TReadonly<U> : T['properties'][K] extends TOptional<infer U> ? U : T['properties'][K];
};
}
export declare 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 declare type TupleToArray<T extends TTuple<TSchema[]>> = T extends TTuple<infer R> ? R : 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';
specialized: 'Undefined';
static: undefined;
type: 'object';
}
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;
specialized: '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';
}
/** Creates a static type from a TypeBox type */
export declare type Static<T extends TSchema, P extends unknown[] = []> = (T & {
params: P;
})['static'];
export declare class TypeBuilder {
/** Creates a readonly optional property */
ReadonlyOptional<T extends TSchema>(item: T): TReadonlyOptional<T>;
/** Creates a readonly property */
Readonly<T extends TSchema>(item: T): TReadonly<T>;
/** Creates a optional property */
Optional<T extends TSchema>(item: T): TOptional<T>;
/** Creates a any type */
Any(options?: SchemaOptions): TAny;
/** Creates a array type */
Array<T extends TSchema>(items: T, options?: ArrayOptions): TArray<T>;
/** Creates a boolean type */
Boolean(options?: SchemaOptions): TBoolean;
/** Creates a tuple type from this constructors parameters */
ConstructorParameters<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TConstructorParameters<T>;
/** Creates a constructor type */
Constructor<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TConstructor<TupleToArray<T>, U>;
/** Creates a constructor type */
Constructor<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TConstructor<T, U>;
/** Creates a enum type */
Enum<T extends Record<string, string | number>>(item: T, options?: SchemaOptions): TEnum<T>;
/** Creates a function type */
Function<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TFunction<TupleToArray<T>, U>;
/** Creates a function type */
Function<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TFunction<T, U>;
/** Creates a type from this constructors instance type */
InstanceType<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TInstanceType<T>;
/** Creates a integer type */
Integer(options?: NumericOptions): TInteger;
/** Creates a intersect type. */
Intersect<T extends TObject[]>(objects: [...T], options?: ObjectOptions): TIntersect<T>;
/** Creates a keyof type */
KeyOf<T extends TObject>(object: T, options?: SchemaOptions): TKeyOf<T>;
/** Creates a literal type. */
Literal<T extends TLiteralValue>(value: T, options?: SchemaOptions): TLiteral<T>;
/** Creates a never type */
Never(options?: SchemaOptions): TNever;
/** Creates a null type */
Null(options?: SchemaOptions): TNull;
/** Creates a number type */
Number(options?: NumericOptions): TNumber;
/** Creates an object type with the given properties */
Object<T extends TProperties>(properties: T, options?: ObjectOptions): TObject<T>;
/** Creates a new object whose properties are omitted from the given object */
Omit<T extends TObject, K extends TUnion<TLiteral<string>[]>>(schema: T, keys: K, options?: ObjectOptions): TOmit<T, UnionStringLiteralToTuple<K>>;
/** Creates a new object whose properties are omitted from the given object */
Omit<T extends TObject, K extends ObjectPropertyKeys<T>[]>(schema: T, keys: readonly [...K], options?: ObjectOptions): TOmit<T, K>;
/** Creates a tuple type from this functions parameters */
Parameters<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TParameters<T>;
/** Creates an object type whose properties are all optional */
Partial<T extends TObject>(schema: T, options?: ObjectOptions): TPartial<T>;
/** Creates a object whose properties are picked from the given object */
Pick<T extends TObject, K extends TUnion<TLiteral<string>[]>>(schema: T, keys: K, options?: ObjectOptions): TPick<T, UnionStringLiteralToTuple<K>>;
/** Creates a object whose properties are picked from the given object */
Pick<T extends TObject, K extends ObjectPropertyKeys<T>[]>(schema: T, keys: readonly [...K], options?: ObjectOptions): TPick<T, K>;
/** Creates a promise type. This type cannot be represented in schema. */
Promise<T extends TSchema>(item: T, options?: SchemaOptions): TPromise<T>;
/** Creates an object whose properties are derived from the given string literal union. */
Record<K extends TUnion<TLiteral[]>, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): TObject<TRecordProperties<K, T>>;
/** Creates a record type */
Record<K extends TString | TNumeric, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): TRecord<K, T>;
/** Creates a recursive object type */
Recursive<T extends TSchema>(callback: (self: TSelf) => T, options?: SchemaOptions): TRecursive<T>;
/** Creates a reference schema */
Ref<T extends TSchema>(schema: T, options?: SchemaOptions): TRef<T>;
/** Creates a string type from a regular expression */
RegEx(regex: RegExp, options?: SchemaOptions): TString;
/** Creates an object type whose properties are all required */
Required<T extends TObject>(schema: T, options?: SchemaOptions): TRequired<T>;
/** Creates a type from this functions return type */
ReturnType<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TReturnType<T>;
/** Removes Kind and Modifier symbol property keys from this schema */
Strict<T extends TSchema>(schema: T): T;
/** Creates a string type */
String<Format extends string>(options?: StringOptions<StringFormatOption | Format>): TString<Format>;
/** Creates a tuple type */
Tuple<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TTuple<T>;
/** Creates a undefined type */
Undefined(options?: SchemaOptions): TUndefined;
/** Creates a union type */
Union(items: [], options?: SchemaOptions): TNever;
Union<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TUnion<T>;
/** Creates a Uint8Array type */
Uint8Array(options?: Uint8ArrayOptions): TUint8Array;
/** Creates an unknown type */
Unknown(options?: SchemaOptions): TUnknown;
/** Creates a user defined schema that infers as type T */
Unsafe<T>(options?: UnsafeOptions): TUnsafe<T>;
/** Creates a void type */
Void(options?: SchemaOptions): TVoid;
/** Use this function to return TSchema with static and params omitted */
protected Create<T>(schema: Omit<T, 'static' | 'params'>): T;
/** Clones the given value */
protected Clone(value: any): any;
}
/** JSON Schema Type Builder with Static Type Resolution for TypeScript */
export declare const Type: TypeBuilder;

View File

@@ -1,383 +1,383 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox
The MIT License (MIT)
Copyright (c) 2022 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.Type = exports.TypeBuilder = exports.Modifier = exports.Hint = exports.Kind = void 0;
// --------------------------------------------------------------------------
// Symbols
// --------------------------------------------------------------------------
exports.Kind = Symbol.for('TypeBox.Kind');
exports.Hint = Symbol.for('TypeBox.Hint');
exports.Modifier = Symbol.for('TypeBox.Modifier');
// --------------------------------------------------------------------------
// TypeBuilder
// --------------------------------------------------------------------------
let TypeOrdinal = 0;
class TypeBuilder {
// ----------------------------------------------------------------------
// Modifiers
// ----------------------------------------------------------------------
/** Creates a readonly optional property */
ReadonlyOptional(item) {
return { [exports.Modifier]: 'ReadonlyOptional', ...item };
}
/** Creates a readonly property */
Readonly(item) {
return { [exports.Modifier]: 'Readonly', ...item };
}
/** Creates a optional property */
Optional(item) {
return { [exports.Modifier]: 'Optional', ...item };
}
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
/** Creates a any type */
Any(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Any' });
}
/** Creates a array type */
Array(items, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Array', type: 'array', items });
}
/** Creates a boolean type */
Boolean(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Boolean', type: 'boolean' });
}
/** Creates a tuple type from this constructors parameters */
ConstructorParameters(schema, options = {}) {
return this.Tuple([...schema.parameters], { ...options });
}
/** Creates a constructor type */
Constructor(parameters, returns, options = {}) {
if (parameters[exports.Kind] === 'Tuple') {
const inner = parameters.items === undefined ? [] : parameters.items;
return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'constructor', parameters: inner, returns });
}
else if (globalThis.Array.isArray(parameters)) {
return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'constructor', parameters, returns });
}
else {
throw new Error('TypeBuilder.Constructor: Invalid parameters');
}
}
/** Creates a enum type */
Enum(item, options = {}) {
const values = Object.keys(item)
.filter((key) => isNaN(key))
.map((key) => item[key]);
const anyOf = values.map((value) => (typeof value === 'string' ? { [exports.Kind]: 'Literal', type: 'string', const: value } : { [exports.Kind]: 'Literal', type: 'number', const: value }));
return this.Create({ ...options, [exports.Kind]: 'Union', [exports.Hint]: 'Enum', anyOf });
}
/** Creates a function type */
Function(parameters, returns, options = {}) {
if (parameters[exports.Kind] === 'Tuple') {
const inner = parameters.items === undefined ? [] : parameters.items;
return this.Create({ ...options, [exports.Kind]: 'Function', type: 'function', parameters: inner, returns });
}
else if (globalThis.Array.isArray(parameters)) {
return this.Create({ ...options, [exports.Kind]: 'Function', type: 'function', parameters, returns });
}
else {
throw new Error('TypeBuilder.Function: Invalid parameters');
}
}
/** Creates a type from this constructors instance type */
InstanceType(schema, options = {}) {
return { ...options, ...this.Clone(schema.returns) };
}
/** Creates a integer type */
Integer(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Integer', type: 'integer' });
}
/** Creates a intersect type. */
Intersect(objects, options = {}) {
const isOptional = (schema) => (schema[exports.Modifier] && schema[exports.Modifier] === 'Optional') || schema[exports.Modifier] === 'ReadonlyOptional';
const [required, optional] = [new Set(), new Set()];
for (const object of objects) {
for (const [key, schema] of Object.entries(object.properties)) {
if (isOptional(schema))
optional.add(key);
}
}
for (const object of objects) {
for (const key of Object.keys(object.properties)) {
if (!optional.has(key))
required.add(key);
}
}
const properties = {};
for (const object of objects) {
for (const [key, schema] of Object.entries(object.properties)) {
properties[key] = properties[key] === undefined ? schema : { [exports.Kind]: 'Union', anyOf: [properties[key], { ...schema }] };
}
}
if (required.size > 0) {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties, required: [...required] });
}
else {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties });
}
}
/** Creates a keyof type */
KeyOf(object, options = {}) {
const items = Object.keys(object.properties).map((key) => this.Create({ ...options, [exports.Kind]: 'Literal', type: 'string', const: key }));
return this.Create({ ...options, [exports.Kind]: 'Union', [exports.Hint]: 'KeyOf', anyOf: items });
}
/** Creates a literal type. */
Literal(value, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Literal', const: value, type: typeof value });
}
/** Creates a never type */
Never(options = {}) {
return this.Create({
...options,
[exports.Kind]: 'Never',
allOf: [
{ type: 'boolean', const: false },
{ type: 'boolean', const: true },
],
});
}
/** Creates a null type */
Null(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Null', type: 'null' });
}
/** Creates a number type */
Number(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Number', type: 'number' });
}
/** Creates an object type with the given properties */
Object(properties, options = {}) {
const property_names = Object.keys(properties);
const optional = property_names.filter((name) => {
const property = properties[name];
const modifier = property[exports.Modifier];
return modifier && (modifier === 'Optional' || modifier === 'ReadonlyOptional');
});
const required = property_names.filter((name) => !optional.includes(name));
if (required.length > 0) {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties, required });
}
else {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties });
}
}
/** Creates a new object whose properties are omitted from the given object */
Omit(schema, keys, options = {}) {
const select = keys[exports.Kind] === 'Union' ? keys.anyOf.map((schema) => schema.const) : keys;
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Omit' };
if (next.required) {
next.required = next.required.filter((key) => !select.includes(key));
if (next.required.length === 0)
delete next.required;
}
for (const key of Object.keys(next.properties)) {
if (select.includes(key))
delete next.properties[key];
}
return this.Create(next);
}
/** Creates a tuple type from this functions parameters */
Parameters(schema, options = {}) {
return exports.Type.Tuple(schema.parameters, { ...options });
}
/** Creates an object type whose properties are all optional */
Partial(schema, options = {}) {
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Partial' };
delete next.required;
for (const key of Object.keys(next.properties)) {
const property = next.properties[key];
const modifer = property[exports.Modifier];
switch (modifer) {
case 'ReadonlyOptional':
property[exports.Modifier] = 'ReadonlyOptional';
break;
case 'Readonly':
property[exports.Modifier] = 'ReadonlyOptional';
break;
case 'Optional':
property[exports.Modifier] = 'Optional';
break;
default:
property[exports.Modifier] = 'Optional';
break;
}
}
return this.Create(next);
}
/** Creates a object whose properties are picked from the given object */
Pick(schema, keys, options = {}) {
const select = keys[exports.Kind] === 'Union' ? keys.anyOf.map((schema) => schema.const) : keys;
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Pick' };
if (next.required) {
next.required = next.required.filter((key) => select.includes(key));
if (next.required.length === 0)
delete next.required;
}
for (const key of Object.keys(next.properties)) {
if (!select.includes(key))
delete next.properties[key];
}
return this.Create(next);
}
/** Creates a promise type. This type cannot be represented in schema. */
Promise(item, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Promise', type: 'promise', item });
}
/** Creates a record type */
Record(key, value, options = {}) {
// If string literal union return TObject with properties extracted from union.
if (key[exports.Kind] === 'Union') {
return this.Object(key.anyOf.reduce((acc, literal) => {
return { ...acc, [literal.const]: value };
}, {}), { ...options, [exports.Hint]: 'Record' });
}
// otherwise return TRecord with patternProperties
const pattern = ['Integer', 'Number'].includes(key[exports.Kind]) ? '^(0|[1-9][0-9]*)$' : key[exports.Kind] === 'String' && key.pattern ? key.pattern : '^.*$';
return this.Create({
...options,
[exports.Kind]: 'Record',
type: 'object',
patternProperties: { [pattern]: value },
additionalProperties: false,
});
}
/** Creates a recursive object type */
Recursive(callback, options = {}) {
if (options.$id === undefined)
options.$id = `T${TypeOrdinal++}`;
const self = callback({ [exports.Kind]: 'Self', $ref: `${options.$id}` });
self.$id = options.$id;
return this.Create({ ...options, ...self });
}
/** Creates a reference schema */
Ref(schema, options = {}) {
if (schema.$id === undefined)
throw Error('TypeBuilder.Ref: Referenced schema must specify an $id');
return this.Create({ ...options, [exports.Kind]: 'Ref', $ref: schema.$id });
}
/** Creates a string type from a regular expression */
RegEx(regex, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'String', type: 'string', pattern: regex.source });
}
/** Creates an object type whose properties are all required */
Required(schema, options = {}) {
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Required' };
next.required = Object.keys(next.properties);
for (const key of Object.keys(next.properties)) {
const property = next.properties[key];
const modifier = property[exports.Modifier];
switch (modifier) {
case 'ReadonlyOptional':
property[exports.Modifier] = 'Readonly';
break;
case 'Readonly':
property[exports.Modifier] = 'Readonly';
break;
case 'Optional':
delete property[exports.Modifier];
break;
default:
delete property[exports.Modifier];
break;
}
}
return this.Create(next);
}
/** Creates a type from this functions return type */
ReturnType(schema, options = {}) {
return { ...options, ...this.Clone(schema.returns) };
}
/** Removes Kind and Modifier symbol property keys from this schema */
Strict(schema) {
return JSON.parse(JSON.stringify(schema));
}
/** Creates a string type */
String(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'String', type: 'string' });
}
/** Creates a tuple type */
Tuple(items, options = {}) {
const additionalItems = false;
const minItems = items.length;
const maxItems = items.length;
const schema = (items.length > 0 ? { ...options, [exports.Kind]: 'Tuple', type: 'array', items, additionalItems, minItems, maxItems } : { ...options, [exports.Kind]: 'Tuple', type: 'array', minItems, maxItems });
return this.Create(schema);
}
/** Creates a undefined type */
Undefined(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Undefined', type: 'object', specialized: 'Undefined' });
}
Union(items, options = {}) {
return items.length === 0 ? exports.Type.Never({ ...options }) : this.Create({ ...options, [exports.Kind]: 'Union', anyOf: items });
}
/** Creates a Uint8Array type */
Uint8Array(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Uint8Array', type: 'object', specialized: 'Uint8Array' });
}
/** Creates an unknown type */
Unknown(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Unknown' });
}
/** Creates a user defined schema that infers as type T */
Unsafe(options = {}) {
return this.Create({ ...options, [exports.Kind]: options[exports.Kind] || 'Unsafe' });
}
/** Creates a void type */
Void(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Void', type: 'null' });
}
/** Use this function to return TSchema with static and params omitted */
Create(schema) {
return schema;
}
/** Clones the given value */
Clone(value) {
const isObject = (object) => typeof object === 'object' && object !== null && !Array.isArray(object);
const isArray = (object) => typeof object === 'object' && object !== null && Array.isArray(object);
if (isObject(value)) {
return Object.keys(value).reduce((acc, key) => ({
...acc,
[key]: this.Clone(value[key]),
}), Object.getOwnPropertySymbols(value).reduce((acc, key) => ({
...acc,
[key]: this.Clone(value[key]),
}), {}));
}
else if (isArray(value)) {
return value.map((item) => this.Clone(item));
}
else {
return value;
}
}
}
exports.TypeBuilder = TypeBuilder;
/** JSON Schema Type Builder with Static Type Resolution for TypeScript */
exports.Type = new TypeBuilder();
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox
The MIT License (MIT)
Copyright (c) 2022 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.Type = exports.TypeBuilder = exports.Modifier = exports.Hint = exports.Kind = void 0;
// --------------------------------------------------------------------------
// Symbols
// --------------------------------------------------------------------------
exports.Kind = Symbol.for('TypeBox.Kind');
exports.Hint = Symbol.for('TypeBox.Hint');
exports.Modifier = Symbol.for('TypeBox.Modifier');
// --------------------------------------------------------------------------
// TypeBuilder
// --------------------------------------------------------------------------
let TypeOrdinal = 0;
class TypeBuilder {
// ----------------------------------------------------------------------
// Modifiers
// ----------------------------------------------------------------------
/** Creates a readonly optional property */
ReadonlyOptional(item) {
return { [exports.Modifier]: 'ReadonlyOptional', ...item };
}
/** Creates a readonly property */
Readonly(item) {
return { [exports.Modifier]: 'Readonly', ...item };
}
/** Creates a optional property */
Optional(item) {
return { [exports.Modifier]: 'Optional', ...item };
}
// ----------------------------------------------------------------------
// Types
// ----------------------------------------------------------------------
/** Creates a any type */
Any(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Any' });
}
/** Creates a array type */
Array(items, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Array', type: 'array', items });
}
/** Creates a boolean type */
Boolean(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Boolean', type: 'boolean' });
}
/** Creates a tuple type from this constructors parameters */
ConstructorParameters(schema, options = {}) {
return this.Tuple([...schema.parameters], { ...options });
}
/** Creates a constructor type */
Constructor(parameters, returns, options = {}) {
if (parameters[exports.Kind] === 'Tuple') {
const inner = parameters.items === undefined ? [] : parameters.items;
return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'constructor', parameters: inner, returns });
}
else if (globalThis.Array.isArray(parameters)) {
return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'constructor', parameters, returns });
}
else {
throw new Error('TypeBuilder.Constructor: Invalid parameters');
}
}
/** Creates a enum type */
Enum(item, options = {}) {
const values = Object.keys(item)
.filter((key) => isNaN(key))
.map((key) => item[key]);
const anyOf = values.map((value) => (typeof value === 'string' ? { [exports.Kind]: 'Literal', type: 'string', const: value } : { [exports.Kind]: 'Literal', type: 'number', const: value }));
return this.Create({ ...options, [exports.Kind]: 'Union', [exports.Hint]: 'Enum', anyOf });
}
/** Creates a function type */
Function(parameters, returns, options = {}) {
if (parameters[exports.Kind] === 'Tuple') {
const inner = parameters.items === undefined ? [] : parameters.items;
return this.Create({ ...options, [exports.Kind]: 'Function', type: 'function', parameters: inner, returns });
}
else if (globalThis.Array.isArray(parameters)) {
return this.Create({ ...options, [exports.Kind]: 'Function', type: 'function', parameters, returns });
}
else {
throw new Error('TypeBuilder.Function: Invalid parameters');
}
}
/** Creates a type from this constructors instance type */
InstanceType(schema, options = {}) {
return { ...options, ...this.Clone(schema.returns) };
}
/** Creates a integer type */
Integer(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Integer', type: 'integer' });
}
/** Creates a intersect type. */
Intersect(objects, options = {}) {
const isOptional = (schema) => (schema[exports.Modifier] && schema[exports.Modifier] === 'Optional') || schema[exports.Modifier] === 'ReadonlyOptional';
const [required, optional] = [new Set(), new Set()];
for (const object of objects) {
for (const [key, schema] of Object.entries(object.properties)) {
if (isOptional(schema))
optional.add(key);
}
}
for (const object of objects) {
for (const key of Object.keys(object.properties)) {
if (!optional.has(key))
required.add(key);
}
}
const properties = {};
for (const object of objects) {
for (const [key, schema] of Object.entries(object.properties)) {
properties[key] = properties[key] === undefined ? schema : { [exports.Kind]: 'Union', anyOf: [properties[key], { ...schema }] };
}
}
if (required.size > 0) {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties, required: [...required] });
}
else {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties });
}
}
/** Creates a keyof type */
KeyOf(object, options = {}) {
const items = Object.keys(object.properties).map((key) => this.Create({ ...options, [exports.Kind]: 'Literal', type: 'string', const: key }));
return this.Create({ ...options, [exports.Kind]: 'Union', [exports.Hint]: 'KeyOf', anyOf: items });
}
/** Creates a literal type. */
Literal(value, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Literal', const: value, type: typeof value });
}
/** Creates a never type */
Never(options = {}) {
return this.Create({
...options,
[exports.Kind]: 'Never',
allOf: [
{ type: 'boolean', const: false },
{ type: 'boolean', const: true },
],
});
}
/** Creates a null type */
Null(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Null', type: 'null' });
}
/** Creates a number type */
Number(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Number', type: 'number' });
}
/** Creates an object type with the given properties */
Object(properties, options = {}) {
const property_names = Object.keys(properties);
const optional = property_names.filter((name) => {
const property = properties[name];
const modifier = property[exports.Modifier];
return modifier && (modifier === 'Optional' || modifier === 'ReadonlyOptional');
});
const required = property_names.filter((name) => !optional.includes(name));
if (required.length > 0) {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties, required });
}
else {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties });
}
}
/** Creates a new object whose properties are omitted from the given object */
Omit(schema, keys, options = {}) {
const select = keys[exports.Kind] === 'Union' ? keys.anyOf.map((schema) => schema.const) : keys;
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Omit' };
if (next.required) {
next.required = next.required.filter((key) => !select.includes(key));
if (next.required.length === 0)
delete next.required;
}
for (const key of Object.keys(next.properties)) {
if (select.includes(key))
delete next.properties[key];
}
return this.Create(next);
}
/** Creates a tuple type from this functions parameters */
Parameters(schema, options = {}) {
return exports.Type.Tuple(schema.parameters, { ...options });
}
/** Creates an object type whose properties are all optional */
Partial(schema, options = {}) {
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Partial' };
delete next.required;
for (const key of Object.keys(next.properties)) {
const property = next.properties[key];
const modifer = property[exports.Modifier];
switch (modifer) {
case 'ReadonlyOptional':
property[exports.Modifier] = 'ReadonlyOptional';
break;
case 'Readonly':
property[exports.Modifier] = 'ReadonlyOptional';
break;
case 'Optional':
property[exports.Modifier] = 'Optional';
break;
default:
property[exports.Modifier] = 'Optional';
break;
}
}
return this.Create(next);
}
/** Creates a object whose properties are picked from the given object */
Pick(schema, keys, options = {}) {
const select = keys[exports.Kind] === 'Union' ? keys.anyOf.map((schema) => schema.const) : keys;
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Pick' };
if (next.required) {
next.required = next.required.filter((key) => select.includes(key));
if (next.required.length === 0)
delete next.required;
}
for (const key of Object.keys(next.properties)) {
if (!select.includes(key))
delete next.properties[key];
}
return this.Create(next);
}
/** Creates a promise type. This type cannot be represented in schema. */
Promise(item, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Promise', type: 'promise', item });
}
/** Creates a record type */
Record(key, value, options = {}) {
// If string literal union return TObject with properties extracted from union.
if (key[exports.Kind] === 'Union') {
return this.Object(key.anyOf.reduce((acc, literal) => {
return { ...acc, [literal.const]: value };
}, {}), { ...options, [exports.Hint]: 'Record' });
}
// otherwise return TRecord with patternProperties
const pattern = ['Integer', 'Number'].includes(key[exports.Kind]) ? '^(0|[1-9][0-9]*)$' : key[exports.Kind] === 'String' && key.pattern ? key.pattern : '^.*$';
return this.Create({
...options,
[exports.Kind]: 'Record',
type: 'object',
patternProperties: { [pattern]: value },
additionalProperties: false,
});
}
/** Creates a recursive object type */
Recursive(callback, options = {}) {
if (options.$id === undefined)
options.$id = `T${TypeOrdinal++}`;
const self = callback({ [exports.Kind]: 'Self', $ref: `${options.$id}` });
self.$id = options.$id;
return this.Create({ ...options, ...self });
}
/** Creates a reference schema */
Ref(schema, options = {}) {
if (schema.$id === undefined)
throw Error('TypeBuilder.Ref: Referenced schema must specify an $id');
return this.Create({ ...options, [exports.Kind]: 'Ref', $ref: schema.$id });
}
/** Creates a string type from a regular expression */
RegEx(regex, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'String', type: 'string', pattern: regex.source });
}
/** Creates an object type whose properties are all required */
Required(schema, options = {}) {
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Required' };
next.required = Object.keys(next.properties);
for (const key of Object.keys(next.properties)) {
const property = next.properties[key];
const modifier = property[exports.Modifier];
switch (modifier) {
case 'ReadonlyOptional':
property[exports.Modifier] = 'Readonly';
break;
case 'Readonly':
property[exports.Modifier] = 'Readonly';
break;
case 'Optional':
delete property[exports.Modifier];
break;
default:
delete property[exports.Modifier];
break;
}
}
return this.Create(next);
}
/** Creates a type from this functions return type */
ReturnType(schema, options = {}) {
return { ...options, ...this.Clone(schema.returns) };
}
/** Removes Kind and Modifier symbol property keys from this schema */
Strict(schema) {
return JSON.parse(JSON.stringify(schema));
}
/** Creates a string type */
String(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'String', type: 'string' });
}
/** Creates a tuple type */
Tuple(items, options = {}) {
const additionalItems = false;
const minItems = items.length;
const maxItems = items.length;
const schema = (items.length > 0 ? { ...options, [exports.Kind]: 'Tuple', type: 'array', items, additionalItems, minItems, maxItems } : { ...options, [exports.Kind]: 'Tuple', type: 'array', minItems, maxItems });
return this.Create(schema);
}
/** Creates a undefined type */
Undefined(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Undefined', type: 'object', specialized: 'Undefined' });
}
Union(items, options = {}) {
return items.length === 0 ? exports.Type.Never({ ...options }) : this.Create({ ...options, [exports.Kind]: 'Union', anyOf: items });
}
/** Creates a Uint8Array type */
Uint8Array(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Uint8Array', type: 'object', specialized: 'Uint8Array' });
}
/** Creates an unknown type */
Unknown(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Unknown' });
}
/** Creates a user defined schema that infers as type T */
Unsafe(options = {}) {
return this.Create({ ...options, [exports.Kind]: options[exports.Kind] || 'Unsafe' });
}
/** Creates a void type */
Void(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Void', type: 'null' });
}
/** Use this function to return TSchema with static and params omitted */
Create(schema) {
return schema;
}
/** Clones the given value */
Clone(value) {
const isObject = (object) => typeof object === 'object' && object !== null && !Array.isArray(object);
const isArray = (object) => typeof object === 'object' && object !== null && Array.isArray(object);
if (isObject(value)) {
return Object.keys(value).reduce((acc, key) => ({
...acc,
[key]: this.Clone(value[key]),
}), Object.getOwnPropertySymbols(value).reduce((acc, key) => ({
...acc,
[key]: this.Clone(value[key]),
}), {}));
}
else if (isArray(value)) {
return value.map((item) => this.Clone(item));
}
else {
return value;
}
}
}
exports.TypeBuilder = TypeBuilder;
/** JSON Schema Type Builder with Static Type Resolution for TypeScript */
exports.Type = new TypeBuilder();

View File

@@ -1,26 +1,26 @@
import * as Types from '../typebox';
export declare class ValueCastReferenceTypeError extends Error {
readonly schema: Types.TRef | Types.TSelf;
constructor(schema: Types.TRef | Types.TSelf);
}
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 namespace ValueCast {
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): any;
function Cast<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: any): Types.Static<T>;
}
import * as Types from '../typebox';
export declare class ValueCastReferenceTypeError extends Error {
readonly schema: Types.TRef | Types.TSelf;
constructor(schema: Types.TRef | Types.TSelf);
}
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 namespace ValueCast {
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): any;
function Cast<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: any): Types.Static<T>;
}

View File

@@ -1,364 +1,364 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.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");
var UnionValueCast;
(function (UnionValueCast) {
// ----------------------------------------------------------------------------------------------
// 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.
// ----------------------------------------------------------------------------------------------
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) {
return check_1.ValueCheck.Check(union, references, value) ? clone_1.ValueClone.Clone(value) : ValueCast.Cast(Select(union, references, value), references, value);
}
UnionValueCast.Create = Create;
})(UnionValueCast || (UnionValueCast = {}));
// -----------------------------------------------------------
// 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;
var ValueCast;
(function (ValueCast) {
// -----------------------------------------------------------
// Guards
// -----------------------------------------------------------
function IsArray(value) {
return typeof value === 'object' && globalThis.Array.isArray(value);
}
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';
}
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 === 1n) || (IsString(value) && (value.toLowerCase() === 'true' || value === '1'));
}
function IsValueFalse(value) {
return value === false || (IsNumber(value) && value === 0) || (IsBigInt(value) && value === 0n) || (IsString(value) && (value.toLowerCase() === 'false' || value === '0'));
}
// -----------------------------------------------------------
// Convert
// -----------------------------------------------------------
function TryConvertString(value) {
return IsValueToString(value) ? value.toString() : value;
}
function TryConvertNumber(value) {
return IsStringNumeric(value) ? parseFloat(value) : IsValueTrue(value) ? 1 : value;
}
function TryConvertInteger(value) {
return IsStringNumeric(value) ? parseInt(value) : IsValueTrue(value) ? 1 : value;
}
function TryConvertBoolean(value) {
return IsValueTrue(value) ? true : IsValueFalse(value) ? false : value;
}
// -----------------------------------------------------------
// Cast
// -----------------------------------------------------------
function Any(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? 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 Boolean(schema, references, value) {
const conversion = TryConvertBoolean(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : 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 Enum(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? 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) {
const conversion = TryConvertInteger(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : 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 Null(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Number(schema, references, value) {
const conversion = TryConvertNumber(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references);
}
function Object(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(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 propertyKeys = globalThis.Object.keys(schema.properties);
for (const objectKey of globalThis.Object.keys(value)) {
if (propertyKeys.includes(objectKey))
continue;
result[objectKey] = Visit(schema.additionalProperties, references, value[objectKey]);
}
}
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))
return create_1.ValueCreate.Create(schema, references);
const subschemaKey = globalThis.Object.keys(schema.patternProperties)[0];
const subschema = schema.patternProperties[subschemaKey];
const result = {};
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
result[propKey] = Visit(subschema, references, propValue);
}
return result;
}
function Recursive(schema, references, value) {
throw new ValueCastRecursiveTypeError(schema);
}
function Ref(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new ValueCastReferenceTypeError(schema);
return Visit(reference, references, value);
}
function Self(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new ValueCastReferenceTypeError(schema);
return Visit(reference, references, value);
}
function String(schema, references, value) {
const conversion = TryConvertString(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references);
}
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) ? value : create_1.ValueCreate.Create(schema, references);
}
function Union(schema, references, value) {
return UnionValueCast.Create(schema, references, value);
}
function Uint8Array(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Unknown(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Void(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Visit(schema, references, value) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema;
switch (schema[Types.Kind]) {
case 'Any':
return Any(anySchema, anyReferences, value);
case 'Array':
return Array(anySchema, anyReferences, value);
case 'Boolean':
return Boolean(anySchema, anyReferences, value);
case 'Constructor':
return Constructor(anySchema, anyReferences, value);
case 'Enum':
return Enum(anySchema, anyReferences, value);
case 'Function':
return Function(anySchema, anyReferences, value);
case 'Integer':
return Integer(anySchema, anyReferences, value);
case 'Literal':
return Literal(anySchema, anyReferences, value);
case 'Never':
return Never(anySchema, anyReferences, value);
case 'Null':
return Null(anySchema, anyReferences, value);
case 'Number':
return Number(anySchema, anyReferences, value);
case 'Object':
return Object(anySchema, anyReferences, value);
case 'Promise':
return Promise(anySchema, anyReferences, value);
case 'Record':
return Record(anySchema, anyReferences, value);
case 'Rec':
return Recursive(anySchema, anyReferences, value);
case 'Ref':
return Ref(anySchema, anyReferences, value);
case 'Self':
return Self(anySchema, anyReferences, value);
case 'String':
return String(anySchema, anyReferences, value);
case 'Tuple':
return Tuple(anySchema, anyReferences, value);
case 'Undefined':
return Undefined(anySchema, anyReferences, value);
case 'Union':
return Union(anySchema, anyReferences, value);
case 'Uint8Array':
return Uint8Array(anySchema, anyReferences, value);
case 'Unknown':
return Unknown(anySchema, anyReferences, value);
case 'Void':
return Void(anySchema, anyReferences, value);
default:
throw new ValueCastUnknownTypeError(anySchema);
}
}
ValueCast.Visit = Visit;
function Cast(schema, references, value) {
return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value);
}
ValueCast.Cast = Cast;
})(ValueCast = exports.ValueCast || (exports.ValueCast = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.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");
var UnionValueCast;
(function (UnionValueCast) {
// ----------------------------------------------------------------------------------------------
// 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.
// ----------------------------------------------------------------------------------------------
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) {
return check_1.ValueCheck.Check(union, references, value) ? clone_1.ValueClone.Clone(value) : ValueCast.Cast(Select(union, references, value), references, value);
}
UnionValueCast.Create = Create;
})(UnionValueCast || (UnionValueCast = {}));
// -----------------------------------------------------------
// 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;
var ValueCast;
(function (ValueCast) {
// -----------------------------------------------------------
// Guards
// -----------------------------------------------------------
function IsArray(value) {
return typeof value === 'object' && globalThis.Array.isArray(value);
}
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';
}
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 === 1n) || (IsString(value) && (value.toLowerCase() === 'true' || value === '1'));
}
function IsValueFalse(value) {
return value === false || (IsNumber(value) && value === 0) || (IsBigInt(value) && value === 0n) || (IsString(value) && (value.toLowerCase() === 'false' || value === '0'));
}
// -----------------------------------------------------------
// Convert
// -----------------------------------------------------------
function TryConvertString(value) {
return IsValueToString(value) ? value.toString() : value;
}
function TryConvertNumber(value) {
return IsStringNumeric(value) ? parseFloat(value) : IsValueTrue(value) ? 1 : value;
}
function TryConvertInteger(value) {
return IsStringNumeric(value) ? parseInt(value) : IsValueTrue(value) ? 1 : value;
}
function TryConvertBoolean(value) {
return IsValueTrue(value) ? true : IsValueFalse(value) ? false : value;
}
// -----------------------------------------------------------
// Cast
// -----------------------------------------------------------
function Any(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? 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 Boolean(schema, references, value) {
const conversion = TryConvertBoolean(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : 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 Enum(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? 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) {
const conversion = TryConvertInteger(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : 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 Null(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Number(schema, references, value) {
const conversion = TryConvertNumber(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references);
}
function Object(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(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 propertyKeys = globalThis.Object.keys(schema.properties);
for (const objectKey of globalThis.Object.keys(value)) {
if (propertyKeys.includes(objectKey))
continue;
result[objectKey] = Visit(schema.additionalProperties, references, value[objectKey]);
}
}
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))
return create_1.ValueCreate.Create(schema, references);
const subschemaKey = globalThis.Object.keys(schema.patternProperties)[0];
const subschema = schema.patternProperties[subschemaKey];
const result = {};
for (const [propKey, propValue] of globalThis.Object.entries(value)) {
result[propKey] = Visit(subschema, references, propValue);
}
return result;
}
function Recursive(schema, references, value) {
throw new ValueCastRecursiveTypeError(schema);
}
function Ref(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new ValueCastReferenceTypeError(schema);
return Visit(reference, references, value);
}
function Self(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new ValueCastReferenceTypeError(schema);
return Visit(reference, references, value);
}
function String(schema, references, value) {
const conversion = TryConvertString(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references);
}
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) ? value : create_1.ValueCreate.Create(schema, references);
}
function Union(schema, references, value) {
return UnionValueCast.Create(schema, references, value);
}
function Uint8Array(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Unknown(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Void(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
}
function Visit(schema, references, value) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema;
switch (schema[Types.Kind]) {
case 'Any':
return Any(anySchema, anyReferences, value);
case 'Array':
return Array(anySchema, anyReferences, value);
case 'Boolean':
return Boolean(anySchema, anyReferences, value);
case 'Constructor':
return Constructor(anySchema, anyReferences, value);
case 'Enum':
return Enum(anySchema, anyReferences, value);
case 'Function':
return Function(anySchema, anyReferences, value);
case 'Integer':
return Integer(anySchema, anyReferences, value);
case 'Literal':
return Literal(anySchema, anyReferences, value);
case 'Never':
return Never(anySchema, anyReferences, value);
case 'Null':
return Null(anySchema, anyReferences, value);
case 'Number':
return Number(anySchema, anyReferences, value);
case 'Object':
return Object(anySchema, anyReferences, value);
case 'Promise':
return Promise(anySchema, anyReferences, value);
case 'Record':
return Record(anySchema, anyReferences, value);
case 'Rec':
return Recursive(anySchema, anyReferences, value);
case 'Ref':
return Ref(anySchema, anyReferences, value);
case 'Self':
return Self(anySchema, anyReferences, value);
case 'String':
return String(anySchema, anyReferences, value);
case 'Tuple':
return Tuple(anySchema, anyReferences, value);
case 'Undefined':
return Undefined(anySchema, anyReferences, value);
case 'Union':
return Union(anySchema, anyReferences, value);
case 'Uint8Array':
return Uint8Array(anySchema, anyReferences, value);
case 'Unknown':
return Unknown(anySchema, anyReferences, value);
case 'Void':
return Void(anySchema, anyReferences, value);
default:
throw new ValueCastUnknownTypeError(anySchema);
}
}
ValueCast.Visit = Visit;
function Cast(schema, references, value) {
return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value);
}
ValueCast.Cast = Cast;
})(ValueCast = exports.ValueCast || (exports.ValueCast = {}));

View File

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

View File

@@ -1,331 +1,331 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.ValueCheckUnknownTypeError = void 0;
const Types = require("../typebox");
const format_1 = require("../format");
class ValueCheckUnknownTypeError extends Error {
constructor(schema) {
super('ValueCheck: Unknown type');
this.schema = schema;
}
}
exports.ValueCheckUnknownTypeError = ValueCheckUnknownTypeError;
var ValueCheck;
(function (ValueCheck) {
function Any(schema, references, value) {
return true;
}
function Array(schema, references, value) {
if (!globalThis.Array.isArray(value)) {
return false;
}
if (schema.minItems !== undefined && !(value.length >= schema.minItems)) {
return false;
}
if (schema.maxItems !== undefined && !(value.length <= schema.maxItems)) {
return false;
}
if (schema.uniqueItems === true && !(new Set(value).size === value.length)) {
return false;
}
return value.every((val) => Visit(schema.items, references, val));
}
function Boolean(schema, references, value) {
return typeof value === 'boolean';
}
function Constructor(schema, references, value) {
return Visit(schema.returns, references, value.prototype);
}
function Function(schema, references, value) {
return typeof value === 'function';
}
function Integer(schema, references, value) {
if (!(typeof value === 'number')) {
return false;
}
if (!globalThis.Number.isInteger(value)) {
return false;
}
if (schema.multipleOf !== undefined && !(value % schema.multipleOf === 0)) {
return false;
}
if (schema.exclusiveMinimum !== undefined && !(value > schema.exclusiveMinimum)) {
return false;
}
if (schema.exclusiveMaximum !== undefined && !(value < schema.exclusiveMaximum)) {
return false;
}
if (schema.minimum !== undefined && !(value >= schema.minimum)) {
return false;
}
if (schema.maximum !== undefined && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Literal(schema, references, value) {
return value === schema.const;
}
function Never(schema, references, value) {
return false;
}
function Null(schema, references, value) {
return value === null;
}
function Number(schema, references, value) {
if (!(typeof value === 'number')) {
return false;
}
if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
return false;
}
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
return false;
}
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
return false;
}
if (schema.minimum && !(value >= schema.minimum)) {
return false;
}
if (schema.maximum && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Object(schema, references, value) {
if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return false;
}
if (schema.minProperties !== undefined && !(globalThis.Object.keys(value).length >= schema.minProperties)) {
return false;
}
if (schema.maxProperties !== undefined && !(globalThis.Object.keys(value).length <= schema.maxProperties)) {
return false;
}
const propertyKeys = globalThis.Object.keys(schema.properties);
if (schema.additionalProperties === false) {
// optimization: If the property key length matches the required keys length
// then we only need check that the values property key length matches that
// of the property key length. This is because exhaustive testing for values
// will occur in subsequent property tests.
if (schema.required && schema.required.length === propertyKeys.length && !(globalThis.Object.keys(value).length === propertyKeys.length)) {
return false;
}
else {
if (!globalThis.Object.keys(value).every((key) => propertyKeys.includes(key))) {
return false;
}
}
}
if (typeof schema.additionalProperties === 'object') {
for (const objectKey of globalThis.Object.keys(value)) {
if (propertyKeys.includes(objectKey))
continue;
if (!Visit(schema.additionalProperties, references, value[objectKey])) {
return false;
}
}
}
for (const propertyKey of propertyKeys) {
const propertySchema = schema.properties[propertyKey];
if (schema.required && schema.required.includes(propertyKey)) {
if (!Visit(propertySchema, references, value[propertyKey])) {
return false;
}
}
else {
if (value[propertyKey] !== undefined) {
if (!Visit(propertySchema, references, value[propertyKey])) {
return false;
}
}
}
}
return true;
}
function Promise(schema, references, value) {
return typeof value === 'object' && typeof value.then === 'function';
}
function Record(schema, references, value) {
if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return false;
}
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern);
if (!globalThis.Object.keys(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 reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueCheck.Ref: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references, value);
}
function Self(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueCheck.Self: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references, value);
}
function String(schema, references, value) {
if (!(typeof value === 'string')) {
return false;
}
if (schema.minLength !== undefined) {
if (!(value.length >= schema.minLength))
return false;
}
if (schema.maxLength !== undefined) {
if (!(value.length <= schema.maxLength))
return false;
}
if (schema.pattern !== undefined) {
const regex = new RegExp(schema.pattern);
if (!regex.test(value))
return false;
}
if (schema.format !== undefined) {
if (!format_1.Format.Has(schema.format))
return false;
const func = format_1.Format.Get(schema.format);
return func(value);
}
return true;
}
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 (schema.maxByteLength && !(value.length <= schema.maxByteLength)) {
return false;
}
if (schema.minByteLength && !(value.length >= schema.minByteLength)) {
return false;
}
return true;
}
function Unknown(schema, references, value) {
return true;
}
function Void(schema, references, value) {
return value === null;
}
function Visit(schema, references, value) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema;
switch (anySchema[Types.Kind]) {
case 'Any':
return Any(anySchema, anyReferences, value);
case 'Array':
return Array(anySchema, anyReferences, value);
case 'Boolean':
return Boolean(anySchema, anyReferences, value);
case 'Constructor':
return Constructor(anySchema, anyReferences, value);
case 'Function':
return Function(anySchema, anyReferences, value);
case 'Integer':
return Integer(anySchema, anyReferences, value);
case 'Literal':
return Literal(anySchema, anyReferences, value);
case 'Never':
return Never(anySchema, anyReferences, value);
case 'Null':
return Null(anySchema, anyReferences, value);
case 'Number':
return Number(anySchema, anyReferences, value);
case 'Object':
return Object(anySchema, anyReferences, value);
case 'Promise':
return Promise(anySchema, anyReferences, value);
case 'Record':
return Record(anySchema, anyReferences, value);
case 'Ref':
return Ref(anySchema, anyReferences, value);
case 'Self':
return Self(anySchema, anyReferences, value);
case 'String':
return String(anySchema, anyReferences, value);
case 'Tuple':
return Tuple(anySchema, anyReferences, value);
case 'Undefined':
return Undefined(anySchema, anyReferences, value);
case 'Union':
return Union(anySchema, anyReferences, value);
case 'Uint8Array':
return Uint8Array(anySchema, anyReferences, value);
case 'Unknown':
return Unknown(anySchema, anyReferences, value);
case 'Void':
return Void(anySchema, anyReferences, value);
default:
throw new ValueCheckUnknownTypeError(anySchema);
}
}
// -------------------------------------------------------------------------
// Check
// -------------------------------------------------------------------------
function Check(schema, references, value) {
return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value);
}
ValueCheck.Check = Check;
})(ValueCheck = exports.ValueCheck || (exports.ValueCheck = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.ValueCheckUnknownTypeError = void 0;
const Types = require("../typebox");
const format_1 = require("../format");
class ValueCheckUnknownTypeError extends Error {
constructor(schema) {
super('ValueCheck: Unknown type');
this.schema = schema;
}
}
exports.ValueCheckUnknownTypeError = ValueCheckUnknownTypeError;
var ValueCheck;
(function (ValueCheck) {
function Any(schema, references, value) {
return true;
}
function Array(schema, references, value) {
if (!globalThis.Array.isArray(value)) {
return false;
}
if (schema.minItems !== undefined && !(value.length >= schema.minItems)) {
return false;
}
if (schema.maxItems !== undefined && !(value.length <= schema.maxItems)) {
return false;
}
if (schema.uniqueItems === true && !(new Set(value).size === value.length)) {
return false;
}
return value.every((val) => Visit(schema.items, references, val));
}
function Boolean(schema, references, value) {
return typeof value === 'boolean';
}
function Constructor(schema, references, value) {
return Visit(schema.returns, references, value.prototype);
}
function Function(schema, references, value) {
return typeof value === 'function';
}
function Integer(schema, references, value) {
if (!(typeof value === 'number')) {
return false;
}
if (!globalThis.Number.isInteger(value)) {
return false;
}
if (schema.multipleOf !== undefined && !(value % schema.multipleOf === 0)) {
return false;
}
if (schema.exclusiveMinimum !== undefined && !(value > schema.exclusiveMinimum)) {
return false;
}
if (schema.exclusiveMaximum !== undefined && !(value < schema.exclusiveMaximum)) {
return false;
}
if (schema.minimum !== undefined && !(value >= schema.minimum)) {
return false;
}
if (schema.maximum !== undefined && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Literal(schema, references, value) {
return value === schema.const;
}
function Never(schema, references, value) {
return false;
}
function Null(schema, references, value) {
return value === null;
}
function Number(schema, references, value) {
if (!(typeof value === 'number')) {
return false;
}
if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
return false;
}
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
return false;
}
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
return false;
}
if (schema.minimum && !(value >= schema.minimum)) {
return false;
}
if (schema.maximum && !(value <= schema.maximum)) {
return false;
}
return true;
}
function Object(schema, references, value) {
if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return false;
}
if (schema.minProperties !== undefined && !(globalThis.Object.keys(value).length >= schema.minProperties)) {
return false;
}
if (schema.maxProperties !== undefined && !(globalThis.Object.keys(value).length <= schema.maxProperties)) {
return false;
}
const propertyKeys = globalThis.Object.keys(schema.properties);
if (schema.additionalProperties === false) {
// optimization: If the property key length matches the required keys length
// then we only need check that the values property key length matches that
// of the property key length. This is because exhaustive testing for values
// will occur in subsequent property tests.
if (schema.required && schema.required.length === propertyKeys.length && !(globalThis.Object.keys(value).length === propertyKeys.length)) {
return false;
}
else {
if (!globalThis.Object.keys(value).every((key) => propertyKeys.includes(key))) {
return false;
}
}
}
if (typeof schema.additionalProperties === 'object') {
for (const objectKey of globalThis.Object.keys(value)) {
if (propertyKeys.includes(objectKey))
continue;
if (!Visit(schema.additionalProperties, references, value[objectKey])) {
return false;
}
}
}
for (const propertyKey of propertyKeys) {
const propertySchema = schema.properties[propertyKey];
if (schema.required && schema.required.includes(propertyKey)) {
if (!Visit(propertySchema, references, value[propertyKey])) {
return false;
}
}
else {
if (value[propertyKey] !== undefined) {
if (!Visit(propertySchema, references, value[propertyKey])) {
return false;
}
}
}
}
return true;
}
function Promise(schema, references, value) {
return typeof value === 'object' && typeof value.then === 'function';
}
function Record(schema, references, value) {
if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return false;
}
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern);
if (!globalThis.Object.keys(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 reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueCheck.Ref: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references, value);
}
function Self(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueCheck.Self: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references, value);
}
function String(schema, references, value) {
if (!(typeof value === 'string')) {
return false;
}
if (schema.minLength !== undefined) {
if (!(value.length >= schema.minLength))
return false;
}
if (schema.maxLength !== undefined) {
if (!(value.length <= schema.maxLength))
return false;
}
if (schema.pattern !== undefined) {
const regex = new RegExp(schema.pattern);
if (!regex.test(value))
return false;
}
if (schema.format !== undefined) {
if (!format_1.Format.Has(schema.format))
return false;
const func = format_1.Format.Get(schema.format);
return func(value);
}
return true;
}
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 (schema.maxByteLength && !(value.length <= schema.maxByteLength)) {
return false;
}
if (schema.minByteLength && !(value.length >= schema.minByteLength)) {
return false;
}
return true;
}
function Unknown(schema, references, value) {
return true;
}
function Void(schema, references, value) {
return value === null;
}
function Visit(schema, references, value) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema;
switch (anySchema[Types.Kind]) {
case 'Any':
return Any(anySchema, anyReferences, value);
case 'Array':
return Array(anySchema, anyReferences, value);
case 'Boolean':
return Boolean(anySchema, anyReferences, value);
case 'Constructor':
return Constructor(anySchema, anyReferences, value);
case 'Function':
return Function(anySchema, anyReferences, value);
case 'Integer':
return Integer(anySchema, anyReferences, value);
case 'Literal':
return Literal(anySchema, anyReferences, value);
case 'Never':
return Never(anySchema, anyReferences, value);
case 'Null':
return Null(anySchema, anyReferences, value);
case 'Number':
return Number(anySchema, anyReferences, value);
case 'Object':
return Object(anySchema, anyReferences, value);
case 'Promise':
return Promise(anySchema, anyReferences, value);
case 'Record':
return Record(anySchema, anyReferences, value);
case 'Ref':
return Ref(anySchema, anyReferences, value);
case 'Self':
return Self(anySchema, anyReferences, value);
case 'String':
return String(anySchema, anyReferences, value);
case 'Tuple':
return Tuple(anySchema, anyReferences, value);
case 'Undefined':
return Undefined(anySchema, anyReferences, value);
case 'Union':
return Union(anySchema, anyReferences, value);
case 'Uint8Array':
return Uint8Array(anySchema, anyReferences, value);
case 'Unknown':
return Unknown(anySchema, anyReferences, value);
case 'Void':
return Void(anySchema, anyReferences, value);
default:
throw new ValueCheckUnknownTypeError(anySchema);
}
}
// -------------------------------------------------------------------------
// Check
// -------------------------------------------------------------------------
function Check(schema, references, value) {
return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value);
}
ValueCheck.Check = Check;
})(ValueCheck = exports.ValueCheck || (exports.ValueCheck = {}));

View File

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

View File

@@ -1,65 +1,65 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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 Object(value) {
const keys = [...globalThis.Object.keys(value), ...globalThis.Object.getOwnPropertySymbols(value)];
return keys.reduce((acc, key) => ({ ...acc, [key]: Clone(value[key]) }), {});
}
function Array(value) {
return value.map((element) => Clone(element));
}
function TypedArray(value) {
return value.slice();
}
function Value(value) {
return value;
}
function Clone(value) {
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 = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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 Object(value) {
const keys = [...globalThis.Object.keys(value), ...globalThis.Object.getOwnPropertySymbols(value)];
return keys.reduce((acc, key) => ({ ...acc, [key]: Clone(value[key]) }), {});
}
function Array(value) {
return value.map((element) => Clone(element));
}
function TypedArray(value) {
return value.slice();
}
function Value(value) {
return value;
}
function Clone(value) {
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

@@ -1,14 +1,14 @@
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 namespace ValueCreate {
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit<T extends Types.TSchema>(schema: T, references: Types.TSchema[]): Types.Static<T>;
function Create<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R]): Types.Static<T>;
}
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 namespace ValueCreate {
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit<T extends Types.TSchema>(schema: T, references: Types.TSchema[]): Types.Static<T>;
function Create<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R]): Types.Static<T>;
}

View File

@@ -1,357 +1,357 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.ValueCreateNeverTypeError = exports.ValueCreateUnknownTypeError = void 0;
const Types = require("../typebox");
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;
var ValueCreate;
(function (ValueCreate) {
function Any(schema, references) {
if (schema.default !== undefined) {
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 (schema.default !== undefined) {
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 Boolean(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
return false;
}
}
function Constructor(schema, references) {
if (schema.default !== undefined) {
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 Enum(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else if (schema.anyOf.length === 0) {
throw new Error('ValueCreate.Enum: Cannot create default enum value as this enum has no items');
}
else {
return schema.anyOf[0].const;
}
}
function Function(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
return () => ValueCreate.Create(schema.returns, references);
}
}
function Integer(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else if (schema.minimum !== undefined) {
return schema.minimum;
}
else {
return 0;
}
}
function Literal(schema, references) {
return schema.const;
}
function Never(schema, references) {
throw new ValueCreateNeverTypeError(schema);
}
function Null(schema, references) {
return null;
}
function Number(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else if (schema.minimum !== undefined) {
return schema.minimum;
}
else {
return 0;
}
}
function Object(schema, references) {
if (schema.default !== undefined) {
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 (schema.default !== undefined) {
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 (schema.default !== undefined) {
return schema.default;
}
else if (!(keyPattern === '^.*$' || keyPattern === '^(0|[1-9][0-9]*)$')) {
const propertyKeys = keyPattern.slice(1, keyPattern.length - 1).split('|');
return propertyKeys.reduce((acc, key) => {
return { ...acc, [key]: Create(valueSchema, references) };
}, {});
}
else {
return {};
}
}
function Recursive(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
throw new Error('ValueCreate.Recursive: Recursive types require a default value');
}
}
function Ref(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueCreate.Ref: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references);
}
}
function Self(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueCreate.Self: Cannot locate schema with $id '${schema.$ref}'`);
return Visit(reference, references);
}
}
function String(schema, references) {
if (schema.pattern !== undefined) {
if (schema.default === undefined) {
throw new Error('ValueCreate.String: String types with patterns must specify a default value');
}
else {
return schema.default;
}
}
else if (schema.format !== undefined) {
if (schema.default === undefined) {
throw new Error('ValueCreate.String: String types with formats must specify a default value');
}
else {
return schema.default;
}
}
else {
if (schema.default !== undefined) {
return schema.default;
}
else if (schema.minLength !== undefined) {
return globalThis.Array.from({ length: schema.minLength })
.map(() => '.')
.join('');
}
else {
return '';
}
}
}
function Tuple(schema, references) {
if (schema.default !== undefined) {
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) {
return undefined;
}
function Union(schema, references) {
if (schema.default !== undefined) {
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 (schema.default !== undefined) {
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 (schema.default !== undefined) {
return schema.default;
}
else {
return {};
}
}
function Void(schema, references) {
return null;
}
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit(schema, references) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema;
switch (anySchema[Types.Kind]) {
case 'Any':
return Any(anySchema, anyReferences);
case 'Array':
return Array(anySchema, anyReferences);
case 'Boolean':
return Boolean(anySchema, anyReferences);
case 'Constructor':
return Constructor(anySchema, anyReferences);
case 'Enum':
return Enum(anySchema, anyReferences);
case 'Function':
return Function(anySchema, anyReferences);
case 'Integer':
return Integer(anySchema, anyReferences);
case 'Literal':
return Literal(anySchema, anyReferences);
case 'Never':
return Never(anySchema, anyReferences);
case 'Null':
return Null(anySchema, anyReferences);
case 'Number':
return Number(anySchema, anyReferences);
case 'Object':
return Object(anySchema, anyReferences);
case 'Promise':
return Promise(anySchema, anyReferences);
case 'Record':
return Record(anySchema, anyReferences);
case 'Rec':
return Recursive(anySchema, anyReferences);
case 'Ref':
return Ref(anySchema, anyReferences);
case 'Self':
return Self(anySchema, anyReferences);
case 'String':
return String(anySchema, anyReferences);
case 'Tuple':
return Tuple(anySchema, anyReferences);
case 'Undefined':
return Undefined(anySchema, anyReferences);
case 'Union':
return Union(anySchema, anyReferences);
case 'Uint8Array':
return Uint8Array(anySchema, anyReferences);
case 'Unknown':
return Unknown(anySchema, anyReferences);
case 'Void':
return Void(anySchema, anyReferences);
default:
throw new ValueCreateUnknownTypeError(anySchema);
}
}
ValueCreate.Visit = Visit;
function Create(schema, references) {
return Visit(schema, references);
}
ValueCreate.Create = Create;
})(ValueCreate = exports.ValueCreate || (exports.ValueCreate = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.ValueCreateNeverTypeError = exports.ValueCreateUnknownTypeError = void 0;
const Types = require("../typebox");
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;
var ValueCreate;
(function (ValueCreate) {
function Any(schema, references) {
if (schema.default !== undefined) {
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 (schema.default !== undefined) {
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 Boolean(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
return false;
}
}
function Constructor(schema, references) {
if (schema.default !== undefined) {
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 Enum(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else if (schema.anyOf.length === 0) {
throw new Error('ValueCreate.Enum: Cannot create default enum value as this enum has no items');
}
else {
return schema.anyOf[0].const;
}
}
function Function(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
return () => ValueCreate.Create(schema.returns, references);
}
}
function Integer(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else if (schema.minimum !== undefined) {
return schema.minimum;
}
else {
return 0;
}
}
function Literal(schema, references) {
return schema.const;
}
function Never(schema, references) {
throw new ValueCreateNeverTypeError(schema);
}
function Null(schema, references) {
return null;
}
function Number(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else if (schema.minimum !== undefined) {
return schema.minimum;
}
else {
return 0;
}
}
function Object(schema, references) {
if (schema.default !== undefined) {
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 (schema.default !== undefined) {
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 (schema.default !== undefined) {
return schema.default;
}
else if (!(keyPattern === '^.*$' || keyPattern === '^(0|[1-9][0-9]*)$')) {
const propertyKeys = keyPattern.slice(1, keyPattern.length - 1).split('|');
return propertyKeys.reduce((acc, key) => {
return { ...acc, [key]: Create(valueSchema, references) };
}, {});
}
else {
return {};
}
}
function Recursive(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
throw new Error('ValueCreate.Recursive: Recursive types require a default value');
}
}
function Ref(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueCreate.Ref: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references);
}
}
function Self(schema, references) {
if (schema.default !== undefined) {
return schema.default;
}
else {
const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined)
throw new Error(`ValueCreate.Self: Cannot locate schema with $id '${schema.$ref}'`);
return Visit(reference, references);
}
}
function String(schema, references) {
if (schema.pattern !== undefined) {
if (schema.default === undefined) {
throw new Error('ValueCreate.String: String types with patterns must specify a default value');
}
else {
return schema.default;
}
}
else if (schema.format !== undefined) {
if (schema.default === undefined) {
throw new Error('ValueCreate.String: String types with formats must specify a default value');
}
else {
return schema.default;
}
}
else {
if (schema.default !== undefined) {
return schema.default;
}
else if (schema.minLength !== undefined) {
return globalThis.Array.from({ length: schema.minLength })
.map(() => '.')
.join('');
}
else {
return '';
}
}
}
function Tuple(schema, references) {
if (schema.default !== undefined) {
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) {
return undefined;
}
function Union(schema, references) {
if (schema.default !== undefined) {
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 (schema.default !== undefined) {
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 (schema.default !== undefined) {
return schema.default;
}
else {
return {};
}
}
function Void(schema, references) {
return null;
}
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit(schema, references) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema;
switch (anySchema[Types.Kind]) {
case 'Any':
return Any(anySchema, anyReferences);
case 'Array':
return Array(anySchema, anyReferences);
case 'Boolean':
return Boolean(anySchema, anyReferences);
case 'Constructor':
return Constructor(anySchema, anyReferences);
case 'Enum':
return Enum(anySchema, anyReferences);
case 'Function':
return Function(anySchema, anyReferences);
case 'Integer':
return Integer(anySchema, anyReferences);
case 'Literal':
return Literal(anySchema, anyReferences);
case 'Never':
return Never(anySchema, anyReferences);
case 'Null':
return Null(anySchema, anyReferences);
case 'Number':
return Number(anySchema, anyReferences);
case 'Object':
return Object(anySchema, anyReferences);
case 'Promise':
return Promise(anySchema, anyReferences);
case 'Record':
return Record(anySchema, anyReferences);
case 'Rec':
return Recursive(anySchema, anyReferences);
case 'Ref':
return Ref(anySchema, anyReferences);
case 'Self':
return Self(anySchema, anyReferences);
case 'String':
return String(anySchema, anyReferences);
case 'Tuple':
return Tuple(anySchema, anyReferences);
case 'Undefined':
return Undefined(anySchema, anyReferences);
case 'Union':
return Union(anySchema, anyReferences);
case 'Uint8Array':
return Uint8Array(anySchema, anyReferences);
case 'Unknown':
return Unknown(anySchema, anyReferences);
case 'Void':
return Void(anySchema, anyReferences);
default:
throw new ValueCreateUnknownTypeError(anySchema);
}
}
ValueCreate.Visit = Visit;
function Create(schema, references) {
return Visit(schema, references);
}
ValueCreate.Create = Create;
})(ValueCreate = exports.ValueCreate || (exports.ValueCreate = {}));

View File

@@ -1,22 +1,22 @@
export declare type Edit<T = unknown> = Insert<T> | Update<T> | Delete<T>;
export interface Insert<T> {
brand: T;
type: 'insert';
path: string;
value: any;
}
export interface Update<T> {
brand: T;
type: 'update';
path: string;
value: any;
}
export interface Delete<T> {
brand: T;
type: 'delete';
path: string;
}
export declare namespace ValueDelta {
function Diff<T>(current: T, next: T): Edit<T>[];
function Patch<T>(current: T, edits: Edit<T>[]): T;
}
export declare type Edit<T = unknown> = Insert<T> | Update<T> | Delete<T>;
export interface Insert<T> {
brand: T;
type: 'insert';
path: string;
value: any;
}
export interface Update<T> {
brand: T;
type: 'update';
path: string;
value: any;
}
export interface Delete<T> {
brand: T;
type: 'delete';
path: string;
}
export declare namespace ValueDelta {
function Diff<T>(current: T, next: T): Edit<T>[];
function Patch<T>(current: T, edits: Edit<T>[]): T;
}

View File

@@ -1,168 +1,168 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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 = void 0;
const is_1 = require("./is");
const clone_1 = require("./clone");
const pointer_1 = require("./pointer");
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 Error('ValueDelta: Cannot produce diff symbol keys');
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 Error('ValueDelta: Cannot produce diff symbol keys');
yield* Visit(`${path}/${String(key)}`, current[key], next[key]);
}
for (const key of nextKeys) {
if (typeof key === 'symbol')
throw Error('ValueDelta: Cannot produce diff symbol keys');
if (current[key] === undefined)
yield Insert(`${path}/${String(key)}`, next[key]);
}
for (const key of currentKeys.reverse()) {
if (typeof key === 'symbol')
throw Error('ValueDelta: Cannot produce diff symbol keys');
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 Error('ValueDelta: Cannot produce edits for value');
}
}
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 = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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 = void 0;
const is_1 = require("./is");
const clone_1 = require("./clone");
const pointer_1 = require("./pointer");
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 Error('ValueDelta: Cannot produce diff symbol keys');
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 Error('ValueDelta: Cannot produce diff symbol keys');
yield* Visit(`${path}/${String(key)}`, current[key], next[key]);
}
for (const key of nextKeys) {
if (typeof key === 'symbol')
throw Error('ValueDelta: Cannot produce diff symbol keys');
if (current[key] === undefined)
yield Insert(`${path}/${String(key)}`, next[key]);
}
for (const key of currentKeys.reverse()) {
if (typeof key === 'symbol')
throw Error('ValueDelta: Cannot produce diff symbol keys');
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 Error('ValueDelta: Cannot produce edits for value');
}
}
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

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

View File

@@ -1,74 +1,74 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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 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.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 = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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 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.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 = {}));

View File

@@ -1,3 +1,3 @@
export { ValueError, ValueErrorType } from '../errors/index';
export * from './pointer';
export * from './value';
export { ValueError, ValueErrorType } from '../errors/index';
export * from './pointer';
export * from './value';

View File

@@ -1,48 +1,48 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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("./pointer"), exports);
__exportStar(require("./value"), exports);
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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("./pointer"), exports);
__exportStar(require("./value"), exports);

View File

@@ -1,10 +1,10 @@
export declare type ValueType = null | undefined | Function | symbol | bigint | number | boolean | string;
export declare type ObjectType = Record<string | number | symbol, unknown>;
export declare type TypedArrayType = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
export declare type ArrayType = unknown[];
export declare namespace Is {
function Object(value: unknown): value is ObjectType;
function Array(value: unknown): value is ArrayType;
function Value(value: unknown): value is ValueType;
function TypedArray(value: unknown): value is TypedArrayType;
}
export declare type ValueType = null | undefined | Function | symbol | bigint | number | boolean | string;
export declare type ObjectType = Record<string | number | symbol, unknown>;
export declare type TypedArrayType = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
export declare type ArrayType = unknown[];
export declare namespace Is {
function Object(value: unknown): value is ObjectType;
function Array(value: unknown): value is ArrayType;
function Value(value: unknown): value is ValueType;
function TypedArray(value: unknown): value is TypedArrayType;
}

View File

@@ -1,49 +1,49 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.Is = void 0;
var Is;
(function (Is) {
function Object(value) {
return value !== null && typeof value === 'object' && !globalThis.Array.isArray(value) && !ArrayBuffer.isView(value);
}
Is.Object = Object;
function Array(value) {
return globalThis.Array.isArray(value) && !ArrayBuffer.isView(value);
}
Is.Array = Array;
function Value(value) {
return value === null || value === undefined || typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string';
}
Is.Value = Value;
function TypedArray(value) {
return ArrayBuffer.isView(value);
}
Is.TypedArray = TypedArray;
})(Is = exports.Is || (exports.Is = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.Is = void 0;
var Is;
(function (Is) {
function Object(value) {
return value !== null && typeof value === 'object' && !globalThis.Array.isArray(value) && !ArrayBuffer.isView(value);
}
Is.Object = Object;
function Array(value) {
return globalThis.Array.isArray(value) && !ArrayBuffer.isView(value);
}
Is.Array = Array;
function Value(value) {
return value === null || value === undefined || typeof value === 'function' || typeof value === 'symbol' || typeof value === 'bigint' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'string';
}
Is.Value = Value;
function TypedArray(value) {
return ArrayBuffer.isView(value);
}
Is.TypedArray = TypedArray;
})(Is = exports.Is || (exports.Is = {}));

View File

@@ -1,24 +1,24 @@
export declare class ValuePointerRootSetError extends Error {
readonly value: unknown;
readonly path: string;
readonly update: unknown;
constructor(value: unknown, path: string, update: unknown);
}
export declare class ValuePointerRootDeleteError extends Error {
readonly value: unknown;
readonly path: string;
constructor(value: unknown, path: string);
}
/** ValuePointer performs mutable operations on values using RFC6901 Json Pointers */
export declare namespace ValuePointer {
/** Formats the given pointer into navigable key components */
function Format(pointer: string): IterableIterator<string>;
/** Sets the value at the given pointer. If the value at the pointer does not exist it is created */
function Set(value: any, pointer: string, update: unknown): void;
/** Deletes a value at the given pointer */
function Delete(value: any, pointer: string): void;
/** Returns true if a value exists at the given pointer */
function Has(value: any, pointer: string): boolean;
/** Gets the value at the given pointer */
function Get(value: any, pointer: string): any;
}
export declare class ValuePointerRootSetError extends Error {
readonly value: unknown;
readonly path: string;
readonly update: unknown;
constructor(value: unknown, path: string, update: unknown);
}
export declare class ValuePointerRootDeleteError extends Error {
readonly value: unknown;
readonly path: string;
constructor(value: unknown, path: string);
}
/** ValuePointer performs mutable operations on values using RFC6901 Json Pointers */
export declare namespace ValuePointer {
/** Formats the given pointer into navigable key components */
function Format(pointer: string): IterableIterator<string>;
/** Sets the value at the given pointer. If the value at the pointer does not exist it is created */
function Set(value: any, pointer: string, update: unknown): void;
/** Deletes a value at the given pointer */
function Delete(value: any, pointer: string): void;
/** Returns true if a value exists at the given pointer */
function Has(value: any, pointer: string): boolean;
/** Gets the value at the given pointer */
function Get(value: any, pointer: string): any;
}

View File

@@ -1,142 +1,142 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.ValuePointer = exports.ValuePointerRootDeleteError = exports.ValuePointerRootSetError = void 0;
class ValuePointerRootSetError extends Error {
constructor(value, path, update) {
super('ValuePointer: Cannot set root value');
this.value = value;
this.path = path;
this.update = update;
}
}
exports.ValuePointerRootSetError = ValuePointerRootSetError;
class ValuePointerRootDeleteError extends Error {
constructor(value, path) {
super('ValuePointer: Cannot delete root value');
this.value = value;
this.path = path;
}
}
exports.ValuePointerRootDeleteError = ValuePointerRootDeleteError;
/** ValuePointer performs mutable operations on values using RFC6901 Json Pointers */
var ValuePointer;
(function (ValuePointer) {
function Escape(component) {
return component.indexOf('~') === -1 ? component : component.replace(/~1/g, '/').replace(/~0/g, '~');
}
/** Formats the given pointer into navigable key components */
function* Format(pointer) {
if (pointer === '')
return;
let [start, end] = [0, 0];
for (let i = 0; i < pointer.length; i++) {
const char = pointer.charAt(i);
if (char === '/') {
if (i === 0) {
start = i + 1;
}
else {
end = i;
yield Escape(pointer.slice(start, end));
start = i + 1;
}
}
else {
end = i;
}
}
yield Escape(pointer.slice(start));
}
ValuePointer.Format = Format;
/** Sets the value at the given pointer. If the value at the pointer does not exist it is created */
function Set(value, pointer, update) {
if (pointer === '')
throw new ValuePointerRootSetError(value, pointer, update);
let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) {
if (next[component] === undefined)
next[component] = {};
owner = next;
next = next[component];
key = component;
}
owner[key] = update;
}
ValuePointer.Set = Set;
/** Deletes a value at the given pointer */
function Delete(value, pointer) {
if (pointer === '')
throw new ValuePointerRootDeleteError(value, pointer);
let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) {
if (next[component] === undefined || next[component] === null)
return;
owner = next;
next = next[component];
key = component;
}
if (globalThis.Array.isArray(owner)) {
const index = parseInt(key);
owner.splice(index, 1);
}
else {
delete owner[key];
}
}
ValuePointer.Delete = Delete;
/** Returns true if a value exists at the given pointer */
function Has(value, pointer) {
if (pointer === '')
return true;
let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) {
if (next[component] === undefined)
return false;
owner = next;
next = next[component];
key = component;
}
return globalThis.Object.getOwnPropertyNames(owner).includes(key);
}
ValuePointer.Has = Has;
/** Gets the value at the given pointer */
function Get(value, pointer) {
if (pointer === '')
return value;
let current = value;
for (const component of Format(pointer)) {
if (current[component] === undefined)
return undefined;
current = current[component];
}
return current;
}
ValuePointer.Get = Get;
})(ValuePointer = exports.ValuePointer || (exports.ValuePointer = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.ValuePointer = exports.ValuePointerRootDeleteError = exports.ValuePointerRootSetError = void 0;
class ValuePointerRootSetError extends Error {
constructor(value, path, update) {
super('ValuePointer: Cannot set root value');
this.value = value;
this.path = path;
this.update = update;
}
}
exports.ValuePointerRootSetError = ValuePointerRootSetError;
class ValuePointerRootDeleteError extends Error {
constructor(value, path) {
super('ValuePointer: Cannot delete root value');
this.value = value;
this.path = path;
}
}
exports.ValuePointerRootDeleteError = ValuePointerRootDeleteError;
/** ValuePointer performs mutable operations on values using RFC6901 Json Pointers */
var ValuePointer;
(function (ValuePointer) {
function Escape(component) {
return component.indexOf('~') === -1 ? component : component.replace(/~1/g, '/').replace(/~0/g, '~');
}
/** Formats the given pointer into navigable key components */
function* Format(pointer) {
if (pointer === '')
return;
let [start, end] = [0, 0];
for (let i = 0; i < pointer.length; i++) {
const char = pointer.charAt(i);
if (char === '/') {
if (i === 0) {
start = i + 1;
}
else {
end = i;
yield Escape(pointer.slice(start, end));
start = i + 1;
}
}
else {
end = i;
}
}
yield Escape(pointer.slice(start));
}
ValuePointer.Format = Format;
/** Sets the value at the given pointer. If the value at the pointer does not exist it is created */
function Set(value, pointer, update) {
if (pointer === '')
throw new ValuePointerRootSetError(value, pointer, update);
let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) {
if (next[component] === undefined)
next[component] = {};
owner = next;
next = next[component];
key = component;
}
owner[key] = update;
}
ValuePointer.Set = Set;
/** Deletes a value at the given pointer */
function Delete(value, pointer) {
if (pointer === '')
throw new ValuePointerRootDeleteError(value, pointer);
let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) {
if (next[component] === undefined || next[component] === null)
return;
owner = next;
next = next[component];
key = component;
}
if (globalThis.Array.isArray(owner)) {
const index = parseInt(key);
owner.splice(index, 1);
}
else {
delete owner[key];
}
}
ValuePointer.Delete = Delete;
/** Returns true if a value exists at the given pointer */
function Has(value, pointer) {
if (pointer === '')
return true;
let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) {
if (next[component] === undefined)
return false;
owner = next;
next = next[component];
key = component;
}
return globalThis.Object.getOwnPropertyNames(owner).includes(key);
}
ValuePointer.Has = Has;
/** Gets the value at the given pointer */
function Get(value, pointer) {
if (pointer === '')
return value;
let current = value;
for (const component of Format(pointer)) {
if (current[component] === undefined)
return undefined;
current = current[component];
}
return current;
}
ValuePointer.Get = Get;
})(ValuePointer = exports.ValuePointer || (exports.ValuePointer = {}));

View File

@@ -1,31 +1,31 @@
import * as Types from '../typebox';
import { ValueError } from '../errors/index';
import { Edit } from './delta';
export type { Edit } from './delta';
/** Value performs immutable operations on values */
export declare namespace Value {
/** Casts a value into a given type. The return value will retain as much information of the original value as possible. Cast will convert string, number and boolean values if a reasonable conversion is possible. */
function Cast<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): Types.Static<T>;
/** Casts a value into a given type. The return value will retain as much information of the original value as possible. Cast will convert string, number and boolean values if a reasonable conversion is possible. */
function Cast<T extends Types.TSchema>(schema: T, value: unknown): Types.Static<T>;
/** Creates a value from the given type */
function Create<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R]): Types.Static<T>;
/** Creates a value from the given type */
function Create<T extends Types.TSchema>(schema: T): Types.Static<T>;
/** Returns true if the value matches the given type. */
function Check<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): value is Types.Static<T>;
/** Returns true if the value matches the given type. */
function Check<T extends Types.TSchema>(schema: T, value: unknown): value is Types.Static<T>;
/** Returns an iterator for each error in this value. */
function Errors<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): IterableIterator<ValueError>;
/** Returns an iterator for each error in this value. */
function Errors<T extends Types.TSchema>(schema: T, value: unknown): IterableIterator<ValueError>;
/** Returns true if left and right values are structurally equal */
function Equal<T>(left: T, right: unknown): right is T;
/** Returns a structural clone of the given value */
function Clone<T>(value: T): T;
/** Returns edits to transform the current value into the next value */
function Diff<T>(current: T, next: T): Edit<T>[];
/** Returns a new value with edits applied to the given value */
function Patch<T>(current: T, edits: Edit<T>[]): T;
}
import * as Types from '../typebox';
import { ValueError } from '../errors/index';
import { Edit } from './delta';
export type { Edit } from './delta';
/** Value performs immutable operations on values */
export declare namespace Value {
/** Casts a value into a given type. The return value will retain as much information of the original value as possible. Cast will convert string, number and boolean values if a reasonable conversion is possible. */
function Cast<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): Types.Static<T>;
/** Casts a value into a given type. The return value will retain as much information of the original value as possible. Cast will convert string, number and boolean values if a reasonable conversion is possible. */
function Cast<T extends Types.TSchema>(schema: T, value: unknown): Types.Static<T>;
/** Creates a value from the given type */
function Create<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R]): Types.Static<T>;
/** Creates a value from the given type */
function Create<T extends Types.TSchema>(schema: T): Types.Static<T>;
/** Returns true if the value matches the given type. */
function Check<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): value is Types.Static<T>;
/** Returns true if the value matches the given type. */
function Check<T extends Types.TSchema>(schema: T, value: unknown): value is Types.Static<T>;
/** Returns an iterator for each error in this value. */
function Errors<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: unknown): IterableIterator<ValueError>;
/** Returns an iterator for each error in this value. */
function Errors<T extends Types.TSchema>(schema: T, value: unknown): IterableIterator<ValueError>;
/** Returns true if left and right values are structurally equal */
function Equal<T>(left: T, right: unknown): right is T;
/** Returns a structural clone of the given value */
function Clone<T>(value: T): T;
/** Returns edits to transform the current value into the next value */
function Diff<T>(current: T, next: T): Edit<T>[];
/** Returns a new value with edits applied to the given value */
function Patch<T>(current: T, edits: Edit<T>[]): T;
}

View File

@@ -1,81 +1,81 @@
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.Value = void 0;
const index_1 = require("../errors/index");
const equal_1 = require("./equal");
const cast_1 = require("./cast");
const clone_1 = require("./clone");
const create_1 = require("./create");
const check_1 = require("./check");
const delta_1 = require("./delta");
/** Value performs immutable operations on values */
var Value;
(function (Value) {
function Cast(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
return cast_1.ValueCast.Cast(schema, references, value);
}
Value.Cast = Cast;
function Create(...args) {
const [schema, references] = args.length === 2 ? [args[0], args[1]] : [args[0], []];
return create_1.ValueCreate.Create(schema, references);
}
Value.Create = Create;
function Check(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
return check_1.ValueCheck.Check(schema, references, value);
}
Value.Check = Check;
function* Errors(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
yield* index_1.ValueErrors.Errors(schema, references, value);
}
Value.Errors = Errors;
/** Returns true if left and right values are structurally equal */
function Equal(left, right) {
return equal_1.ValueEqual.Equal(left, right);
}
Value.Equal = Equal;
/** Returns a structural clone of the given value */
function Clone(value) {
return clone_1.ValueClone.Clone(value);
}
Value.Clone = Clone;
/** Returns edits to transform the current value into the next value */
function Diff(current, next) {
return delta_1.ValueDelta.Diff(current, next);
}
Value.Diff = Diff;
/** Returns a new value with edits applied to the given value */
function Patch(current, edits) {
return delta_1.ValueDelta.Patch(current, edits);
}
Value.Patch = Patch;
})(Value = exports.Value || (exports.Value = {}));
"use strict";
/*--------------------------------------------------------------------------
@sinclair/typebox/value
The MIT License (MIT)
Copyright (c) 2022 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.Value = void 0;
const index_1 = require("../errors/index");
const equal_1 = require("./equal");
const cast_1 = require("./cast");
const clone_1 = require("./clone");
const create_1 = require("./create");
const check_1 = require("./check");
const delta_1 = require("./delta");
/** Value performs immutable operations on values */
var Value;
(function (Value) {
function Cast(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
return cast_1.ValueCast.Cast(schema, references, value);
}
Value.Cast = Cast;
function Create(...args) {
const [schema, references] = args.length === 2 ? [args[0], args[1]] : [args[0], []];
return create_1.ValueCreate.Create(schema, references);
}
Value.Create = Create;
function Check(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
return check_1.ValueCheck.Check(schema, references, value);
}
Value.Check = Check;
function* Errors(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]];
yield* index_1.ValueErrors.Errors(schema, references, value);
}
Value.Errors = Errors;
/** Returns true if left and right values are structurally equal */
function Equal(left, right) {
return equal_1.ValueEqual.Equal(left, right);
}
Value.Equal = Equal;
/** Returns a structural clone of the given value */
function Clone(value) {
return clone_1.ValueClone.Clone(value);
}
Value.Clone = Clone;
/** Returns edits to transform the current value into the next value */
function Diff(current, next) {
return delta_1.ValueDelta.Diff(current, next);
}
Value.Diff = Diff;
/** Returns a new value with edits applied to the given value */
function Patch(current, edits) {
return delta_1.ValueDelta.Patch(current, edits);
}
Value.Patch = Patch;
})(Value = exports.Value || (exports.Value = {}));

View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/babel__core`
# Summary
This package contains type definitions for @babel/core (https://github.com/babel/babel/tree/master/packages/babel-core).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__core.
### Additional Details
* Last updated: Mon, 07 Nov 2022 20:33:43 GMT
* Dependencies: [@types/babel__generator](https://npmjs.com/package/@types/babel__generator), [@types/babel__parser](https://npmjs.com/package/@types/babel__parser), [@types/babel__template](https://npmjs.com/package/@types/babel__template), [@types/babel__traverse](https://npmjs.com/package/@types/babel__traverse), [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: `babel`
# Credits
These definitions were written by [Troy Gerwien](https://github.com/yortus), [Marvin Hagemeister](https://github.com/marvinhagemeister), [Melvin Groenhoff](https://github.com/mgroenhoff), [Jessica Franco](https://github.com/Jessidhia), and [Ifiok Jr.](https://github.com/ifiokjr).
# Installation
> `npm install --save @types/babel__core`
# Summary
This package contains type definitions for @babel/core (https://github.com/babel/babel/tree/master/packages/babel-core).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__core.
### Additional Details
* Last updated: Mon, 07 Nov 2022 20:33:43 GMT
* Dependencies: [@types/babel__generator](https://npmjs.com/package/@types/babel__generator), [@types/babel__parser](https://npmjs.com/package/@types/babel__parser), [@types/babel__template](https://npmjs.com/package/@types/babel__template), [@types/babel__traverse](https://npmjs.com/package/@types/babel__traverse), [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: `babel`
# Credits
These definitions were written by [Troy Gerwien](https://github.com/yortus), [Marvin Hagemeister](https://github.com/marvinhagemeister), [Melvin Groenhoff](https://github.com/mgroenhoff), [Jessica Franco](https://github.com/Jessidhia), and [Ifiok Jr.](https://github.com/ifiokjr).

View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/babel__generator`
# Summary
This package contains type definitions for @babel/generator (https://github.com/babel/babel/tree/master/packages/babel-generator).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__generator.
### Additional Details
* Last updated: Thu, 23 Dec 2021 23:34:17 GMT
* Dependencies: [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: none
# Credits
These definitions were written by [Troy Gerwien](https://github.com/yortus), [Melvin Groenhoff](https://github.com/mgroenhoff), [Cameron Yan](https://github.com/khell), and [Lyanbin](https://github.com/Lyanbin).
# Installation
> `npm install --save @types/babel__generator`
# Summary
This package contains type definitions for @babel/generator (https://github.com/babel/babel/tree/master/packages/babel-generator).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__generator.
### Additional Details
* Last updated: Thu, 23 Dec 2021 23:34:17 GMT
* Dependencies: [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: none
# Credits
These definitions were written by [Troy Gerwien](https://github.com/yortus), [Melvin Groenhoff](https://github.com/mgroenhoff), [Cameron Yan](https://github.com/khell), and [Lyanbin](https://github.com/Lyanbin).

View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/babel__template`
# Summary
This package contains type definitions for @babel/template (https://github.com/babel/babel/tree/master/packages/babel-template).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__template.
### Additional Details
* Last updated: Tue, 06 Jul 2021 18:05:41 GMT
* Dependencies: [@types/babel__parser](https://npmjs.com/package/@types/babel__parser), [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: none
# Credits
These definitions were written by [Troy Gerwien](https://github.com/yortus), [Marvin Hagemeister](https://github.com/marvinhagemeister), [Melvin Groenhoff](https://github.com/mgroenhoff), and [ExE Boss](https://github.com/ExE-Boss).
# Installation
> `npm install --save @types/babel__template`
# Summary
This package contains type definitions for @babel/template (https://github.com/babel/babel/tree/master/packages/babel-template).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__template.
### Additional Details
* Last updated: Tue, 06 Jul 2021 18:05:41 GMT
* Dependencies: [@types/babel__parser](https://npmjs.com/package/@types/babel__parser), [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: none
# Credits
These definitions were written by [Troy Gerwien](https://github.com/yortus), [Marvin Hagemeister](https://github.com/marvinhagemeister), [Melvin Groenhoff](https://github.com/mgroenhoff), and [ExE Boss](https://github.com/ExE-Boss).

View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/babel__traverse`
# Summary
This package contains type definitions for @babel/traverse (https://github.com/babel/babel/tree/main/packages/babel-traverse).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__traverse.
### Additional Details
* Last updated: Mon, 28 Nov 2022 17:02:52 GMT
* Dependencies: [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: none
# Credits
These definitions were written by [Troy Gerwien](https://github.com/yortus), [Marvin Hagemeister](https://github.com/marvinhagemeister), [Ryan Petrich](https://github.com/rpetrich), [Melvin Groenhoff](https://github.com/mgroenhoff), [Dean L.](https://github.com/dlgrit), [Ifiok Jr.](https://github.com/ifiokjr), [ExE Boss](https://github.com/ExE-Boss), and [Daniel Tschinder](https://github.com/danez).
# Installation
> `npm install --save @types/babel__traverse`
# Summary
This package contains type definitions for @babel/traverse (https://github.com/babel/babel/tree/main/packages/babel-traverse).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__traverse.
### Additional Details
* Last updated: Mon, 28 Nov 2022 17:02:52 GMT
* Dependencies: [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: none
# Credits
These definitions were written by [Troy Gerwien](https://github.com/yortus), [Marvin Hagemeister](https://github.com/marvinhagemeister), [Ryan Petrich](https://github.com/rpetrich), [Melvin Groenhoff](https://github.com/mgroenhoff), [Dean L.](https://github.com/dlgrit), [Ifiok Jr.](https://github.com/ifiokjr), [ExE Boss](https://github.com/ExE-Boss), and [Daniel Tschinder](https://github.com/danez).

View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/graceful-fs`
# Summary
This package contains type definitions for graceful-fs (https://github.com/isaacs/node-graceful-fs).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/graceful-fs.
### Additional Details
* Last updated: Thu, 11 Feb 2021 21:48:33 GMT
* Dependencies: [@types/node](https://npmjs.com/package/@types/node)
* Global values: none
# Credits
These definitions were written by [Bart van der Schoor](https://github.com/Bartvds), and [BendingBender](https://github.com/BendingBender).
# Installation
> `npm install --save @types/graceful-fs`
# Summary
This package contains type definitions for graceful-fs (https://github.com/isaacs/node-graceful-fs).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/graceful-fs.
### Additional Details
* Last updated: Thu, 11 Feb 2021 21:48:33 GMT
* Dependencies: [@types/node](https://npmjs.com/package/@types/node)
* Global values: none
# Credits
These definitions were written by [Bart van der Schoor](https://github.com/Bartvds), and [BendingBender](https://github.com/BendingBender).

View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/istanbul-lib-coverage`
# Summary
This package contains type definitions for istanbul-lib-coverage (https://istanbul.js.org).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-lib-coverage.
### Additional Details
* Last updated: Thu, 23 Dec 2021 23:34:53 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [Jason Cheatham](https://github.com/jason0x43).
# Installation
> `npm install --save @types/istanbul-lib-coverage`
# Summary
This package contains type definitions for istanbul-lib-coverage (https://istanbul.js.org).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-lib-coverage.
### Additional Details
* Last updated: Thu, 23 Dec 2021 23:34:53 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [Jason Cheatham](https://github.com/jason0x43).

View File

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

View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/istanbul-lib-report`
# Summary
This package contains type definitions for istanbul-lib-report (https://istanbul.js.org).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-lib-report.
### Additional Details
* Last updated: Tue, 21 Jan 2020 01:00:06 GMT
* Dependencies: [@types/istanbul-lib-coverage](https://npmjs.com/package/@types/istanbul-lib-coverage)
* Global values: none
# Credits
These definitions were written by Jason Cheatham (https://github.com/jason0x43), and Zacharias Björngren (https://github.com/zache).
# Installation
> `npm install --save @types/istanbul-lib-report`
# Summary
This package contains type definitions for istanbul-lib-report (https://istanbul.js.org).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-lib-report.
### Additional Details
* Last updated: Tue, 21 Jan 2020 01:00:06 GMT
* Dependencies: [@types/istanbul-lib-coverage](https://npmjs.com/package/@types/istanbul-lib-coverage)
* Global values: none
# Credits
These definitions were written by Jason Cheatham (https://github.com/jason0x43), and Zacharias Björngren (https://github.com/zache).

View File

@@ -1,13 +1,13 @@
# Installation
> `npm install --save @types/istanbul-reports`
# Summary
This package contains type definitions for istanbul-reports (https://github.com/istanbuljs/istanbuljs).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-reports.
## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-reports/index.d.ts)
````ts
# Installation
> `npm install --save @types/istanbul-reports`
# Summary
This package contains type definitions for istanbul-reports (https://github.com/istanbuljs/istanbuljs).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-reports.
## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-reports/index.d.ts)
````ts
// Type definitions for istanbul-reports 3.0
// Project: https://github.com/istanbuljs/istanbuljs, https://istanbul.js.org
// Definitions by: Jason Cheatham <https://github.com/jason0x43>
@@ -82,13 +82,13 @@ export interface LinkMapper {
relativePath(source: string | Node, target: string | Node): string;
assetPath(node: Node, name: string): string;
}
````
### Additional Details
* Last updated: Tue, 01 Jun 2021 21:02:19 GMT
* Dependencies: [@types/istanbul-lib-report](https://npmjs.com/package/@types/istanbul-lib-report)
* Global values: none
# Credits
These definitions were written by [Jason Cheatham](https://github.com/jason0x43), and [Elena Shcherbakova](https://github.com/not-a-doctor).
````
### Additional Details
* Last updated: Tue, 01 Jun 2021 21:02:19 GMT
* Dependencies: [@types/istanbul-lib-report](https://npmjs.com/package/@types/istanbul-lib-report)
* Global values: none
# Credits
These definitions were written by [Jason Cheatham](https://github.com/jason0x43), and [Elena Shcherbakova](https://github.com/not-a-doctor).

32
node_modules/@types/jest/README.md generated vendored
View File

@@ -1,17 +1,17 @@
# Installation
> `npm install --save @types/jest`
# Summary
This package contains type definitions for Jest (https://jestjs.io/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest.
### Additional Details
* Last updated: Mon, 05 Dec 2022 07:03:06 GMT
* Dependencies: [@types/expect](https://npmjs.com/package/@types/expect), [@types/pretty-format](https://npmjs.com/package/@types/pretty-format)
* Global values: `afterAll`, `afterEach`, `beforeAll`, `beforeEach`, `describe`, `expect`, `fail`, `fdescribe`, `fit`, `it`, `jasmine`, `jest`, `pending`, `spyOn`, `test`, `xdescribe`, `xit`, `xtest`
# Credits
# Installation
> `npm install --save @types/jest`
# Summary
This package contains type definitions for Jest (https://jestjs.io/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jest.
### Additional Details
* Last updated: Mon, 05 Dec 2022 07:03:06 GMT
* Dependencies: [@types/expect](https://npmjs.com/package/@types/expect), [@types/pretty-format](https://npmjs.com/package/@types/pretty-format)
* Global values: `afterAll`, `afterEach`, `beforeAll`, `beforeEach`, `describe`, `expect`, `fail`, `fdescribe`, `fit`, `it`, `jasmine`, `jest`, `pending`, `spyOn`, `test`, `xdescribe`, `xit`, `xtest`
# Credits
These definitions were written by [Asana (https://asana.com)
// Ivo Stratev](https://github.com/NoHomey), [jwbay](https://github.com/jwbay), [Alexey Svetliakov](https://github.com/asvetliakov), [Alex Jover Morales](https://github.com/alexjoverm), [Allan Lukwago](https://github.com/epicallan), [Ika](https://github.com/ikatyang), [Waseem Dahman](https://github.com/wsmd), [Jamie Mason](https://github.com/JamieMason), [Douglas Duteil](https://github.com/douglasduteil), [Ahn](https://github.com/ahnpnl), [Jeff Lau](https://github.com/UselessPickles), [Andrew Makarov](https://github.com/r3nya), [Martin Hochel](https://github.com/hotell), [Sebastian Sebald](https://github.com/sebald), [Andy](https://github.com/andys8), [Antoine Brault](https://github.com/antoinebrault), [Gregor Stamać](https://github.com/gstamac), [ExE Boss](https://github.com/ExE-Boss), [Alex Bolenok](https://github.com/quassnoi), [Mario Beltrán Alarcón](https://github.com/Belco90), [Tony Hallett](https://github.com/tonyhallett), [Jason Yu](https://github.com/ycmjason), [Pawel Fajfer](https://github.com/pawfa), [Alexandre Germain](https://github.com/gerkindev), [Adam Jones](https://github.com/domdomegg), and [Tom Mrazauskas](https://github.com/mrazauskas).
// Ivo Stratev](https://github.com/NoHomey), [jwbay](https://github.com/jwbay), [Alexey Svetliakov](https://github.com/asvetliakov), [Alex Jover Morales](https://github.com/alexjoverm), [Allan Lukwago](https://github.com/epicallan), [Ika](https://github.com/ikatyang), [Waseem Dahman](https://github.com/wsmd), [Jamie Mason](https://github.com/JamieMason), [Douglas Duteil](https://github.com/douglasduteil), [Ahn](https://github.com/ahnpnl), [Jeff Lau](https://github.com/UselessPickles), [Andrew Makarov](https://github.com/r3nya), [Martin Hochel](https://github.com/hotell), [Sebastian Sebald](https://github.com/sebald), [Andy](https://github.com/andys8), [Antoine Brault](https://github.com/antoinebrault), [Gregor Stamać](https://github.com/gstamac), [ExE Boss](https://github.com/ExE-Boss), [Alex Bolenok](https://github.com/quassnoi), [Mario Beltrán Alarcón](https://github.com/Belco90), [Tony Hallett](https://github.com/tonyhallett), [Jason Yu](https://github.com/ycmjason), [Pawel Fajfer](https://github.com/pawfa), [Alexandre Germain](https://github.com/gerkindev), [Adam Jones](https://github.com/domdomegg), and [Tom Mrazauskas](https://github.com/mrazauskas).

32
node_modules/@types/node/README.md generated vendored
View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/node`
# Summary
This package contains type definitions for Node.js (https://nodejs.org/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v12.
### Additional Details
* Last updated: Tue, 07 Jun 2022 19:01:37 GMT
* Dependencies: none
* Global values: `Buffer`, `NodeJS`, `__dirname`, `__filename`, `clearImmediate`, `clearInterval`, `clearTimeout`, `console`, `exports`, `global`, `module`, `process`, `queueMicrotask`, `require`, `setImmediate`, `setInterval`, `setTimeout`
# Credits
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Hoàng Văn Khải](https://github.com/KSXGitHub), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Zane Hannan AU](https://github.com/ZaneHannanAU), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), and [ExE Boss](https://github.com/ExE-Boss).
# Installation
> `npm install --save @types/node`
# Summary
This package contains type definitions for Node.js (https://nodejs.org/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v12.
### Additional Details
* Last updated: Tue, 07 Jun 2022 19:01:37 GMT
* Dependencies: none
* Global values: `Buffer`, `NodeJS`, `__dirname`, `__filename`, `clearImmediate`, `clearInterval`, `clearTimeout`, `console`, `exports`, `global`, `module`, `process`, `queueMicrotask`, `require`, `setImmediate`, `setInterval`, `setTimeout`
# Credits
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Hoàng Văn Khải](https://github.com/KSXGitHub), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Zane Hannan AU](https://github.com/ZaneHannanAU), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), and [ExE Boss](https://github.com/ExE-Boss).

View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/prettier`
# Summary
This package contains type definitions for prettier (https://prettier.io).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/prettier.
### Additional Details
* Last updated: Sat, 24 Sep 2022 05:02:56 GMT
* Dependencies: none
* Global values: `prettier`
# Credits
These definitions were written by [Ika](https://github.com/ikatyang), [Ifiok Jr.](https://github.com/ifiokjr), [Florian Imdahl](https://github.com/ffflorian), [Sosuke Suzuki](https://github.com/sosukesuzuki), [Christopher Quadflieg](https://github.com/Shinigami92), [Georgii Dolzhykov](https://github.com/thorn0), [JounQin](https://github.com/JounQin), and [Chuah Chee Shian](https://github.com/shian15810).
# Installation
> `npm install --save @types/prettier`
# Summary
This package contains type definitions for prettier (https://prettier.io).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/prettier.
### Additional Details
* Last updated: Sat, 24 Sep 2022 05:02:56 GMT
* Dependencies: none
* Global values: `prettier`
# Credits
These definitions were written by [Ika](https://github.com/ikatyang), [Ifiok Jr.](https://github.com/ifiokjr), [Florian Imdahl](https://github.com/ffflorian), [Sosuke Suzuki](https://github.com/sosukesuzuki), [Christopher Quadflieg](https://github.com/Shinigami92), [Georgii Dolzhykov](https://github.com/thorn0), [JounQin](https://github.com/JounQin), and [Chuah Chee Shian](https://github.com/shian15810).

View File

@@ -1,13 +1,13 @@
# Installation
> `npm install --save @types/stack-utils`
# Summary
This package contains type definitions for stack-utils (https://github.com/tapjs/stack-utils#readme).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/stack-utils.
## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/stack-utils/index.d.ts)
````ts
# Installation
> `npm install --save @types/stack-utils`
# Summary
This package contains type definitions for stack-utils (https://github.com/tapjs/stack-utils#readme).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/stack-utils.
## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/stack-utils/index.d.ts)
````ts
// Type definitions for stack-utils 2.0
// Project: https://github.com/tapjs/stack-utils#readme
// Definitions by: BendingBender <https://github.com/BendingBender>
@@ -73,13 +73,13 @@ declare namespace StackUtils {
method?: string | undefined;
}
}
````
### Additional Details
* Last updated: Fri, 02 Jul 2021 22:32:52 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [BendingBender](https://github.com/BendingBender).
````
### Additional Details
* Last updated: Fri, 02 Jul 2021 22:32:52 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [BendingBender](https://github.com/BendingBender).

View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/yargs-parser`
# Summary
This package contains type definitions for yargs-parser (https://github.com/yargs/yargs-parser#readme).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs-parser.
### Additional Details
* Last updated: Wed, 02 Mar 2022 17:31:51 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [Miles Johnson](https://github.com/milesj).
# Installation
> `npm install --save @types/yargs-parser`
# Summary
This package contains type definitions for yargs-parser (https://github.com/yargs/yargs-parser#readme).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs-parser.
### Additional Details
* Last updated: Wed, 02 Mar 2022 17:31:51 GMT
* Dependencies: none
* Global values: none
# Credits
These definitions were written by [Miles Johnson](https://github.com/milesj).

32
node_modules/@types/yargs/README.md generated vendored
View File

@@ -1,16 +1,16 @@
# Installation
> `npm install --save @types/yargs`
# Summary
This package contains type definitions for yargs (https://github.com/chevex/yargs).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs.
### Additional Details
* Last updated: Wed, 07 Dec 2022 17:33:14 GMT
* Dependencies: [@types/yargs-parser](https://npmjs.com/package/@types/yargs-parser)
* Global values: none
# Credits
These definitions were written by [Martin Poelstra](https://github.com/poelstra), [Mizunashi Mana](https://github.com/mizunashi-mana), [Jeffery Grajkowski](https://github.com/pushplay), [Jimi (Dimitris) Charalampidis](https://github.com/JimiC), [Steffen Viken Valvåg](https://github.com/steffenvv), [Emily Marigold Klassen](https://github.com/forivall), [ExE Boss](https://github.com/ExE-Boss), [Aankhen](https://github.com/Aankhen), and [Ben Coe](https://github.com/bcoe).
# Installation
> `npm install --save @types/yargs`
# Summary
This package contains type definitions for yargs (https://github.com/chevex/yargs).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs.
### Additional Details
* Last updated: Wed, 07 Dec 2022 17:33:14 GMT
* Dependencies: [@types/yargs-parser](https://npmjs.com/package/@types/yargs-parser)
* Global values: none
# Credits
These definitions were written by [Martin Poelstra](https://github.com/poelstra), [Mizunashi Mana](https://github.com/mizunashi-mana), [Jeffery Grajkowski](https://github.com/pushplay), [Jimi (Dimitris) Charalampidis](https://github.com/JimiC), [Steffen Viken Valvåg](https://github.com/steffenvv), [Emily Marigold Klassen](https://github.com/forivall), [ExE Boss](https://github.com/ExE-Boss), [Aankhen](https://github.com/Aankhen), and [Ben Coe](https://github.com/bcoe).

View File

@@ -1,24 +1,24 @@
export declare enum FormatType {
"JSON" = 0,
"XML" = 1
}
/**
* Takes content as string and format type (xml, json).
* Exposes getSecret method to get value of specific secret in object and set it as secret.
*/
export declare class SecretParser {
private dom;
private contentType;
constructor(content: string, contentType: FormatType);
/**
*
* @param key jsonpath or xpath depending on content type
* @param isSecret should the value parsed be a secret. Deafult: true
* @param variableName optional. If provided value will be exported with this variable name
* @returns a string value or empty string if key not found
*/
getSecret(key: string, isSecret?: boolean, variableName?: string): string;
private extractJsonPath;
private extractXmlPath;
private handleSecret;
}
export declare enum FormatType {
"JSON" = 0,
"XML" = 1
}
/**
* Takes content as string and format type (xml, json).
* Exposes getSecret method to get value of specific secret in object and set it as secret.
*/
export declare class SecretParser {
private dom;
private contentType;
constructor(content: string, contentType: FormatType);
/**
*
* @param key jsonpath or xpath depending on content type
* @param isSecret should the value parsed be a secret. Deafult: true
* @param variableName optional. If provided value will be exported with this variable name
* @returns a string value or empty string if key not found
*/
getSecret(key: string, isSecret?: boolean, variableName?: string): string;
private extractJsonPath;
private extractXmlPath;
private handleSecret;
}

View File

@@ -1,92 +1,92 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecretParser = exports.FormatType = void 0;
var core = require('@actions/core');
var jp = require('jsonpath');
var xpath = require('xpath');
var domParser = require('xmldom').DOMParser;
var FormatType;
(function (FormatType) {
FormatType[FormatType["JSON"] = 0] = "JSON";
FormatType[FormatType["XML"] = 1] = "XML";
})(FormatType = exports.FormatType || (exports.FormatType = {}));
/**
* Takes content as string and format type (xml, json).
* Exposes getSecret method to get value of specific secret in object and set it as secret.
*/
class SecretParser {
constructor(content, contentType) {
switch (contentType) {
case FormatType.JSON:
try {
this.dom = JSON.parse(content);
}
catch (ex) {
throw new Error('Content is not a valid JSON object');
}
break;
case FormatType.XML:
try {
this.dom = new domParser().parseFromString(content);
}
catch (ex) {
throw new Error('Content is not a valid XML object');
}
break;
default:
throw new Error(`Given format: ${contentType} is not supported. Valid options are JSON, XML.`);
}
this.contentType = contentType;
}
/**
*
* @param key jsonpath or xpath depending on content type
* @param isSecret should the value parsed be a secret. Deafult: true
* @param variableName optional. If provided value will be exported with this variable name
* @returns a string value or empty string if key not found
*/
getSecret(key, isSecret = true, variableName) {
let value = "";
switch (this.contentType) {
case FormatType.JSON:
value = this.extractJsonPath(key, isSecret, variableName);
break;
case FormatType.XML:
value = this.extractXmlPath(key, isSecret, variableName);
break;
}
return value;
}
extractJsonPath(key, isSecret = false, variableName) {
let value = jp.query(this.dom, key);
if (value.length == 0) {
core.debug("Cannot find key: " + key);
return "";
}
else if (value.length > 1) {
core.debug("Multiple values found for key: " + key + ". Please give jsonPath which points to a single value.");
return "";
}
return this.handleSecret(key, value[0], isSecret, variableName);
}
extractXmlPath(key, isSecret = false, variableName) {
let value = xpath.select("string(" + key + ")", this.dom);
return this.handleSecret(key, value, isSecret, variableName);
}
handleSecret(key, value, isSecret, variableName) {
if (!!value) {
if (isSecret) {
core.setSecret(value);
}
if (!!variableName) {
core.exportVariable(variableName, value);
}
return value;
}
else {
core.debug("Cannot find key: " + key);
return "";
}
}
}
exports.SecretParser = SecretParser;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SecretParser = exports.FormatType = void 0;
var core = require('@actions/core');
var jp = require('jsonpath');
var xpath = require('xpath');
var domParser = require('xmldom').DOMParser;
var FormatType;
(function (FormatType) {
FormatType[FormatType["JSON"] = 0] = "JSON";
FormatType[FormatType["XML"] = 1] = "XML";
})(FormatType = exports.FormatType || (exports.FormatType = {}));
/**
* Takes content as string and format type (xml, json).
* Exposes getSecret method to get value of specific secret in object and set it as secret.
*/
class SecretParser {
constructor(content, contentType) {
switch (contentType) {
case FormatType.JSON:
try {
this.dom = JSON.parse(content);
}
catch (ex) {
throw new Error('Content is not a valid JSON object');
}
break;
case FormatType.XML:
try {
this.dom = new domParser().parseFromString(content);
}
catch (ex) {
throw new Error('Content is not a valid XML object');
}
break;
default:
throw new Error(`Given format: ${contentType} is not supported. Valid options are JSON, XML.`);
}
this.contentType = contentType;
}
/**
*
* @param key jsonpath or xpath depending on content type
* @param isSecret should the value parsed be a secret. Deafult: true
* @param variableName optional. If provided value will be exported with this variable name
* @returns a string value or empty string if key not found
*/
getSecret(key, isSecret = true, variableName) {
let value = "";
switch (this.contentType) {
case FormatType.JSON:
value = this.extractJsonPath(key, isSecret, variableName);
break;
case FormatType.XML:
value = this.extractXmlPath(key, isSecret, variableName);
break;
}
return value;
}
extractJsonPath(key, isSecret = false, variableName) {
let value = jp.query(this.dom, key);
if (value.length == 0) {
core.debug("Cannot find key: " + key);
return "";
}
else if (value.length > 1) {
core.debug("Multiple values found for key: " + key + ". Please give jsonPath which points to a single value.");
return "";
}
return this.handleSecret(key, value[0], isSecret, variableName);
}
extractXmlPath(key, isSecret = false, variableName) {
let value = xpath.select("string(" + key + ")", this.dom);
return this.handleSecret(key, value, isSecret, variableName);
}
handleSecret(key, value, isSecret, variableName) {
if (!!value) {
if (isSecret) {
core.setSecret(value);
}
if (!!variableName) {
core.exportVariable(variableName, value);
}
return value;
}
else {
core.debug("Cannot find key: " + key);
return "";
}
}
}
exports.SecretParser = SecretParser;

View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esprima\bin\esparse.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esprima\bin\esparse.js" %*

View File

@@ -1,17 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esprima\bin\esvalidate.js" %*
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\esprima\bin\esvalidate.js" %*

View File

@@ -1,35 +1,35 @@
{
"name": "actions-secret-parser",
"version": "1.0.4",
"description": "Parse and set repository secrets",
"main": "index.js",
"scripts": {
"build": "tsc",
"copypackage": "copy package.json lib",
"dist": "npm run build && npm run copypackage && cd lib && npm publish"
},
"keywords": [
"secret",
"actions"
],
"repository": {
"type": "git",
"url": "git+https://github.com/Microsoft/pipelines-appservice-lib.git"
},
"author": "Sumiran Aggarwal <suaggar@microsoft.com>",
"bugs": {
"url": "https://github.com/Microsoft/pipelines-appservice-lib/issues"
},
"homepage": "https://github.com/Microsoft/pipelines-appservice-lib/tree/master/packages/utility",
"license": "MIT",
"devDependencies": {
"@types/node": "^18.11.17",
"typescript": "^3.6.3"
},
"dependencies": {
"@actions/core": "^1.1.10",
"jsonpath": "^1.0.2",
"xmldom": "^0.1.27",
"xpath": "0.0.27"
}
}
{
"name": "actions-secret-parser",
"version": "1.0.4",
"description": "Parse and set repository secrets",
"main": "index.js",
"scripts": {
"build": "tsc",
"copypackage": "copy package.json lib",
"dist": "npm run build && npm run copypackage && cd lib && npm publish"
},
"keywords": [
"secret",
"actions"
],
"repository": {
"type": "git",
"url": "git+https://github.com/Microsoft/pipelines-appservice-lib.git"
},
"author": "Sumiran Aggarwal <suaggar@microsoft.com>",
"bugs": {
"url": "https://github.com/Microsoft/pipelines-appservice-lib/issues"
},
"homepage": "https://github.com/Microsoft/pipelines-appservice-lib/tree/master/packages/utility",
"license": "MIT",
"devDependencies": {
"@types/node": "^18.11.17",
"typescript": "^3.6.3"
},
"dependencies": {
"@actions/core": "^1.1.10",
"jsonpath": "^1.0.2",
"xmldom": "^0.1.27",
"xpath": "0.0.27"
}
}

42
node_modules/char-regex/LICENSE generated vendored
View File

@@ -1,21 +1,21 @@
MIT License
Copyright (c) 2019 Richie Bendall
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.
MIT License
Copyright (c) 2019 Richie Bendall
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.

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