Compare commits

..

1 Commits

Author SHA1 Message Date
YanaXu
4c88f01b0e prepare release 1.5.0 2023-11-20 14:12:35 +08:00
227 changed files with 26266 additions and 26457 deletions

View File

@@ -30,7 +30,7 @@ jobs:
az --version az --version
- name: Check out repository - name: Check out repository
uses: actions/checkout@v4 uses: actions/checkout@v3
- name: 'Az CLI login with subscription' - name: 'Az CLI login with subscription'
uses: azure/login@v1 uses: azure/login@v1

View File

@@ -9,6 +9,86 @@ permissions:
jobs: jobs:
OSTest:
runs-on: macos-latest
environment: Automation test
steps:
- name: 'Checking out repo code'
uses: actions/checkout@v3.5.2
- name: Set Node.js 16.x for GitHub Action
uses: actions/setup-node@v1
with:
node-version: 16.x
- name: 'Validate build'
run: |
npm install
npm run build
npm run test
- name: Login with creds
continue-on-error: true
uses: ./
with:
creds: ${{secrets.SP1}}
enable-AzPSSession: true
- name: Run Azure Cli
run: |
az account show --output none
az group show --name GitHubAction_CI_RG --output none
az vm list --output none
- name: Run Azure PowerShell
id: ps_1
continue-on-error: true
uses: azure/powershell@v1.2.0
with:
azPSVersion: "latest"
inlineScript: |
(Get-AzContext).Environment.Name -eq 'AzureCloud'
(Get-AzResourceGroup -Name GitHubAction_CI_RG).ResourceGroupName -eq 'GitHubAction_CI_RG'
(Get-AzVM).Count -gt 0
- name: Check Last step failed
if: steps.ps_1.outcome == 'success'
uses: actions/github-script@v3
with:
script: |
core.setFailed('Last action should fail but not. Please check it.')
- name: Login with individual parameters
id: login_2
uses: ./
with:
client-id: ${{ secrets.OIDC_SP2_CLIENT_ID }}
tenant-id: ${{ secrets.OIDC_SP2_TENANT_ID }}
# subscription-id: ${{ secrets.OIDC_SP2_SUBSCRIPTION_ID }}
allow-no-subscriptions: true
enable-AzPSSession: true
- name: Run Azure Cli again
run: |
az account show --output none
- name: Run Azure PowerShell again
id: ps_2
continue-on-error: true
uses: azure/powershell@v1.2.0
with:
azPSVersion: "latest"
inlineScript: |
(Get-AzContext).Environment.Name -eq 'AzureCloud'
- name: Check Last step failed
if: steps.ps_2.outcome == 'success'
uses: actions/github-script@v3
with:
script: |
core.setFailed('Last action should fail but not. Please check it.')
PermissionTest: PermissionTest:
strategy: strategy:
matrix: matrix:
@@ -19,10 +99,10 @@ jobs:
steps: steps:
- name: 'Checking out repo code' - name: 'Checking out repo code'
uses: actions/checkout@v4 uses: actions/checkout@v3.5.2
- name: Set Node.js 16.x for GitHub Action - name: Set Node.js 16.x for GitHub Action
uses: actions/setup-node@v4 uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 16.x
@@ -50,7 +130,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.cli_3.outcome == 'success' if: steps.cli_3.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -58,7 +138,7 @@ jobs:
- name: Run Azure PowerShell - name: Run Azure PowerShell
id: ps_3 id: ps_3
continue-on-error: true continue-on-error: true
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -68,7 +148,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.ps_3.outcome == 'success' if: steps.ps_3.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -82,10 +162,10 @@ jobs:
steps: steps:
- name: 'Checking out repo code' - name: 'Checking out repo code'
uses: actions/checkout@v4 uses: actions/checkout@v3.5.2
- name: Set Node.js 16.x for GitHub Action - name: Set Node.js 16.x for GitHub Action
uses: actions/setup-node@v4 uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 16.x
@@ -104,7 +184,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.login_4.outcome == 'success' if: steps.login_4.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -119,7 +199,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.login_5.outcome == 'success' if: steps.login_5.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -133,7 +213,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.login_6.outcome == 'success' if: steps.login_6.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -149,7 +229,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.login_7.outcome == 'success' if: steps.login_7.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -166,7 +246,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.login_8.outcome == 'success' if: steps.login_8.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -186,7 +266,7 @@ jobs:
- name: Run Azure PowerShell - name: Run Azure PowerShell
id: ps_8 id: ps_8
continue-on-error: true continue-on-error: true
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -196,7 +276,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.ps_8.outcome == 'success' if: steps.ps_8.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -216,7 +296,7 @@ jobs:
- name: Run Azure PowerShell - name: Run Azure PowerShell
id: ps_9 id: ps_9
continue-on-error: true continue-on-error: true
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -226,7 +306,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.ps_9.outcome == 'success' if: steps.ps_9.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -245,7 +325,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.login_10.outcome == 'success' if: steps.login_10.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -262,12 +342,12 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.login_11.outcome == 'success' if: steps.login_11.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
# SP1 is ignored and SP2 will be used for login, but it will fail since SP2 has no access to the given subscription # Secret of SP1 in creds will be used to sign in SP2
- name: Login with both creds and individual parameters - name: Login with both creds and individual parameters
id: login_12 id: login_12
continue-on-error: true continue-on-error: true
@@ -282,7 +362,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.login_12.outcome == 'success' if: steps.login_12.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -298,38 +378,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.login_13.outcome == 'success' if: steps.login_13.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with:
script: |
core.setFailed('Last action should fail but not. Please check it.')
- name: Login with individual parameters, no subscription-id, no allow-no-subscriptions
id: login_14
continue-on-error: true
uses: ./
with:
client-id: ${{ secrets.OIDC_SP2_CLIENT_ID }}
tenant-id: ${{ secrets.OIDC_SP2_TENANT_ID }}
enable-AzPSSession: true
- name: Check Last step failed
if: steps.login_14.outcome == 'success'
uses: actions/github-script@v7
with:
script: |
core.setFailed('Last action should fail but not. Please check it.')
- name: Login with creds, no subscription-id, no allow-no-subscriptions
id: login_15
continue-on-error: true
uses: ./
with:
creds: '{"clientId":"${{ secrets.OIDC_SP2_CLIENT_ID }}","clientSecret":"${{ secrets.SP2_CLIENT_SECRET }}","tenantId":"${{ secrets.OIDC_SP2_TENANT_ID }}"}'
enable-AzPSSession: true
- name: Check Last step failed
if: steps.login_15.outcome == 'success'
uses: actions/github-script@v7
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')
@@ -343,10 +392,10 @@ jobs:
steps: steps:
- name: 'Checking out repo code' - name: 'Checking out repo code'
uses: actions/checkout@v4 uses: actions/checkout@v3.5.2
- name: Set Node.js 16.x for GitHub Action - name: Set Node.js 16.x for GitHub Action
uses: actions/setup-node@v4 uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 16.x
@@ -362,7 +411,7 @@ jobs:
- name: Check Last step failed - name: Check Last step failed
if: steps.login_14.outcome == 'success' if: steps.login_14.outcome == 'success'
uses: actions/github-script@v7 uses: actions/github-script@v3
with: with:
script: | script: |
core.setFailed('Last action should fail but not. Please check it.') core.setFailed('Last action should fail but not. Please check it.')

View File

@@ -12,16 +12,16 @@ jobs:
BasicTest: BasicTest:
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest, self_linux, self_windows] os: [ubuntu-latest, windows-latest, self_linux, self_windows]
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
environment: Automation test environment: Automation test
steps: steps:
- name: 'Checking out repo code' - name: 'Checking out repo code'
uses: actions/checkout@v4 uses: actions/checkout@v3.5.2
- name: Set Node.js 16.x for GitHub Action - name: Set Node.js 16.x for GitHub Action
uses: actions/setup-node@v4 uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 16.x
@@ -47,7 +47,7 @@ jobs:
az vm list --output none az vm list --output none
- name: Run Azure PowerShell - name: Run Azure PowerShell
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -61,9 +61,10 @@ jobs:
- name: Login with individual parameters - name: Login with individual parameters
uses: ./ uses: ./
with: with:
client-id: ${{ secrets.SP1_CLIENT_ID }} client-id: ${{ secrets.OIDC_SP2_CLIENT_ID }}
tenant-id: ${{ secrets.SP1_TENANT_ID }} tenant-id: ${{ secrets.OIDC_SP2_TENANT_ID }}
subscription-id: ${{ secrets.SP1_SUBSCRIPTION_ID }} # subscription-id: ${{ secrets.OIDC_SP2_SUBSCRIPTION_ID }}
allow-no-subscriptions: true
enable-AzPSSession: true enable-AzPSSession: true
- name: Run Azure Cli again - name: Run Azure Cli again
@@ -71,7 +72,7 @@ jobs:
az account show --output none az account show --output none
- name: Run Azure PowerShell again - name: Run Azure PowerShell again
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -94,7 +95,7 @@ jobs:
az vm list --output none az vm list --output none
- name: Run Azure PowerShell - name: Run Azure PowerShell
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -108,16 +109,16 @@ jobs:
ParameterTest: ParameterTest:
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest, windows-latest, macos-latest] os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
environment: Automation test environment: Automation test
steps: steps:
- name: 'Checking out repo code' - name: 'Checking out repo code'
uses: actions/checkout@v4 uses: actions/checkout@v3.5.2
- name: Set Node.js 16.x for GitHub Action - name: Set Node.js 16.x for GitHub Action
uses: actions/setup-node@v4 uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 16.x
@@ -164,7 +165,7 @@ jobs:
az vm list --output none az vm list --output none
- name: Run Azure PowerShell - name: Run Azure PowerShell
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -175,29 +176,6 @@ jobs:
throw "Not all checks passed!" throw "Not all checks passed!"
} }
- name: Login with individual parameters, allow no subscription
uses: ./
with:
client-id: ${{ secrets.SP1_CLIENT_ID }}
tenant-id: ${{ secrets.SP1_TENANT_ID}}
subscription-id: ${{ secrets.SP1_SUBSCRIPTION_ID }}
allow-no-subscriptions: true
enable-AzPSSession: true
- name: Run Azure Cli again
run: |
az account show --output none
- name: Run Azure PowerShell again
uses: azure/powershell@v1
with:
azPSVersion: "latest"
inlineScript: |
$checkResult = (Get-AzContext).Environment.Name -eq 'AzureCloud'
if(-not $checkResult){
throw "Not all checks passed!"
}
- name: Login with individual parameters, no subscription, allow no subscription - name: Login with individual parameters, no subscription, allow no subscription
uses: ./ uses: ./
with: with:
@@ -206,37 +184,12 @@ jobs:
allow-no-subscriptions: true allow-no-subscriptions: true
enable-AzPSSession: true enable-AzPSSession: true
- name: Run Azure Cli
shell: pwsh
run: |
$checkResult = (az account list --output json | ConvertFrom-Json).Count -eq 2
if(-not $checkResult){
throw "Not all checks passed!"
}
- name: Run Azure PowerShell
uses: azure/powershell@v1
with:
azPSVersion: "latest"
inlineScript: |
$checkResult = (Get-AzContext -ListAvailable).Count -eq 2
if(-not $checkResult){
throw "Not all checks passed!"
}
- name: Login with creds, no subscription, allow no subscription
uses: ./
with:
creds: '{"clientId":"${{ secrets.OIDC_SP2_CLIENT_ID }}","clientSecret":"${{ secrets.SP2_CLIENT_SECRET }}","tenantId":"${{ secrets.OIDC_SP2_TENANT_ID }}"}'
allow-no-subscriptions: true
enable-AzPSSession: true
- name: Run Azure Cli - name: Run Azure Cli
run: | run: |
az account show --output none az account show --output none
- name: Run Azure PowerShell - name: Run Azure PowerShell
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -254,10 +207,10 @@ jobs:
steps: steps:
- name: 'Checking out repo code' - name: 'Checking out repo code'
uses: actions/checkout@v4 uses: actions/checkout@v3.5.2
- name: Set Node.js 16.x for GitHub Action - name: Set Node.js 16.x for GitHub Action
uses: actions/setup-node@v4 uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 16.x
@@ -278,7 +231,7 @@ jobs:
az account show --output none az account show --output none
- name: Run Azure PowerShell - name: Run Azure PowerShell
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -301,7 +254,7 @@ jobs:
az vm list --output none az vm list --output none
- name: Run Azure PowerShell - name: Run Azure PowerShell
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -325,7 +278,7 @@ jobs:
az account show --output none az account show --output none
- name: Run Azure PowerShell - name: Run Azure PowerShell
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -349,7 +302,7 @@ jobs:
az vm list --output none az vm list --output none
- name: Run Azure PowerShell - name: Run Azure PowerShell
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |

View File

@@ -11,14 +11,14 @@ jobs:
runs-on: windows-latest runs-on: windows-latest
steps: steps:
- name: Checkout from PR branch - name: Checkout from PR branch
uses: actions/checkout@v4 uses: actions/checkout@v2
with: with:
repository: ${{ github.event.pull_request.head.repo.full_name }} repository: ${{ github.event.pull_request.head.repo.full_name }}
ref: ${{ github.event.pull_request.head.ref }} ref: ${{ github.event.pull_request.head.ref }}
# Using 16.x version as an example # Using 16.x version as an example
- name: Set Node.js 16.x for GitHub Action - name: Set Node.js 16.x for GitHub Action
uses: actions/setup-node@v4 uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 16.x

View File

@@ -1,5 +1,3 @@
name: Build and Test
on: on:
pull_request: pull_request:
branches: branches:
@@ -18,10 +16,10 @@ jobs:
steps: steps:
- name: 'Checking out repo code' - name: 'Checking out repo code'
uses: actions/checkout@v4 uses: actions/checkout@v2
- name: Set Node.js 16.x for GitHub Action - name: Set Node.js 16.x for GitHub Action
uses: actions/setup-node@v4 uses: actions/setup-node@v1
with: with:
node-version: 16.x node-version: 16.x

View File

@@ -14,13 +14,23 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v2
with:
# We must fetch at least the immediate parents so that if this is
# a pull request then we can checkout the head.
fetch-depth: 2
# If this run was triggered by a pull request event, then checkout
# the head of the pull request instead of the merge commit.
- run: git checkout HEAD^2
if: ${{ github.event_name == 'pull_request' }}
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v2 uses: github/codeql-action/init@v2
with: # Override language selection by uncommenting this and choosing your languages
languages: javascript # with:
# languages: go, javascript, csharp, python, cpp, java
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below) # If this step fails, then you should remove it and run the build manually (see below)

View File

@@ -14,7 +14,7 @@ jobs:
# Steps represent a sequence of tasks that will be executed as part of the job # Steps represent a sequence of tasks that will be executed as part of the job
steps: steps:
- uses: actions/stale@v8 - uses: actions/stale@v3
name: Setting issue as idle name: Setting issue as idle
with: with:
repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token: ${{ secrets.GITHUB_TOKEN }}
@@ -25,7 +25,7 @@ jobs:
operations-per-run: 100 operations-per-run: 100
exempt-issue-labels: 'backlog' exempt-issue-labels: 'backlog'
- uses: actions/stale@v8 - uses: actions/stale@v3
name: Setting PR as idle name: Setting PR as idle
with: with:
repo-token: ${{ secrets.GITHUB_TOKEN }} repo-token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -7,9 +7,9 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v2
- name: Use Node.js - name: Use Node.js
uses: actions/setup-node@v4 uses: actions/setup-node@v3
with: with:
node-version: 16.x node-version: 16.x
- name: Run Markdownlint - name: Run Markdownlint

View File

@@ -235,7 +235,7 @@ jobs:
az account show az account show
- name: Azure PowerShell script - name: Azure PowerShell script
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -323,7 +323,7 @@ jobs:
az account show az account show
- name: Azure PowerShell script - name: Azure PowerShell script
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -394,7 +394,7 @@ jobs:
az account show az account show
- name: Azure PowerShell script - name: Azure PowerShell script
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -461,7 +461,7 @@ jobs:
az account show az account show
- name: Azure PowerShell script - name: Azure PowerShell script
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -549,7 +549,7 @@ jobs:
az account show az account show
- name: Run Azure PowerShell - name: Run Azure PowerShell
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |
@@ -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). 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 ```yaml
- name: Azure CLI script - name: Azure CLI script
uses: azure/CLI@v1 uses: azure/CLI@v1
@@ -573,7 +570,7 @@ This action doesn't implement ```az logout``` by default at the end of execution
az account clear az account clear
- name: Azure PowerShell script - name: Azure PowerShell script
uses: azure/powershell@v1 uses: azure/powershell@v1.2.0
with: with:
azPSVersion: "latest" azPSVersion: "latest"
inlineScript: | inlineScript: |

View File

@@ -74,29 +74,16 @@ describe("LoginConfig Test", () => {
await testCreds(creds1); await testCreds(creds1);
}); });
test('initialize with creds, lack of subscriptionId, but allowNoSubscriptionsLogin=true', async () => { test('initialize with creds, lack of subscriptionId', async () => {
let creds1 = { let creds1 = {
'clientId': 'client-id', 'clientId': 'client-id',
'clientSecret': 'client-secret', 'clientSecret': 'client-secret',
'tenantId': 'tenant-id', 'tenantId': 'tenant-id',
// 'subscriptionId': 'subscription-id' // 'subscriptionId': 'subscription-id'
} }
setEnv('environment', 'azurecloud'); await testCreds(creds1);
setEnv('enable-AzPSSession', 'true');
setEnv('allow-no-subscriptions', 'true');
setEnv('auth-type', 'SERVICE_PRINCIPAL');
setEnv('creds', JSON.stringify(creds1));
let loginConfig = new LoginConfig();
await loginConfig.initialize();
expect(loginConfig.environment).toBe("azurecloud");
expect(loginConfig.enableAzPSSession).toBeTruthy();
expect(loginConfig.allowNoSubscriptionsLogin).toBeTruthy();
expect(loginConfig.authType).toBe("SERVICE_PRINCIPAL");
expect(loginConfig.servicePrincipalId).toBe("client-id");
expect(loginConfig.servicePrincipalSecret).toBe("client-secret");
expect(loginConfig.tenantId).toBe("tenant-id");
expect(loginConfig.subscriptionId).toBe("");
}); });
test('initialize with creds', async () => { test('initialize with creds', async () => {

View File

@@ -1,92 +1,92 @@
import * as os from 'os'; import * as os from 'os';
import { AzPSLogin } from '../../src/PowerShell/AzPSLogin'; import { AzPSLogin } from '../../src/PowerShell/AzPSLogin';
import { LoginConfig } from '../../src/common/LoginConfig'; import { LoginConfig } from '../../src/common/LoginConfig';
import { AzPSConstants, AzPSUtils } from '../../src/PowerShell/AzPSUtils'; import AzPSConstants from '../../src/PowerShell/AzPSConstants';
let azpsLogin: AzPSLogin; let azpsLogin: AzPSLogin;
jest.setTimeout(30000); jest.setTimeout(30000);
beforeAll(() => { beforeAll(() => {
var loginConfig = new LoginConfig(); var loginConfig = new LoginConfig();
loginConfig.servicePrincipalId = "servicePrincipalID"; loginConfig.servicePrincipalId = "servicePrincipalID";
loginConfig.servicePrincipalSecret = "servicePrincipalSecret"; loginConfig.servicePrincipalSecret = "servicePrincipalSecret";
loginConfig.tenantId = "tenantId"; loginConfig.tenantId = "tenantId";
loginConfig.subscriptionId = "subscriptionId"; loginConfig.subscriptionId = "subscriptionId";
azpsLogin = new AzPSLogin(loginConfig); azpsLogin = new AzPSLogin(loginConfig);
}); });
afterEach(() => { afterEach(() => {
jest.restoreAllMocks(); jest.restoreAllMocks();
}); });
describe('Testing login', () => { describe('Testing login', () => {
let loginSpy; let loginSpy;
beforeEach(() => { beforeEach(() => {
loginSpy = jest.spyOn(azpsLogin, 'login'); loginSpy = jest.spyOn(azpsLogin, 'login');
}); });
test('ServicePrincipal login should pass', async () => { test('ServicePrincipal login should pass', async () => {
loginSpy.mockImplementationOnce(() => Promise.resolve()); loginSpy.mockImplementationOnce(() => Promise.resolve());
await azpsLogin.login(); await azpsLogin.login();
expect(loginSpy).toHaveBeenCalled(); expect(loginSpy).toHaveBeenCalled();
}); });
}); });
describe('Testing set module path', () => { describe('Testing set module path', () => {
test('setDefaultPSModulePath should work', () => { test('setDefaultPSModulePath should work', () => {
AzPSUtils.setPSModulePathForGitHubRunner(); azpsLogin.setPSModulePathForGitHubRunner();
const runner: string = process.env.RUNNER_OS || os.type(); const runner: string = process.env.RUNNER_OS || os.type();
if(runner.toLowerCase() === "linux"){ if(runner.toLowerCase() === "linux"){
expect(process.env.PSModulePath).toContain(AzPSConstants.DEFAULT_AZ_PATH_ON_LINUX); expect(process.env.PSModulePath).toContain(AzPSConstants.DEFAULT_AZ_PATH_ON_LINUX);
} }
if(runner.toLowerCase().startsWith("windows")){ if(runner.toLowerCase().startsWith("windows")){
expect(process.env.PSModulePath).toContain(AzPSConstants.DEFAULT_AZ_PATH_ON_WINDOWS); expect(process.env.PSModulePath).toContain(AzPSConstants.DEFAULT_AZ_PATH_ON_WINDOWS);
} }
}); });
}); });
describe('Testing runPSScript', () => { describe('Testing runPSScript', () => {
test('Get PowerShell Version', async () => { test('Get PowerShell Version', async () => {
let script = `try { let script = `try {
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue" $WarningPreference = "SilentlyContinue"
$output = @{} $output = @{}
$output['Success'] = $true $output['Success'] = $true
$output['Result'] = $PSVersionTable.PSVersion.ToString() $output['Result'] = $PSVersionTable.PSVersion.ToString()
} }
catch { catch {
$output['Success'] = $false $output['Success'] = $false
$output['Error'] = $_.exception.Message $output['Error'] = $_.exception.Message
} }
return ConvertTo-Json $output`; return ConvertTo-Json $output`;
let psVersion: string = await AzPSUtils.runPSScript(script); let psVersion: string = await AzPSLogin.runPSScript(script);
expect(psVersion === null).toBeFalsy(); expect(psVersion === null).toBeFalsy();
}); });
test('Get PowerShell Version with Wrong Name', async () => { test('Get PowerShell Version with Wrong Name', async () => {
let script = `try { let script = `try {
$ErrorActionPreference = "Stop" $ErrorActionPreference = "Stop"
$WarningPreference = "SilentlyContinue" $WarningPreference = "SilentlyContinue"
$output = @{} $output = @{}
$output['Success'] = $true $output['Success'] = $true
$output['Result'] = $PSVersionTableWrongName.PSVersion.ToString() $output['Result'] = $PSVersionTableWrongName.PSVersion.ToString()
} }
catch { catch {
$output['Success'] = $false $output['Success'] = $false
$output['Error'] = $_.exception.Message $output['Error'] = $_.exception.Message
} }
return ConvertTo-Json $output`; return ConvertTo-Json $output`;
try{ try{
await AzPSUtils.runPSScript(script); await AzPSLogin.runPSScript(script);
throw new Error("The last step should fail."); throw new Error("The last step should fail.");
}catch(error){ }catch(error){
expect(error.message.includes("Azure PowerShell login failed with error: You cannot call a method on a null-valued expression.")).toBeTruthy(); expect(error.message.includes("Azure PowerShell login failed with error: You cannot call a method on a null-valued expression.")).toBeTruthy();
} }
}); });
}); });

View File

@@ -1,153 +1,153 @@
import AzPSSCriptBuilder from "../../src/PowerShell/AzPSScriptBuilder"; import AzPSSCriptBuilder from "../../src/PowerShell/AzPSScriptBuilder";
import { LoginConfig } from "../../src/common/LoginConfig"; import { LoginConfig } from "../../src/common/LoginConfig";
describe("Getting AzLogin PS script", () => { describe("Getting AzLogin PS script", () => {
function setEnv(name: string, value: string) { function setEnv(name: string, value: string) {
process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] = value; process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] = value;
} }
function cleanEnv() { function cleanEnv() {
for (const envKey in process.env) { for (const envKey in process.env) {
if (envKey.startsWith('INPUT_')) { if (envKey.startsWith('INPUT_')) {
delete process.env[envKey] delete process.env[envKey]
} }
} }
} }
beforeEach(() => { beforeEach(() => {
cleanEnv(); cleanEnv();
}); });
test('getImportLatestModuleScript', () => { test('getImportLatestModuleScript', () => {
expect(AzPSSCriptBuilder.getImportLatestModuleScript("TestModule")).toContain("(Get-Module -Name 'TestModule' -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1).Path"); expect(AzPSSCriptBuilder.getImportLatestModuleScript("TestModule")).toContain("(Get-Module -Name 'TestModule' -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1).Path");
expect(AzPSSCriptBuilder.getImportLatestModuleScript("TestModule")).toContain("Import-Module -Name $latestModulePath"); expect(AzPSSCriptBuilder.getImportLatestModuleScript("TestModule")).toContain("Import-Module -Name $latestModulePath");
}); });
test('getAzPSLoginScript for SP+secret with allowNoSubscriptionsLogin=true', () => { test('getAzPSLoginScript for SP+secret with allowNoSubscriptionsLogin=true', () => {
setEnv('environment', 'azurecloud'); setEnv('environment', 'azurecloud');
setEnv('enable-AzPSSession', 'true'); setEnv('enable-AzPSSession', 'true');
setEnv('allow-no-subscriptions', 'true'); setEnv('allow-no-subscriptions', 'true');
setEnv('auth-type', 'SERVICE_PRINCIPAL'); setEnv('auth-type', 'SERVICE_PRINCIPAL');
let creds = { let creds = {
'clientId': 'client-id', 'clientId': 'client-id',
'clientSecret': "client-secret", 'clientSecret': "client-secret",
'tenantId': 'tenant-id', 'tenantId': 'tenant-id',
'subscriptionId': 'subscription-id' 'subscriptionId': 'subscription-id'
} }
setEnv('creds', JSON.stringify(creds)); setEnv('creds', JSON.stringify(creds));
let loginConfig = new LoginConfig(); let loginConfig = new LoginConfig();
loginConfig.initialize(); loginConfig.initialize();
return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => { return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => {
expect(loginScript.includes("$psLoginSecrets = ConvertTo-SecureString 'client-secret' -AsPlainText -Force; $psLoginCredential = New-Object System.Management.Automation.PSCredential('client-id', $psLoginSecrets); Connect-AzAccount -ServicePrincipal -Environment 'azurecloud' -Tenant 'tenant-id' -Subscription 'subscription-id' -Credential $psLoginCredential | out-null;")).toBeTruthy(); expect(loginScript.includes("Clear-AzContext -Scope Process; Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue; $psLoginSecrets = ConvertTo-SecureString 'client-secret' -AsPlainText -Force; $psLoginCredential = New-Object System.Management.Automation.PSCredential('client-id', $psLoginSecrets); Connect-AzAccount -ServicePrincipal -Environment 'azurecloud' -Tenant 'tenant-id' -Subscription 'subscription-id' -Credential $psLoginCredential | out-null;")).toBeTruthy();
expect(loginMethod).toBe('service principal with secret'); expect(loginMethod).toBe('service principal with secret');
}); });
}); });
test('getAzPSLoginScript for SP+secret with allowNoSubscriptionsLogin=true, secret with single-quote', () => { test('getAzPSLoginScript for SP+secret with allowNoSubscriptionsLogin=true, secret with single-quote', () => {
setEnv('environment', 'azurecloud'); setEnv('environment', 'azurecloud');
setEnv('enable-AzPSSession', 'true'); setEnv('enable-AzPSSession', 'true');
setEnv('allow-no-subscriptions', 'true'); setEnv('allow-no-subscriptions', 'true');
setEnv('auth-type', 'SERVICE_PRINCIPAL'); setEnv('auth-type', 'SERVICE_PRINCIPAL');
let creds = { let creds = {
'clientId': 'client-id', 'clientId': 'client-id',
'clientSecret': "client-se'cret", 'clientSecret': "client-se'cret",
'tenantId': 'tenant-id', 'tenantId': 'tenant-id',
'subscriptionId': 'subscription-id' 'subscriptionId': 'subscription-id'
} }
setEnv('creds', JSON.stringify(creds)); setEnv('creds', JSON.stringify(creds));
let loginConfig = new LoginConfig(); let loginConfig = new LoginConfig();
loginConfig.initialize(); loginConfig.initialize();
return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => { return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => {
expect(loginScript.includes("$psLoginSecrets = ConvertTo-SecureString 'client-se''cret' -AsPlainText -Force; $psLoginCredential = New-Object System.Management.Automation.PSCredential('client-id', $psLoginSecrets); Connect-AzAccount -ServicePrincipal -Environment 'azurecloud' -Tenant 'tenant-id' -Subscription 'subscription-id' -Credential $psLoginCredential | out-null;")).toBeTruthy(); expect(loginScript.includes("Clear-AzContext -Scope Process; Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue; $psLoginSecrets = ConvertTo-SecureString 'client-se''cret' -AsPlainText -Force; $psLoginCredential = New-Object System.Management.Automation.PSCredential('client-id', $psLoginSecrets); Connect-AzAccount -ServicePrincipal -Environment 'azurecloud' -Tenant 'tenant-id' -Subscription 'subscription-id' -Credential $psLoginCredential | out-null;")).toBeTruthy();
expect(loginMethod).toBe('service principal with secret'); expect(loginMethod).toBe('service principal with secret');
}); });
}); });
test('getAzPSLoginScript for SP+secret with allowNoSubscriptionsLogin=false', () => { test('getAzPSLoginScript for SP+secret with allowNoSubscriptionsLogin=false', () => {
setEnv('environment', 'azurecloud'); setEnv('environment', 'azurecloud');
setEnv('enable-AzPSSession', 'true'); setEnv('enable-AzPSSession', 'true');
setEnv('allow-no-subscriptions', 'false'); // same as true setEnv('allow-no-subscriptions', 'false'); // same as true
setEnv('auth-type', 'SERVICE_PRINCIPAL'); setEnv('auth-type', 'SERVICE_PRINCIPAL');
let creds = { let creds = {
'clientId': 'client-id', 'clientId': 'client-id',
'clientSecret': 'client-secret', 'clientSecret': 'client-secret',
'tenantId': 'tenant-id', 'tenantId': 'tenant-id',
'subscriptionId': 'subscription-id' 'subscriptionId': 'subscription-id'
} }
setEnv('creds', JSON.stringify(creds)); setEnv('creds', JSON.stringify(creds));
let loginConfig = new LoginConfig(); let loginConfig = new LoginConfig();
loginConfig.initialize(); loginConfig.initialize();
return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => { return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => {
expect(loginScript.includes("$psLoginSecrets = ConvertTo-SecureString 'client-secret' -AsPlainText -Force; $psLoginCredential = New-Object System.Management.Automation.PSCredential('client-id', $psLoginSecrets); Connect-AzAccount -ServicePrincipal -Environment 'azurecloud' -Tenant 'tenant-id' -Subscription 'subscription-id' -Credential $psLoginCredential | out-null;")).toBeTruthy(); expect(loginScript.includes("Clear-AzContext -Scope Process; Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue; $psLoginSecrets = ConvertTo-SecureString 'client-secret' -AsPlainText -Force; $psLoginCredential = New-Object System.Management.Automation.PSCredential('client-id', $psLoginSecrets); Connect-AzAccount -ServicePrincipal -Environment 'azurecloud' -Tenant 'tenant-id' -Subscription 'subscription-id' -Credential $psLoginCredential | out-null;")).toBeTruthy();
expect(loginMethod).toBe('service principal with secret'); expect(loginMethod).toBe('service principal with secret');
}); });
}); });
test('getAzPSLoginScript for OIDC', () => { test('getAzPSLoginScript for OIDC', () => {
setEnv('environment', 'azurecloud'); setEnv('environment', 'azurecloud');
setEnv('enable-AzPSSession', 'true'); setEnv('enable-AzPSSession', 'true');
setEnv('allow-no-subscriptions', 'false'); setEnv('allow-no-subscriptions', 'false');
setEnv('tenant-id', 'tenant-id'); setEnv('tenant-id', 'tenant-id');
setEnv('subscription-id', 'subscription-id'); setEnv('subscription-id', 'subscription-id');
setEnv('client-id', 'client-id'); setEnv('client-id', 'client-id');
setEnv('auth-type', 'SERVICE_PRINCIPAL'); setEnv('auth-type', 'SERVICE_PRINCIPAL');
let loginConfig = new LoginConfig(); let loginConfig = new LoginConfig();
loginConfig.initialize(); loginConfig.initialize();
jest.spyOn(loginConfig, 'getFederatedToken').mockImplementation(async () => {loginConfig.federatedToken = "fake-token";}); jest.spyOn(loginConfig, 'getFederatedToken').mockImplementation(async () => {loginConfig.federatedToken = "fake-token";});
return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => { return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => {
expect(loginScript.includes("Connect-AzAccount -ServicePrincipal -Environment 'azurecloud' -Tenant 'tenant-id' -Subscription 'subscription-id' -ApplicationId 'client-id' -FederatedToken 'fake-token' | out-null;")).toBeTruthy(); expect(loginScript.includes("Clear-AzContext -Scope Process; Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue; Connect-AzAccount -ServicePrincipal -Environment 'azurecloud' -Tenant 'tenant-id' -Subscription 'subscription-id' -ApplicationId 'client-id' -FederatedToken 'fake-token' | out-null;")).toBeTruthy();
expect(loginMethod).toBe('OIDC'); expect(loginMethod).toBe('OIDC');
}); });
}); });
test('getAzPSLoginScript for System MI', () => { test('getAzPSLoginScript for System MI', () => {
setEnv('environment', 'azurecloud'); setEnv('environment', 'azurecloud');
setEnv('enable-AzPSSession', 'true'); setEnv('enable-AzPSSession', 'true');
setEnv('allow-no-subscriptions', 'false'); setEnv('allow-no-subscriptions', 'false');
setEnv('subscription-id', 'subscription-id'); setEnv('subscription-id', 'subscription-id');
setEnv('auth-type', 'IDENTITY'); setEnv('auth-type', 'IDENTITY');
let loginConfig = new LoginConfig(); let loginConfig = new LoginConfig();
loginConfig.initialize(); loginConfig.initialize();
return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => { return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => {
expect(loginScript.includes("Connect-AzAccount -Identity -Environment 'azurecloud' -Subscription 'subscription-id' | out-null;")).toBeTruthy(); expect(loginScript.includes("Clear-AzContext -Scope Process; Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue; Connect-AzAccount -Identity -Environment 'azurecloud' -Subscription 'subscription-id' | out-null;")).toBeTruthy();
expect(loginMethod).toBe('system-assigned managed identity'); expect(loginMethod).toBe('system-assigned managed identity');
}); });
}); });
test('getAzPSLoginScript for System MI without subscription id', () => { test('getAzPSLoginScript for System MI without subscription id', () => {
setEnv('environment', 'azurecloud'); setEnv('environment', 'azurecloud');
setEnv('enable-AzPSSession', 'true'); setEnv('enable-AzPSSession', 'true');
setEnv('allow-no-subscriptions', 'false'); setEnv('allow-no-subscriptions', 'false');
// setEnv('subscription-id', 'subscription-id'); // setEnv('subscription-id', 'subscription-id');
setEnv('auth-type', 'IDENTITY'); setEnv('auth-type', 'IDENTITY');
let loginConfig = new LoginConfig(); let loginConfig = new LoginConfig();
loginConfig.initialize(); loginConfig.initialize();
return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => { return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => {
expect(loginScript.includes("Connect-AzAccount -Identity -Environment 'azurecloud' | out-null;")).toBeTruthy(); expect(loginScript.includes("Clear-AzContext -Scope Process; Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue; Connect-AzAccount -Identity -Environment 'azurecloud' | out-null;")).toBeTruthy();
expect(loginMethod).toBe('system-assigned managed identity'); expect(loginMethod).toBe('system-assigned managed identity');
}); });
}); });
test('getAzPSLoginScript for user-assigned MI', () => { test('getAzPSLoginScript for user-assigned MI', () => {
setEnv('environment', 'azurecloud'); setEnv('environment', 'azurecloud');
setEnv('enable-AzPSSession', 'true'); setEnv('enable-AzPSSession', 'true');
setEnv('allow-no-subscriptions', 'true'); setEnv('allow-no-subscriptions', 'true');
setEnv('auth-type', 'IDENTITY'); setEnv('auth-type', 'IDENTITY');
setEnv('client-id', 'client-id'); setEnv('client-id', 'client-id');
let loginConfig = new LoginConfig(); let loginConfig = new LoginConfig();
loginConfig.initialize(); loginConfig.initialize();
return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => { return AzPSSCriptBuilder.getAzPSLoginScript(loginConfig).then(([loginMethod, loginScript]) => {
expect(loginScript.includes("Connect-AzAccount -Identity -Environment 'azurecloud' -AccountId 'client-id' | out-null;")).toBeTruthy(); expect(loginScript.includes("Clear-AzContext -Scope Process; Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue; Connect-AzAccount -Identity -Environment 'azurecloud' -AccountId 'client-id' | out-null;")).toBeTruthy();
expect(loginMethod).toBe('user-assigned managed identity'); expect(loginMethod).toBe('user-assigned managed identity');
}); });
}); });
}); });

View File

@@ -39,6 +39,4 @@ branding:
color: 'blue' color: 'blue'
runs: runs:
using: 'node16' using: 'node16'
pre: 'lib/cleanup.js'
main: 'lib/main.js' main: 'lib/main.js'
post: 'lib/cleanup.js'

View File

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

View File

@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class AzPSConstants {
}
exports.default = 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";

View File

@@ -1,59 +1,126 @@
"use strict"; "use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k; if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k); var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } }; desc = { enumerable: true, get: function() { return m[k]; } };
} }
Object.defineProperty(o, k2, desc); Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) { }) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k; if (k2 === undefined) k2 = k;
o[k2] = m[k]; o[k2] = m[k];
})); }));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v }); Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) { }) : function(o, v) {
o["default"] = v; o["default"] = v;
}); });
var __importStar = (this && this.__importStar) || function (mod) { var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod); __setModuleDefault(result, mod);
return result; return result;
}; };
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } 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 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); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importDefault = (this && this.__importDefault) || function (mod) { var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.AzPSLogin = void 0; exports.AzPSLogin = void 0;
const core = __importStar(require("@actions/core")); const core = __importStar(require("@actions/core"));
const AzPSScriptBuilder_1 = __importDefault(require("./AzPSScriptBuilder")); const exec = __importStar(require("@actions/exec"));
const AzPSUtils_1 = require("./AzPSUtils"); const io = __importStar(require("@actions/io"));
class AzPSLogin { const os = __importStar(require("os"));
constructor(loginConfig) { const path = __importStar(require("path"));
this.loginConfig = loginConfig; const AzPSScriptBuilder_1 = __importDefault(require("./AzPSScriptBuilder"));
} const AzPSConstants_1 = __importDefault(require("./AzPSConstants"));
login() { class AzPSLogin {
return __awaiter(this, void 0, void 0, function* () { constructor(loginConfig) {
core.info(`Running Azure PowerShell Login.`); this.loginConfig = loginConfig;
AzPSUtils_1.AzPSUtils.setPSModulePathForGitHubRunner(); }
yield AzPSUtils_1.AzPSUtils.importLatestAzAccounts(); login() {
const [loginMethod, loginScript] = yield AzPSScriptBuilder_1.default.getAzPSLoginScript(this.loginConfig); return __awaiter(this, void 0, void 0, function* () {
core.info(`Attempting Azure PowerShell login by using ${loginMethod}...`); core.info(`Running Azure PowerShell Login.`);
core.debug(`Azure PowerShell Login Script: ${loginScript}`); this.setPSModulePathForGitHubRunner();
yield AzPSUtils_1.AzPSUtils.runPSScript(loginScript); yield this.importLatestAzAccounts();
console.log(`Running Azure PowerShell Login successfully.`); 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 AzPSLogin.runPSScript(loginScript);
exports.AzPSLogin = AzPSLogin; console.log(`Running Azure PowerShell Login successfully.`);
});
}
setPSModulePathForGitHubRunner() {
const runner = process.env.RUNNER_OS || os.type();
switch (runner.toLowerCase()) {
case "linux":
this.pushPSModulePath(AzPSConstants_1.default.DEFAULT_AZ_PATH_ON_LINUX);
break;
case "windows":
case "windows_nt":
this.pushPSModulePath(AzPSConstants_1.default.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;
}
}
pushPSModulePath(psModulePath) {
process.env.PSModulePath = `${psModulePath}${path.delimiter}${process.env.PSModulePath}`;
core.debug(`Set PSModulePath as ${process.env.PSModulePath}`);
}
importLatestAzAccounts() {
return __awaiter(this, void 0, void 0, function* () {
let importLatestAccountsScript = AzPSScriptBuilder_1.default.getImportLatestModuleScript(AzPSConstants_1.default.AzAccounts);
core.debug(`The script to import the latest Az.Accounts: ${importLatestAccountsScript}`);
let azAccountsPath = yield AzPSLogin.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_1.default.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.AzPSLogin = AzPSLogin;

View File

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

View File

@@ -1,119 +0,0 @@
"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 +0,0 @@
"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();

View File

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

View File

@@ -1,69 +0,0 @@
"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;

View File

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

View File

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

View File

@@ -1,17 +1,17 @@
@ECHO off @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\import-local\fixtures\cli.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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\jest\bin\jest.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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\js-yaml\bin\js-yaml.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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\jsesc\bin\jsesc" %* 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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\json5\lib\cli.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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %* 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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\package-lock\bin\package-lock.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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\@babel\parser\bin\babel-parser.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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\resolve\bin\resolve" %* 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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\ts-jest\cli.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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsc" %* 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 @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsserver" %* endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\typescript\bin\tsserver" %*

8
node_modules/.package-lock.json generated vendored
View File

@@ -1117,11 +1117,11 @@
"dev": true "dev": true
}, },
"node_modules/actions-secret-parser": { "node_modules/actions-secret-parser": {
"version": "1.0.4", "version": "1.0.3",
"resolved": "https://registry.npmjs.org/actions-secret-parser/-/actions-secret-parser-1.0.4.tgz", "resolved": "https://registry.npmjs.org/actions-secret-parser/-/actions-secret-parser-1.0.3.tgz",
"integrity": "sha512-gDAB8GK2Vj9CN5r97DZlmpxqrMcpAGKGWiIY3hpFhJMieLpl3K3ocVR49/Q4ANaA5a/2wNRE3Qng+x0K8mkmkQ==", "integrity": "sha512-+iGlMSsE/cbxDaEZlqR0NUjn35DckMYsdYFwVeZ7JRbtyO/AiBKnaScKkzkHSoiZ4nEPTdIHtMpRGVgoeVYX+A==",
"dependencies": { "dependencies": {
"@actions/core": "^1.1.10", "@actions/core": "^1.1.3",
"jsonpath": "^1.0.2", "jsonpath": "^1.0.2",
"xmldom": "^0.1.27", "xmldom": "^0.1.27",
"xpath": "0.0.27" "xpath": "0.0.27"

View File

@@ -1,17 +1,17 @@
@ECHO off @ECHO off
GOTO start GOTO start
:find_dp0 :find_dp0
SET dp0=%~dp0 SET dp0=%~dp0
EXIT /b EXIT /b
:start :start
SETLOCAL SETLOCAL
CALL :find_dp0 CALL :find_dp0
IF EXIST "%dp0%\node.exe" ( IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe" SET "_prog=%dp0%\node.exe"
) ELSE ( ) ELSE (
SET "_prog=node" SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;% SET PATHEXT=%PATHEXT:;.JS;=;%
) )
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\uuid\dist\bin\uuid" %* 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 //this will affect all the git repos
git config --global core.excludesfile ~/.gitignore git config --global core.excludesfile ~/.gitignore
//update files since .ignore won't if already tracked //update files since .ignore won't if already tracked
git rm --cached <file> git rm --cached <file>
# Compiled source # # Compiled source #
################### ###################
*.com *.com
*.class *.class
*.dll *.dll
*.exe *.exe
*.o *.o
*.so *.so
# Packages # # Packages #
############ ############
# it's better to unpack these files and commit the raw source # it's better to unpack these files and commit the raw source
# git has its own built in compression methods # git has its own built in compression methods
*.7z *.7z
*.dmg *.dmg
*.gz *.gz
*.iso *.iso
*.jar *.jar
*.rar *.rar
*.tar *.tar
*.zip *.zip
# Logs and databases # # Logs and databases #
###################### ######################
*.log *.log
*.sql *.sql
*.sqlite *.sqlite
# OS generated files # # OS generated files #
###################### ######################
.DS_Store .DS_Store
.DS_Store? .DS_Store?
._* ._*
.Spotlight-V100 .Spotlight-V100
.Trashes .Trashes
# Icon? # Icon?
ehthumbs.db ehthumbs.db
Thumbs.db Thumbs.db
.cache .cache
.project .project
.settings .settings
.tmproj .tmproj
*.esproj *.esproj
nbproject nbproject
# Numerous always-ignore extensions # # Numerous always-ignore extensions #
##################################### #####################################
*.diff *.diff
*.err *.err
*.orig *.orig
*.rej *.rej
*.swn *.swn
*.swo *.swo
*.swp *.swp
*.vi *.vi
*~ *~
*.sass-cache *.sass-cache
*.grunt *.grunt
*.tmp *.tmp
# Dreamweaver added files # # Dreamweaver added files #
########################### ###########################
_notes _notes
dwsync.xml dwsync.xml
# Komodo # # Komodo #
########################### ###########################
*.komodoproject *.komodoproject
.komodotools .komodotools
# Node # # Node #
##################### #####################
node_modules node_modules
# Bower # # Bower #
##################### #####################
bower_components bower_components
# Folders to ignore # # Folders to ignore #
##################### #####################
.hg .hg
.svn .svn
.CVS .CVS
intermediate intermediate
publish publish
.idea .idea
.graphics .graphics
_test _test
_archive _archive
uploads uploads
tmp tmp
# Vim files to ignore # # Vim files to ignore #
####################### #######################
.VimballRecord .VimballRecord
.netrwhist .netrwhist
bundle.* bundle.*
_demo _demo

View File

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

View File

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

View File

@@ -1,28 +1,28 @@
import { ValueError } from '../errors/index'; import { ValueError } from '../errors/index';
import * as Types from '../typebox'; import * as Types from '../typebox';
export declare type CheckFunction = (value: unknown) => boolean; export declare type CheckFunction = (value: unknown) => boolean;
export declare class TypeCheck<T extends Types.TSchema> { export declare class TypeCheck<T extends Types.TSchema> {
private readonly schema; private readonly schema;
private readonly references; private readonly references;
private readonly checkFunc; private readonly checkFunc;
private readonly code; private readonly code;
constructor(schema: T, references: Types.TSchema[], checkFunc: CheckFunction, code: string); constructor(schema: T, references: Types.TSchema[], checkFunc: CheckFunction, code: string);
/** Returns the generated validation code used to validate this type. */ /** Returns the generated validation code used to validate this type. */
Code(): string; Code(): string;
/** Returns an iterator for each error in this value. */ /** Returns an iterator for each error in this value. */
Errors(value: unknown): IterableIterator<ValueError>; Errors(value: unknown): IterableIterator<ValueError>;
/** Returns true if the value matches the given type. */ /** Returns true if the value matches the given type. */
Check(value: unknown): value is Types.Static<T>; Check(value: unknown): value is Types.Static<T>;
} }
export declare namespace Property { export declare namespace Property {
function Check(propertyName: string): boolean; function Check(propertyName: string): boolean;
} }
export declare class TypeCompilerUnknownTypeError extends Error { export declare class TypeCompilerUnknownTypeError extends Error {
readonly schema: Types.TSchema; readonly schema: Types.TSchema;
constructor(schema: Types.TSchema); constructor(schema: Types.TSchema);
} }
/** Compiles Types for Runtime Type Checking */ /** Compiles Types for Runtime Type Checking */
export declare namespace TypeCompiler { export declare namespace TypeCompiler {
/** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */ /** 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>; function Compile<T extends Types.TSchema>(schema: T, references?: Types.TSchema[]): TypeCheck<T>;
} }

View File

@@ -1,409 +1,409 @@
"use strict"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/compiler @sinclair/typebox/compiler
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeCompiler = exports.TypeCompilerUnknownTypeError = exports.Property = exports.TypeCheck = void 0; exports.TypeCompiler = exports.TypeCompilerUnknownTypeError = exports.Property = exports.TypeCheck = void 0;
const index_1 = require("../errors/index"); const index_1 = require("../errors/index");
const index_2 = require("../guard/index"); const index_2 = require("../guard/index");
const index_3 = require("../format/index"); const index_3 = require("../format/index");
const Types = require("../typebox"); const Types = require("../typebox");
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// TypeCheck // TypeCheck
// ------------------------------------------------------------------- // -------------------------------------------------------------------
class TypeCheck { class TypeCheck {
constructor(schema, references, checkFunc, code) { constructor(schema, references, checkFunc, code) {
this.schema = schema; this.schema = schema;
this.references = references; this.references = references;
this.checkFunc = checkFunc; this.checkFunc = checkFunc;
this.code = code; this.code = code;
} }
/** Returns the generated validation code used to validate this type. */ /** Returns the generated validation code used to validate this type. */
Code() { Code() {
return this.code; return this.code;
} }
/** Returns an iterator for each error in this value. */ /** Returns an iterator for each error in this value. */
Errors(value) { Errors(value) {
return index_1.ValueErrors.Errors(this.schema, this.references, value); return index_1.ValueErrors.Errors(this.schema, this.references, value);
} }
/** Returns true if the value matches the given type. */ /** Returns true if the value matches the given type. */
Check(value) { Check(value) {
return this.checkFunc(value); return this.checkFunc(value);
} }
} }
exports.TypeCheck = TypeCheck; exports.TypeCheck = TypeCheck;
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// Property // Property
// ------------------------------------------------------------------- // -------------------------------------------------------------------
var Property; var Property;
(function (Property) { (function (Property) {
function DollarSign(code) { function DollarSign(code) {
return code === 36; return code === 36;
} }
function Underscore(code) { function Underscore(code) {
return code === 95; return code === 95;
} }
function Numeric(code) { function Numeric(code) {
return code >= 48 && code <= 57; return code >= 48 && code <= 57;
} }
function Alpha(code) { function Alpha(code) {
return (code >= 65 && code <= 90) || (code >= 97 && code <= 122); return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
} }
function Check(propertyName) { function Check(propertyName) {
if (propertyName.length === 0) if (propertyName.length === 0)
return false; return false;
{ {
const code = propertyName.charCodeAt(0); const code = propertyName.charCodeAt(0);
if (!(DollarSign(code) || Underscore(code) || Alpha(code))) { if (!(DollarSign(code) || Underscore(code) || Alpha(code))) {
return false; return false;
} }
} }
for (let i = 1; i < propertyName.length; i++) { for (let i = 1; i < propertyName.length; i++) {
const code = propertyName.charCodeAt(i); const code = propertyName.charCodeAt(i);
if (!(DollarSign(code) || Underscore(code) || Alpha(code) || Numeric(code))) { if (!(DollarSign(code) || Underscore(code) || Alpha(code) || Numeric(code))) {
return false; return false;
} }
} }
return true; return true;
} }
Property.Check = Check; Property.Check = Check;
})(Property = exports.Property || (exports.Property = {})); })(Property = exports.Property || (exports.Property = {}));
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// TypeCompiler // TypeCompiler
// ------------------------------------------------------------------- // -------------------------------------------------------------------
class TypeCompilerUnknownTypeError extends Error { class TypeCompilerUnknownTypeError extends Error {
constructor(schema) { constructor(schema) {
super('TypeCompiler: Unknown type'); super('TypeCompiler: Unknown type');
this.schema = schema; this.schema = schema;
} }
} }
exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError; exports.TypeCompilerUnknownTypeError = TypeCompilerUnknownTypeError;
/** Compiles Types for Runtime Type Checking */ /** Compiles Types for Runtime Type Checking */
var TypeCompiler; var TypeCompiler;
(function (TypeCompiler) { (function (TypeCompiler) {
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// Types // Types
// ------------------------------------------------------------------- // -------------------------------------------------------------------
function* Any(schema, value) { function* Any(schema, value) {
yield '(true)'; yield '(true)';
} }
function* Array(schema, value) { function* Array(schema, value) {
const expression = CreateExpression(schema.items, 'value'); const expression = CreateExpression(schema.items, 'value');
if (schema.minItems !== undefined) if (schema.minItems !== undefined)
yield `(${value}.length >= ${schema.minItems})`; yield `(${value}.length >= ${schema.minItems})`;
if (schema.maxItems !== undefined) if (schema.maxItems !== undefined)
yield `(${value}.length <= ${schema.maxItems})`; yield `(${value}.length <= ${schema.maxItems})`;
if (schema.uniqueItems !== undefined) if (schema.uniqueItems !== undefined)
yield `(new Set(${value}).size === ${value}.length)`; yield `(new Set(${value}).size === ${value}.length)`;
yield `(Array.isArray(${value}) && ${value}.every(value => ${expression}))`; yield `(Array.isArray(${value}) && ${value}.every(value => ${expression}))`;
} }
function* Boolean(schema, value) { function* Boolean(schema, value) {
yield `(typeof ${value} === 'boolean')`; yield `(typeof ${value} === 'boolean')`;
} }
function* Constructor(schema, value) { function* Constructor(schema, value) {
yield* Visit(schema.returns, `${value}.prototype`); yield* Visit(schema.returns, `${value}.prototype`);
} }
function* Function(schema, value) { function* Function(schema, value) {
yield `(typeof ${value} === 'function')`; yield `(typeof ${value} === 'function')`;
} }
function* Integer(schema, value) { function* Integer(schema, value) {
yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`; yield `(typeof ${value} === 'number' && Number.isInteger(${value}))`;
if (schema.multipleOf !== undefined) if (schema.multipleOf !== undefined)
yield `(${value} % ${schema.multipleOf} === 0)`; yield `(${value} % ${schema.multipleOf} === 0)`;
if (schema.exclusiveMinimum !== undefined) if (schema.exclusiveMinimum !== undefined)
yield `(${value} > ${schema.exclusiveMinimum})`; yield `(${value} > ${schema.exclusiveMinimum})`;
if (schema.exclusiveMaximum !== undefined) if (schema.exclusiveMaximum !== undefined)
yield `(${value} < ${schema.exclusiveMaximum})`; yield `(${value} < ${schema.exclusiveMaximum})`;
if (schema.minimum !== undefined) if (schema.minimum !== undefined)
yield `(${value} >= ${schema.minimum})`; yield `(${value} >= ${schema.minimum})`;
if (schema.maximum !== undefined) if (schema.maximum !== undefined)
yield `(${value} <= ${schema.maximum})`; yield `(${value} <= ${schema.maximum})`;
} }
function* Literal(schema, value) { function* Literal(schema, value) {
if (typeof schema.const === 'number' || typeof schema.const === 'boolean') { if (typeof schema.const === 'number' || typeof schema.const === 'boolean') {
yield `(${value} === ${schema.const})`; yield `(${value} === ${schema.const})`;
} }
else { else {
yield `(${value} === '${schema.const}')`; yield `(${value} === '${schema.const}')`;
} }
} }
function* Never(schema, value) { function* Never(schema, value) {
yield `(false)`; yield `(false)`;
} }
function* Null(schema, value) { function* Null(schema, value) {
yield `(${value} === null)`; yield `(${value} === null)`;
} }
function* Number(schema, value) { function* Number(schema, value) {
yield `(typeof ${value} === 'number')`; yield `(typeof ${value} === 'number')`;
if (schema.multipleOf !== undefined) if (schema.multipleOf !== undefined)
yield `(${value} % ${schema.multipleOf} === 0)`; yield `(${value} % ${schema.multipleOf} === 0)`;
if (schema.exclusiveMinimum !== undefined) if (schema.exclusiveMinimum !== undefined)
yield `(${value} > ${schema.exclusiveMinimum})`; yield `(${value} > ${schema.exclusiveMinimum})`;
if (schema.exclusiveMaximum !== undefined) if (schema.exclusiveMaximum !== undefined)
yield `(${value} < ${schema.exclusiveMaximum})`; yield `(${value} < ${schema.exclusiveMaximum})`;
if (schema.minimum !== undefined) if (schema.minimum !== undefined)
yield `(${value} >= ${schema.minimum})`; yield `(${value} >= ${schema.minimum})`;
if (schema.maximum !== undefined) if (schema.maximum !== undefined)
yield `(${value} <= ${schema.maximum})`; yield `(${value} <= ${schema.maximum})`;
} }
function* Object(schema, value) { function* Object(schema, value) {
yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`; yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
if (schema.minProperties !== undefined) if (schema.minProperties !== undefined)
yield `(Object.keys(${value}).length >= ${schema.minProperties})`; yield `(Object.keys(${value}).length >= ${schema.minProperties})`;
if (schema.maxProperties !== undefined) if (schema.maxProperties !== undefined)
yield `(Object.keys(${value}).length <= ${schema.maxProperties})`; yield `(Object.keys(${value}).length <= ${schema.maxProperties})`;
const propertyKeys = globalThis.Object.keys(schema.properties); const propertyKeys = globalThis.Object.keys(schema.properties);
if (schema.additionalProperties === false) { if (schema.additionalProperties === false) {
// Optimization: If the property key length matches the required keys length // Optimization: If the property key length matches the required keys length
// then we only need check that the values property key length matches that // 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 // of the property key length. This is because exhaustive testing for values
// will occur in subsequent property tests. // will occur in subsequent property tests.
if (schema.required && schema.required.length === propertyKeys.length) { if (schema.required && schema.required.length === propertyKeys.length) {
yield `(Object.keys(${value}).length === ${propertyKeys.length})`; yield `(Object.keys(${value}).length === ${propertyKeys.length})`;
} }
else { else {
const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`; const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `(Object.keys(${value}).every(key => ${keys}.includes(key)))`; yield `(Object.keys(${value}).every(key => ${keys}.includes(key)))`;
} }
} }
if (index_2.TypeGuard.TSchema(schema.additionalProperties)) { if (index_2.TypeGuard.TSchema(schema.additionalProperties)) {
const expression = CreateExpression(schema.additionalProperties, 'value[key]'); const expression = CreateExpression(schema.additionalProperties, 'value[key]');
const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`; const keys = `[${propertyKeys.map((key) => `'${key}'`).join(', ')}]`;
yield `(Object.keys(${value}).every(key => ${keys}.includes(key) || ${expression}))`; yield `(Object.keys(${value}).every(key => ${keys}.includes(key) || ${expression}))`;
} }
for (const propertyKey of propertyKeys) { for (const propertyKey of propertyKeys) {
const memberExpression = Property.Check(propertyKey) ? `${value}.${propertyKey}` : `${value}['${propertyKey}']`; const memberExpression = Property.Check(propertyKey) ? `${value}.${propertyKey}` : `${value}['${propertyKey}']`;
const propertySchema = schema.properties[propertyKey]; const propertySchema = schema.properties[propertyKey];
if (schema.required && schema.required.includes(propertyKey)) { if (schema.required && schema.required.includes(propertyKey)) {
yield* Visit(propertySchema, memberExpression); yield* Visit(propertySchema, memberExpression);
} }
else { else {
const expression = CreateExpression(propertySchema, memberExpression); const expression = CreateExpression(propertySchema, memberExpression);
yield `(${memberExpression} === undefined ? true : (${expression}))`; yield `(${memberExpression} === undefined ? true : (${expression}))`;
} }
} }
} }
function* Promise(schema, value) { function* Promise(schema, value) {
yield `(typeof value === 'object' && typeof ${value}.then === 'function')`; yield `(typeof value === 'object' && typeof ${value}.then === 'function')`;
} }
function* Record(schema, value) { function* Record(schema, value) {
yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`; yield `(typeof ${value} === 'object' && ${value} !== null && !Array.isArray(${value}))`;
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const local = PushLocal(`new RegExp(/${keyPattern}/)`); const local = PushLocal(`new RegExp(/${keyPattern}/)`);
yield `(Object.keys(${value}).every(key => ${local}.test(key)))`; yield `(Object.keys(${value}).every(key => ${local}.test(key)))`;
const expression = CreateExpression(valueSchema, 'value'); const expression = CreateExpression(valueSchema, 'value');
yield `(Object.values(${value}).every(value => ${expression}))`; yield `(Object.values(${value}).every(value => ${expression}))`;
} }
function* Ref(schema, value) { function* Ref(schema, value) {
// Reference: If we have seen this reference before we can just yield and return // 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 // 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. // set the function for subsequent passes. Consider for refactor.
if (names.has(schema.$ref)) if (names.has(schema.$ref))
return yield `(${CreateFunctionName(schema.$ref)}(${value}))`; return yield `(${CreateFunctionName(schema.$ref)}(${value}))`;
if (!referenceMap.has(schema.$ref)) if (!referenceMap.has(schema.$ref))
throw Error(`TypeCompiler.Ref: Cannot de-reference schema with $id '${schema.$ref}'`); throw Error(`TypeCompiler.Ref: Cannot de-reference schema with $id '${schema.$ref}'`);
const reference = referenceMap.get(schema.$ref); const reference = referenceMap.get(schema.$ref);
yield* Visit(reference, value); yield* Visit(reference, value);
} }
function* Self(schema, value) { function* Self(schema, value) {
const func = CreateFunctionName(schema.$ref); const func = CreateFunctionName(schema.$ref);
yield `(${func}(${value}))`; yield `(${func}(${value}))`;
} }
function* String(schema, value) { function* String(schema, value) {
yield `(typeof ${value} === 'string')`; yield `(typeof ${value} === 'string')`;
if (schema.minLength !== undefined) { if (schema.minLength !== undefined) {
yield `(${value}.length >= ${schema.minLength})`; yield `(${value}.length >= ${schema.minLength})`;
} }
if (schema.maxLength !== undefined) { if (schema.maxLength !== undefined) {
yield `(${value}.length <= ${schema.maxLength})`; yield `(${value}.length <= ${schema.maxLength})`;
} }
if (schema.pattern !== undefined) { if (schema.pattern !== undefined) {
const local = PushLocal(`new RegExp(/${schema.pattern}/);`); const local = PushLocal(`new RegExp(/${schema.pattern}/);`);
yield `(${local}.test(${value}))`; yield `(${local}.test(${value}))`;
} }
if (schema.format !== undefined) { if (schema.format !== undefined) {
yield `(format('${schema.format}', ${value}))`; yield `(format('${schema.format}', ${value}))`;
} }
} }
function* Tuple(schema, value) { function* Tuple(schema, value) {
yield `(Array.isArray(${value}))`; yield `(Array.isArray(${value}))`;
if (schema.items === undefined) if (schema.items === undefined)
return yield `(${value}.length === 0)`; return yield `(${value}.length === 0)`;
yield `(${value}.length === ${schema.maxItems})`; yield `(${value}.length === ${schema.maxItems})`;
for (let i = 0; i < schema.items.length; i++) { for (let i = 0; i < schema.items.length; i++) {
const expression = CreateExpression(schema.items[i], `${value}[${i}]`); const expression = CreateExpression(schema.items[i], `${value}[${i}]`);
yield `(${expression})`; yield `(${expression})`;
} }
} }
function* Undefined(schema, value) { function* Undefined(schema, value) {
yield `(${value} === undefined)`; yield `(${value} === undefined)`;
} }
function* Union(schema, value) { function* Union(schema, value) {
const expressions = schema.anyOf.map((schema) => CreateExpression(schema, value)); const expressions = schema.anyOf.map((schema) => CreateExpression(schema, value));
yield `(${expressions.join(' || ')})`; yield `(${expressions.join(' || ')})`;
} }
function* Uint8Array(schema, value) { function* Uint8Array(schema, value) {
yield `(${value} instanceof Uint8Array)`; yield `(${value} instanceof Uint8Array)`;
if (schema.maxByteLength) if (schema.maxByteLength)
yield `(${value}.length <= ${schema.maxByteLength})`; yield `(${value}.length <= ${schema.maxByteLength})`;
if (schema.minByteLength) if (schema.minByteLength)
yield `(${value}.length >= ${schema.minByteLength})`; yield `(${value}.length >= ${schema.minByteLength})`;
} }
function* Unknown(schema, value) { function* Unknown(schema, value) {
yield '(true)'; yield '(true)';
} }
function* Void(schema, value) { function* Void(schema, value) {
yield `(${value} === null)`; yield `(${value} === null)`;
} }
function* Visit(schema, value) { function* Visit(schema, value) {
// Reference: Referenced schemas can originate from either additional schemas // Reference: Referenced schemas can originate from either additional schemas
// or inline in the schema itself. Ideally the recursive path should align to // or inline in the schema itself. Ideally the recursive path should align to
// reference path. Consider for refactor. // reference path. Consider for refactor.
if (schema.$id && !names.has(schema.$id)) { if (schema.$id && !names.has(schema.$id)) {
names.add(schema.$id); names.add(schema.$id);
const name = CreateFunctionName(schema.$id); const name = CreateFunctionName(schema.$id);
const body = CreateFunction(name, schema, 'value'); const body = CreateFunction(name, schema, 'value');
PushFunction(body); PushFunction(body);
yield `(${name}(${value}))`; yield `(${name}(${value}))`;
return; return;
} }
const anySchema = schema; const anySchema = schema;
switch (anySchema[Types.Kind]) { switch (anySchema[Types.Kind]) {
case 'Any': case 'Any':
return yield* Any(anySchema, value); return yield* Any(anySchema, value);
case 'Array': case 'Array':
return yield* Array(anySchema, value); return yield* Array(anySchema, value);
case 'Boolean': case 'Boolean':
return yield* Boolean(anySchema, value); return yield* Boolean(anySchema, value);
case 'Constructor': case 'Constructor':
return yield* Constructor(anySchema, value); return yield* Constructor(anySchema, value);
case 'Function': case 'Function':
return yield* Function(anySchema, value); return yield* Function(anySchema, value);
case 'Integer': case 'Integer':
return yield* Integer(anySchema, value); return yield* Integer(anySchema, value);
case 'Literal': case 'Literal':
return yield* Literal(anySchema, value); return yield* Literal(anySchema, value);
case 'Never': case 'Never':
return yield* Never(anySchema, value); return yield* Never(anySchema, value);
case 'Null': case 'Null':
return yield* Null(anySchema, value); return yield* Null(anySchema, value);
case 'Number': case 'Number':
return yield* Number(anySchema, value); return yield* Number(anySchema, value);
case 'Object': case 'Object':
return yield* Object(anySchema, value); return yield* Object(anySchema, value);
case 'Promise': case 'Promise':
return yield* Promise(anySchema, value); return yield* Promise(anySchema, value);
case 'Record': case 'Record':
return yield* Record(anySchema, value); return yield* Record(anySchema, value);
case 'Ref': case 'Ref':
return yield* Ref(anySchema, value); return yield* Ref(anySchema, value);
case 'Self': case 'Self':
return yield* Self(anySchema, value); return yield* Self(anySchema, value);
case 'String': case 'String':
return yield* String(anySchema, value); return yield* String(anySchema, value);
case 'Tuple': case 'Tuple':
return yield* Tuple(anySchema, value); return yield* Tuple(anySchema, value);
case 'Undefined': case 'Undefined':
return yield* Undefined(anySchema, value); return yield* Undefined(anySchema, value);
case 'Union': case 'Union':
return yield* Union(anySchema, value); return yield* Union(anySchema, value);
case 'Uint8Array': case 'Uint8Array':
return yield* Uint8Array(anySchema, value); return yield* Uint8Array(anySchema, value);
case 'Unknown': case 'Unknown':
return yield* Unknown(anySchema, value); return yield* Unknown(anySchema, value);
case 'Void': case 'Void':
return yield* Void(anySchema, value); return yield* Void(anySchema, value);
default: default:
throw new TypeCompilerUnknownTypeError(schema); throw new TypeCompilerUnknownTypeError(schema);
} }
} }
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// Compile State // Compile State
// ------------------------------------------------------------------- // -------------------------------------------------------------------
const referenceMap = new Map(); const referenceMap = new Map();
const locals = new Set(); // local variables and functions const locals = new Set(); // local variables and functions
const names = new Set(); // cache of local functions const names = new Set(); // cache of local functions
function ResetCompiler() { function ResetCompiler() {
referenceMap.clear(); referenceMap.clear();
locals.clear(); locals.clear();
names.clear(); names.clear();
} }
function AddReferences(schemas = []) { function AddReferences(schemas = []) {
for (const schema of schemas) { for (const schema of schemas) {
if (!schema.$id) if (!schema.$id)
throw new Error(`TypeCompiler: Referenced schemas must specify an $id.`); throw new Error(`TypeCompiler: Referenced schemas must specify an $id.`);
if (referenceMap.has(schema.$id)) if (referenceMap.has(schema.$id))
throw new Error(`TypeCompiler: Duplicate schema $id found for '${schema.$id}'`); throw new Error(`TypeCompiler: Duplicate schema $id found for '${schema.$id}'`);
referenceMap.set(schema.$id, schema); referenceMap.set(schema.$id, schema);
} }
} }
function CreateExpression(schema, value) { function CreateExpression(schema, value) {
return [...Visit(schema, value)].join(' && '); return [...Visit(schema, value)].join(' && ');
} }
function CreateFunctionName($id) { function CreateFunctionName($id) {
return `check_${$id.replace(/-/g, '_')}`; return `check_${$id.replace(/-/g, '_')}`;
} }
function CreateFunction(name, schema, value) { function CreateFunction(name, schema, value) {
const expression = [...Visit(schema, value)].map((condition) => ` ${condition}`).join(' &&\n'); const expression = [...Visit(schema, value)].map((condition) => ` ${condition}`).join(' &&\n');
return `function ${name}(value) {\n return (\n${expression}\n )\n}`; return `function ${name}(value) {\n return (\n${expression}\n )\n}`;
} }
function PushFunction(functionBody) { function PushFunction(functionBody) {
locals.add(functionBody); locals.add(functionBody);
} }
function PushLocal(expression) { function PushLocal(expression) {
const local = `local_${locals.size}`; const local = `local_${locals.size}`;
locals.add(`const ${local} = ${expression}`); locals.add(`const ${local} = ${expression}`);
return local; return local;
} }
function GetLocals() { function GetLocals() {
return [...locals.values()]; return [...locals.values()];
} }
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// Compile // Compile
// ------------------------------------------------------------------- // -------------------------------------------------------------------
function Build(schema, references = []) { function Build(schema, references = []) {
ResetCompiler(); ResetCompiler();
AddReferences(references); AddReferences(references);
const check = CreateFunction('check', schema, 'value'); const check = CreateFunction('check', schema, 'value');
const locals = GetLocals(); const locals = GetLocals();
return `${locals.join('\n')}\nreturn ${check}`; 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. */ /** Compiles the given type for runtime type checking. This compiler only accepts known TypeBox types non-inclusive of unsafe types. */
function Compile(schema, references = []) { function Compile(schema, references = []) {
index_2.TypeGuard.Assert(schema, references); index_2.TypeGuard.Assert(schema, references);
const code = Build(schema, references); const code = Build(schema, references);
const func1 = globalThis.Function('format', code); const func1 = globalThis.Function('format', code);
const func2 = func1((format, value) => { const func2 = func1((format, value) => {
if (!index_3.Format.Has(format)) if (!index_3.Format.Has(format))
return false; return false;
const func = index_3.Format.Get(format); const func = index_3.Format.Get(format);
return func(value); return func(value);
}); });
return new TypeCheck(schema, references, func2, code); return new TypeCheck(schema, references, func2, code);
} }
TypeCompiler.Compile = Compile; TypeCompiler.Compile = Compile;
})(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {})); })(TypeCompiler = exports.TypeCompiler || (exports.TypeCompiler = {}));

View File

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

View File

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

View File

@@ -1,17 +1,17 @@
import * as Types from '../typebox'; 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 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[]> { 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']>>; 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[]> { 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']>>; static: Extract<Types.Static<T, this['params']>, Types.Static<U, this['params']>>;
} }
/** Conditional Types */ /** Conditional Types */
export declare namespace Conditional { export declare namespace Conditional {
/** (Experimental) Creates a conditional expression type */ /** (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>; 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. */ /** (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>; 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. */ /** (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>; 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"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/conditional @sinclair/typebox/conditional
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.Conditional = void 0; exports.Conditional = void 0;
const Types = require("../typebox"); const Types = require("../typebox");
const structural_1 = require("./structural"); const structural_1 = require("./structural");
const index_1 = require("../guard/index"); const index_1 = require("../guard/index");
/** Conditional Types */ /** Conditional Types */
var Conditional; var Conditional;
(function (Conditional) { (function (Conditional) {
/** (Experimental) Creates a conditional expression type */ /** (Experimental) Creates a conditional expression type */
function Extends(left, right, ok, fail) { function Extends(left, right, ok, fail) {
switch (structural_1.Structural.Check(left, right)) { switch (structural_1.Structural.Check(left, right)) {
case structural_1.StructuralResult.Union: case structural_1.StructuralResult.Union:
return Types.Type.Union([Clone(ok), Clone(fail)]); return Types.Type.Union([Clone(ok), Clone(fail)]);
case structural_1.StructuralResult.True: case structural_1.StructuralResult.True:
return Clone(ok); return Clone(ok);
case structural_1.StructuralResult.False: case structural_1.StructuralResult.False:
return Clone(fail); return Clone(fail);
} }
} }
Conditional.Extends = Extends; Conditional.Extends = Extends;
/** (Experimental) Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers. */ /** (Experimental) Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers. */
function Exclude(unionType, excludedMembers, options = {}) { function Exclude(unionType, excludedMembers, options = {}) {
const anyOf = unionType.anyOf const anyOf = unionType.anyOf
.filter((schema) => { .filter((schema) => {
const check = structural_1.Structural.Check(schema, excludedMembers); const check = structural_1.Structural.Check(schema, excludedMembers);
return !(check === structural_1.StructuralResult.True || check === structural_1.StructuralResult.Union); return !(check === structural_1.StructuralResult.True || check === structural_1.StructuralResult.Union);
}) })
.map((schema) => Clone(schema)); .map((schema) => Clone(schema));
return { ...options, [Types.Kind]: 'Union', anyOf }; return { ...options, [Types.Kind]: 'Union', anyOf };
} }
Conditional.Exclude = Exclude; Conditional.Exclude = Exclude;
/** (Experimental) Constructs a type by extracting from Type all union members that are assignable to Union. */ /** (Experimental) Constructs a type by extracting from Type all union members that are assignable to Union. */
function Extract(type, union, options = {}) { function Extract(type, union, options = {}) {
if (index_1.TypeGuard.TUnion(type)) { 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)); 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 }; return { ...options, [Types.Kind]: 'Union', anyOf };
} }
else { else {
const anyOf = union.anyOf.filter((schema) => structural_1.Structural.Check(type, schema) === structural_1.StructuralResult.True).map((schema) => Clone(schema)); 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 }; return { ...options, [Types.Kind]: 'Union', anyOf };
} }
} }
Conditional.Extract = Extract; Conditional.Extract = Extract;
function Clone(value) { function Clone(value) {
const isObject = (object) => typeof object === 'object' && object !== null && !Array.isArray(object); const isObject = (object) => typeof object === 'object' && object !== null && !Array.isArray(object);
const isArray = (object) => typeof object === 'object' && object !== null && Array.isArray(object); const isArray = (object) => typeof object === 'object' && object !== null && Array.isArray(object);
if (isObject(value)) { if (isObject(value)) {
return Object.keys(value).reduce((acc, key) => ({ return Object.keys(value).reduce((acc, key) => ({
...acc, ...acc,
[key]: Clone(value[key]), [key]: Clone(value[key]),
}), Object.getOwnPropertySymbols(value).reduce((acc, key) => ({ }), Object.getOwnPropertySymbols(value).reduce((acc, key) => ({
...acc, ...acc,
[key]: Clone(value[key]), [key]: Clone(value[key]),
}), {})); }), {}));
} }
else if (isArray(value)) { else if (isArray(value)) {
return value.map((item) => Clone(item)); return value.map((item) => Clone(item));
} }
else { else {
return value; return value;
} }
} }
})(Conditional = exports.Conditional || (exports.Conditional = {})); })(Conditional = exports.Conditional || (exports.Conditional = {}));

View File

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

View File

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

View File

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

View File

@@ -1,398 +1,398 @@
"use strict"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/errors @sinclair/typebox/errors
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueErrors = exports.ValueErrorsUnknownTypeError = exports.ValueErrorType = void 0; exports.ValueErrors = exports.ValueErrorsUnknownTypeError = exports.ValueErrorType = void 0;
const Types = require("../typebox"); const Types = require("../typebox");
const index_1 = require("../format/index"); const index_1 = require("../format/index");
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// ValueErrorType // ValueErrorType
// ------------------------------------------------------------------- // -------------------------------------------------------------------
var ValueErrorType; var ValueErrorType;
(function (ValueErrorType) { (function (ValueErrorType) {
ValueErrorType[ValueErrorType["Array"] = 0] = "Array"; ValueErrorType[ValueErrorType["Array"] = 0] = "Array";
ValueErrorType[ValueErrorType["ArrayMinItems"] = 1] = "ArrayMinItems"; ValueErrorType[ValueErrorType["ArrayMinItems"] = 1] = "ArrayMinItems";
ValueErrorType[ValueErrorType["ArrayMaxItems"] = 2] = "ArrayMaxItems"; ValueErrorType[ValueErrorType["ArrayMaxItems"] = 2] = "ArrayMaxItems";
ValueErrorType[ValueErrorType["ArrayUniqueItems"] = 3] = "ArrayUniqueItems"; ValueErrorType[ValueErrorType["ArrayUniqueItems"] = 3] = "ArrayUniqueItems";
ValueErrorType[ValueErrorType["Boolean"] = 4] = "Boolean"; ValueErrorType[ValueErrorType["Boolean"] = 4] = "Boolean";
ValueErrorType[ValueErrorType["Function"] = 5] = "Function"; ValueErrorType[ValueErrorType["Function"] = 5] = "Function";
ValueErrorType[ValueErrorType["Integer"] = 6] = "Integer"; ValueErrorType[ValueErrorType["Integer"] = 6] = "Integer";
ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 7] = "IntegerMultipleOf"; ValueErrorType[ValueErrorType["IntegerMultipleOf"] = 7] = "IntegerMultipleOf";
ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 8] = "IntegerExclusiveMinimum"; ValueErrorType[ValueErrorType["IntegerExclusiveMinimum"] = 8] = "IntegerExclusiveMinimum";
ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 9] = "IntegerExclusiveMaximum"; ValueErrorType[ValueErrorType["IntegerExclusiveMaximum"] = 9] = "IntegerExclusiveMaximum";
ValueErrorType[ValueErrorType["IntegerMinimum"] = 10] = "IntegerMinimum"; ValueErrorType[ValueErrorType["IntegerMinimum"] = 10] = "IntegerMinimum";
ValueErrorType[ValueErrorType["IntegerMaximum"] = 11] = "IntegerMaximum"; ValueErrorType[ValueErrorType["IntegerMaximum"] = 11] = "IntegerMaximum";
ValueErrorType[ValueErrorType["Literal"] = 12] = "Literal"; ValueErrorType[ValueErrorType["Literal"] = 12] = "Literal";
ValueErrorType[ValueErrorType["Never"] = 13] = "Never"; ValueErrorType[ValueErrorType["Never"] = 13] = "Never";
ValueErrorType[ValueErrorType["Null"] = 14] = "Null"; ValueErrorType[ValueErrorType["Null"] = 14] = "Null";
ValueErrorType[ValueErrorType["Number"] = 15] = "Number"; ValueErrorType[ValueErrorType["Number"] = 15] = "Number";
ValueErrorType[ValueErrorType["NumberMultipleOf"] = 16] = "NumberMultipleOf"; ValueErrorType[ValueErrorType["NumberMultipleOf"] = 16] = "NumberMultipleOf";
ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 17] = "NumberExclusiveMinimum"; ValueErrorType[ValueErrorType["NumberExclusiveMinimum"] = 17] = "NumberExclusiveMinimum";
ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 18] = "NumberExclusiveMaximum"; ValueErrorType[ValueErrorType["NumberExclusiveMaximum"] = 18] = "NumberExclusiveMaximum";
ValueErrorType[ValueErrorType["NumberMinumum"] = 19] = "NumberMinumum"; ValueErrorType[ValueErrorType["NumberMinumum"] = 19] = "NumberMinumum";
ValueErrorType[ValueErrorType["NumberMaximum"] = 20] = "NumberMaximum"; ValueErrorType[ValueErrorType["NumberMaximum"] = 20] = "NumberMaximum";
ValueErrorType[ValueErrorType["Object"] = 21] = "Object"; ValueErrorType[ValueErrorType["Object"] = 21] = "Object";
ValueErrorType[ValueErrorType["ObjectMinProperties"] = 22] = "ObjectMinProperties"; ValueErrorType[ValueErrorType["ObjectMinProperties"] = 22] = "ObjectMinProperties";
ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 23] = "ObjectMaxProperties"; ValueErrorType[ValueErrorType["ObjectMaxProperties"] = 23] = "ObjectMaxProperties";
ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 24] = "ObjectAdditionalProperties"; ValueErrorType[ValueErrorType["ObjectAdditionalProperties"] = 24] = "ObjectAdditionalProperties";
ValueErrorType[ValueErrorType["ObjectRequiredProperties"] = 25] = "ObjectRequiredProperties"; ValueErrorType[ValueErrorType["ObjectRequiredProperties"] = 25] = "ObjectRequiredProperties";
ValueErrorType[ValueErrorType["Promise"] = 26] = "Promise"; ValueErrorType[ValueErrorType["Promise"] = 26] = "Promise";
ValueErrorType[ValueErrorType["RecordKeyNumeric"] = 27] = "RecordKeyNumeric"; ValueErrorType[ValueErrorType["RecordKeyNumeric"] = 27] = "RecordKeyNumeric";
ValueErrorType[ValueErrorType["RecordKeyString"] = 28] = "RecordKeyString"; ValueErrorType[ValueErrorType["RecordKeyString"] = 28] = "RecordKeyString";
ValueErrorType[ValueErrorType["String"] = 29] = "String"; ValueErrorType[ValueErrorType["String"] = 29] = "String";
ValueErrorType[ValueErrorType["StringMinLength"] = 30] = "StringMinLength"; ValueErrorType[ValueErrorType["StringMinLength"] = 30] = "StringMinLength";
ValueErrorType[ValueErrorType["StringMaxLength"] = 31] = "StringMaxLength"; ValueErrorType[ValueErrorType["StringMaxLength"] = 31] = "StringMaxLength";
ValueErrorType[ValueErrorType["StringPattern"] = 32] = "StringPattern"; ValueErrorType[ValueErrorType["StringPattern"] = 32] = "StringPattern";
ValueErrorType[ValueErrorType["StringFormatUnknown"] = 33] = "StringFormatUnknown"; ValueErrorType[ValueErrorType["StringFormatUnknown"] = 33] = "StringFormatUnknown";
ValueErrorType[ValueErrorType["StringFormat"] = 34] = "StringFormat"; ValueErrorType[ValueErrorType["StringFormat"] = 34] = "StringFormat";
ValueErrorType[ValueErrorType["TupleZeroLength"] = 35] = "TupleZeroLength"; ValueErrorType[ValueErrorType["TupleZeroLength"] = 35] = "TupleZeroLength";
ValueErrorType[ValueErrorType["TupleLength"] = 36] = "TupleLength"; ValueErrorType[ValueErrorType["TupleLength"] = 36] = "TupleLength";
ValueErrorType[ValueErrorType["Undefined"] = 37] = "Undefined"; ValueErrorType[ValueErrorType["Undefined"] = 37] = "Undefined";
ValueErrorType[ValueErrorType["Union"] = 38] = "Union"; ValueErrorType[ValueErrorType["Union"] = 38] = "Union";
ValueErrorType[ValueErrorType["Uint8Array"] = 39] = "Uint8Array"; ValueErrorType[ValueErrorType["Uint8Array"] = 39] = "Uint8Array";
ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 40] = "Uint8ArrayMinByteLength"; ValueErrorType[ValueErrorType["Uint8ArrayMinByteLength"] = 40] = "Uint8ArrayMinByteLength";
ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 41] = "Uint8ArrayMaxByteLength"; ValueErrorType[ValueErrorType["Uint8ArrayMaxByteLength"] = 41] = "Uint8ArrayMaxByteLength";
ValueErrorType[ValueErrorType["Void"] = 42] = "Void"; ValueErrorType[ValueErrorType["Void"] = 42] = "Void";
})(ValueErrorType = exports.ValueErrorType || (exports.ValueErrorType = {})); })(ValueErrorType = exports.ValueErrorType || (exports.ValueErrorType = {}));
// ------------------------------------------------------------------- // -------------------------------------------------------------------
// ValueErrors // ValueErrors
// ------------------------------------------------------------------- // -------------------------------------------------------------------
class ValueErrorsUnknownTypeError extends Error { class ValueErrorsUnknownTypeError extends Error {
constructor(schema) { constructor(schema) {
super('ValueErrors: Unknown type'); super('ValueErrors: Unknown type');
this.schema = schema; this.schema = schema;
} }
} }
exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError; exports.ValueErrorsUnknownTypeError = ValueErrorsUnknownTypeError;
var ValueErrors; var ValueErrors;
(function (ValueErrors) { (function (ValueErrors) {
function* Any(schema, references, path, value) { } function* Any(schema, references, path, value) { }
function* Array(schema, references, path, value) { function* Array(schema, references, path, value) {
if (!globalThis.Array.isArray(value)) { if (!globalThis.Array.isArray(value)) {
return yield { type: ValueErrorType.Array, schema, path, value, message: `Expected array` }; return yield { type: ValueErrorType.Array, schema, path, value, message: `Expected array` };
} }
if (schema.minItems !== undefined && !(value.length >= schema.minItems)) { 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}` }; 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)) { 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}` }; 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)) { if (schema.uniqueItems === true && !(new Set(value).size === value.length)) {
yield { type: ValueErrorType.ArrayUniqueItems, schema, path, value, message: `Expected array elements to be unique` }; yield { type: ValueErrorType.ArrayUniqueItems, schema, path, value, message: `Expected array elements to be unique` };
} }
for (let i = 0; i < value.length; i++) { for (let i = 0; i < value.length; i++) {
yield* Visit(schema.items, references, `${path}/${i}`, value[i]); yield* Visit(schema.items, references, `${path}/${i}`, value[i]);
} }
} }
function* Boolean(schema, references, path, value) { function* Boolean(schema, references, path, value) {
if (!(typeof value === 'boolean')) { if (!(typeof value === 'boolean')) {
return yield { type: ValueErrorType.Boolean, schema, path, value, message: `Expected boolean` }; return yield { type: ValueErrorType.Boolean, schema, path, value, message: `Expected boolean` };
} }
} }
function* Constructor(schema, references, path, value) { function* Constructor(schema, references, path, value) {
yield* Visit(schema.returns, references, path, value.prototype); yield* Visit(schema.returns, references, path, value.prototype);
} }
function* Function(schema, references, path, value) { function* Function(schema, references, path, value) {
if (!(typeof value === 'function')) { if (!(typeof value === 'function')) {
return yield { type: ValueErrorType.Function, schema, path, value, message: `Expected function` }; return yield { type: ValueErrorType.Function, schema, path, value, message: `Expected function` };
} }
} }
function* Integer(schema, references, path, value) { function* Integer(schema, references, path, value) {
if (!(typeof value === 'number')) { if (!(typeof value === 'number')) {
return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` }; return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` };
} }
if (!globalThis.Number.isInteger(value)) { if (!globalThis.Number.isInteger(value)) {
yield { type: ValueErrorType.Integer, schema, path, value, message: `Expected integer` }; yield { type: ValueErrorType.Integer, schema, path, value, message: `Expected integer` };
} }
if (schema.multipleOf && !(value % schema.multipleOf === 0)) { if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
yield { type: ValueErrorType.IntegerMultipleOf, schema, path, value, message: `Expected integer to be a multiple of ${schema.multipleOf}` }; yield { type: ValueErrorType.IntegerMultipleOf, schema, path, value, message: `Expected integer to be a multiple of ${schema.multipleOf}` };
} }
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) { if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.IntegerExclusiveMinimum, schema, path, value, message: `Expected integer to be greater than ${schema.exclusiveMinimum}` }; yield { type: ValueErrorType.IntegerExclusiveMinimum, schema, path, value, message: `Expected integer to be greater than ${schema.exclusiveMinimum}` };
} }
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) { if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.IntegerExclusiveMaximum, schema, path, value, message: `Expected integer to be less than ${schema.exclusiveMaximum}` }; yield { type: ValueErrorType.IntegerExclusiveMaximum, schema, path, value, message: `Expected integer to be less than ${schema.exclusiveMaximum}` };
} }
if (schema.minimum && !(value >= schema.minimum)) { if (schema.minimum && !(value >= schema.minimum)) {
yield { type: ValueErrorType.IntegerMinimum, schema, path, value, message: `Expected integer to be greater or equal to ${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)) { if (schema.maximum && !(value <= schema.maximum)) {
yield { type: ValueErrorType.IntegerMaximum, schema, path, value, message: `Expected integer to be less or equal to ${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) { function* Literal(schema, references, path, value) {
if (!(value === schema.const)) { if (!(value === schema.const)) {
const error = typeof schema.const === 'string' ? `'${schema.const}'` : schema.const; const error = typeof schema.const === 'string' ? `'${schema.const}'` : schema.const;
return yield { type: ValueErrorType.Literal, schema, path, value, message: `Expected ${error}` }; return yield { type: ValueErrorType.Literal, schema, path, value, message: `Expected ${error}` };
} }
} }
function* Never(schema, references, path, value) { function* Never(schema, references, path, value) {
yield { type: ValueErrorType.Never, schema, path, value, message: `Value cannot be validated` }; yield { type: ValueErrorType.Never, schema, path, value, message: `Value cannot be validated` };
} }
function* Null(schema, references, path, value) { function* Null(schema, references, path, value) {
if (!(value === null)) { if (!(value === null)) {
return yield { type: ValueErrorType.Null, schema, path, value, message: `Expected null` }; return yield { type: ValueErrorType.Null, schema, path, value, message: `Expected null` };
} }
} }
function* Number(schema, references, path, value) { function* Number(schema, references, path, value) {
if (!(typeof value === 'number')) { if (!(typeof value === 'number')) {
return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` }; return yield { type: ValueErrorType.Number, schema, path, value, message: `Expected number` };
} }
if (schema.multipleOf && !(value % schema.multipleOf === 0)) { if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
yield { type: ValueErrorType.NumberMultipleOf, schema, path, value, message: `Expected number to be a multiple of ${schema.multipleOf}` }; yield { type: ValueErrorType.NumberMultipleOf, schema, path, value, message: `Expected number to be a multiple of ${schema.multipleOf}` };
} }
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) { if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
yield { type: ValueErrorType.NumberExclusiveMinimum, schema, path, value, message: `Expected number to be greater than ${schema.exclusiveMinimum}` }; yield { type: ValueErrorType.NumberExclusiveMinimum, schema, path, value, message: `Expected number to be greater than ${schema.exclusiveMinimum}` };
} }
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) { if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
yield { type: ValueErrorType.NumberExclusiveMaximum, schema, path, value, message: `Expected number to be less than ${schema.exclusiveMaximum}` }; yield { type: ValueErrorType.NumberExclusiveMaximum, schema, path, value, message: `Expected number to be less than ${schema.exclusiveMaximum}` };
} }
if (schema.minimum && !(value >= schema.minimum)) { if (schema.minimum && !(value >= schema.minimum)) {
yield { type: ValueErrorType.NumberMaximum, schema, path, value, message: `Expected number to be greater or equal to ${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)) { if (schema.maximum && !(value <= schema.maximum)) {
yield { type: ValueErrorType.NumberMinumum, schema, path, value, message: `Expected number to be less or equal to ${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) { function* Object(schema, references, path, value) {
if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) { if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` }; return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` };
} }
if (schema.minProperties !== undefined && !(globalThis.Object.keys(value).length >= schema.minProperties)) { 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` }; 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)) { 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` }; yield { type: ValueErrorType.ObjectMaxProperties, schema, path, value, message: `Expected object to have less than ${schema.minProperties} properties` };
} }
const propertyKeys = globalThis.Object.keys(schema.properties); const propertyKeys = globalThis.Object.keys(schema.properties);
if (schema.additionalProperties === false) { if (schema.additionalProperties === false) {
for (const objectKey of globalThis.Object.keys(value)) { for (const objectKey of globalThis.Object.keys(value)) {
if (!propertyKeys.includes(objectKey)) { if (!propertyKeys.includes(objectKey)) {
yield { type: ValueErrorType.ObjectAdditionalProperties, schema, path: `${path}/${objectKey}`, value: value[objectKey], message: `Unexpected property` }; yield { type: ValueErrorType.ObjectAdditionalProperties, schema, path: `${path}/${objectKey}`, value: value[objectKey], message: `Unexpected property` };
} }
} }
} }
if (schema.required && schema.required.length > 0) { if (schema.required && schema.required.length > 0) {
const objectKeys = globalThis.Object.keys(value); const objectKeys = globalThis.Object.keys(value);
for (const requiredKey of schema.required) { for (const requiredKey of schema.required) {
if (objectKeys.includes(requiredKey)) if (objectKeys.includes(requiredKey))
continue; continue;
yield { type: ValueErrorType.ObjectRequiredProperties, schema: schema.properties[requiredKey], path: `${path}/${requiredKey}`, value: undefined, message: `Expected required property` }; yield { type: ValueErrorType.ObjectRequiredProperties, schema: schema.properties[requiredKey], path: `${path}/${requiredKey}`, value: undefined, message: `Expected required property` };
} }
} }
if (typeof schema.additionalProperties === 'object') { if (typeof schema.additionalProperties === 'object') {
for (const objectKey of globalThis.Object.keys(value)) { for (const objectKey of globalThis.Object.keys(value)) {
if (propertyKeys.includes(objectKey)) if (propertyKeys.includes(objectKey))
continue; continue;
yield* Visit(schema.additionalProperties, references, `${path}/${objectKey}`, value[objectKey]); yield* Visit(schema.additionalProperties, references, `${path}/${objectKey}`, value[objectKey]);
} }
} }
for (const propertyKey of propertyKeys) { for (const propertyKey of propertyKeys) {
const propertySchema = schema.properties[propertyKey]; const propertySchema = schema.properties[propertyKey];
if (schema.required && schema.required.includes(propertyKey)) { if (schema.required && schema.required.includes(propertyKey)) {
yield* Visit(propertySchema, references, `${path}/${propertyKey}`, value[propertyKey]); yield* Visit(propertySchema, references, `${path}/${propertyKey}`, value[propertyKey]);
} }
else { else {
if (value[propertyKey] !== undefined) { if (value[propertyKey] !== undefined) {
yield* Visit(propertySchema, references, `${path}/${propertyKey}`, value[propertyKey]); yield* Visit(propertySchema, references, `${path}/${propertyKey}`, value[propertyKey]);
} }
} }
} }
} }
function* Promise(schema, references, path, value) { function* Promise(schema, references, path, value) {
if (!(typeof value === 'object' && typeof value.then === 'function')) { if (!(typeof value === 'object' && typeof value.then === 'function')) {
yield { type: ValueErrorType.Promise, schema, path, value, message: `Expected Promise` }; yield { type: ValueErrorType.Promise, schema, path, value, message: `Expected Promise` };
} }
} }
function* Record(schema, references, path, value) { function* Record(schema, references, path, value) {
if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) { if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` }; return yield { type: ValueErrorType.Object, schema, path, value, message: `Expected object` };
} }
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern); const regex = new RegExp(keyPattern);
if (!globalThis.Object.keys(value).every((key) => regex.test(key))) { if (!globalThis.Object.keys(value).every((key) => regex.test(key))) {
const numeric = keyPattern === '^(0|[1-9][0-9]*)$'; const numeric = keyPattern === '^(0|[1-9][0-9]*)$';
const type = numeric ? ValueErrorType.RecordKeyNumeric : ValueErrorType.RecordKeyString; 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'; 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 }; return yield { type, schema, path, value, message };
} }
for (const [propKey, propValue] of globalThis.Object.entries(value)) { for (const [propKey, propValue] of globalThis.Object.entries(value)) {
yield* Visit(valueSchema, references, `${path}/${propKey}`, propValue); yield* Visit(valueSchema, references, `${path}/${propKey}`, propValue);
} }
} }
function* Ref(schema, references, path, value) { function* Ref(schema, references, path, value) {
const reference = references.find((reference) => reference.$id === schema.$ref); const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined) if (reference === undefined)
throw new Error(`ValueErrors.Ref: Cannot find schema with $id '${schema.$ref}'.`); throw new Error(`ValueErrors.Ref: Cannot find schema with $id '${schema.$ref}'.`);
yield* Visit(reference, references, path, value); yield* Visit(reference, references, path, value);
} }
function* Self(schema, references, path, value) { function* Self(schema, references, path, value) {
const reference = references.find((reference) => reference.$id === schema.$ref); const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined) if (reference === undefined)
throw new Error(`ValueErrors.Self: Cannot find schema with $id '${schema.$ref}'.`); throw new Error(`ValueErrors.Self: Cannot find schema with $id '${schema.$ref}'.`);
yield* Visit(reference, references, path, value); yield* Visit(reference, references, path, value);
} }
function* String(schema, references, path, value) { function* String(schema, references, path, value) {
if (!(typeof value === 'string')) { if (!(typeof value === 'string')) {
return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' }; return yield { type: ValueErrorType.String, schema, path, value, message: 'Expected string' };
} }
if (schema.minLength !== undefined && !(value.length >= schema.minLength)) { 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}` }; 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)) { 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}` }; yield { type: ValueErrorType.StringMaxLength, schema, path, value, message: `Expected string length less or equal to ${schema.maxLength}` };
} }
if (schema.pattern !== undefined) { if (schema.pattern !== undefined) {
const regex = new RegExp(schema.pattern); const regex = new RegExp(schema.pattern);
if (!regex.test(value)) { if (!regex.test(value)) {
yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` }; yield { type: ValueErrorType.StringPattern, schema, path, value, message: `Expected string to match pattern ${schema.pattern}` };
} }
} }
if (schema.format !== undefined) { if (schema.format !== undefined) {
if (!index_1.Format.Has(schema.format)) { if (!index_1.Format.Has(schema.format)) {
yield { type: ValueErrorType.StringFormatUnknown, schema, path, value, message: `Unknown string format '${schema.format}'` }; yield { type: ValueErrorType.StringFormatUnknown, schema, path, value, message: `Unknown string format '${schema.format}'` };
} }
else { else {
const format = index_1.Format.Get(schema.format); const format = index_1.Format.Get(schema.format);
if (!format(value)) { if (!format(value)) {
yield { type: ValueErrorType.StringFormat, schema, path, value, message: `Expected string to match format '${schema.format}'` }; yield { type: ValueErrorType.StringFormat, schema, path, value, message: `Expected string to match format '${schema.format}'` };
} }
} }
} }
} }
function* Tuple(schema, references, path, value) { function* Tuple(schema, references, path, value) {
if (!globalThis.Array.isArray(value)) { if (!globalThis.Array.isArray(value)) {
return yield { type: ValueErrorType.Array, schema, path, value, message: 'Expected Array' }; return yield { type: ValueErrorType.Array, schema, path, value, message: 'Expected Array' };
} }
if (schema.items === undefined && !(value.length === 0)) { if (schema.items === undefined && !(value.length === 0)) {
return yield { type: ValueErrorType.TupleZeroLength, schema, path, value, message: 'Expected tuple to have 0 elements' }; return yield { type: ValueErrorType.TupleZeroLength, schema, path, value, message: 'Expected tuple to have 0 elements' };
} }
if (!(value.length === schema.maxItems)) { if (!(value.length === schema.maxItems)) {
yield { type: ValueErrorType.TupleLength, schema, path, value, message: `Expected tuple to have ${schema.maxItems} elements` }; yield { type: ValueErrorType.TupleLength, schema, path, value, message: `Expected tuple to have ${schema.maxItems} elements` };
} }
if (!schema.items) { if (!schema.items) {
return; return;
} }
for (let i = 0; i < schema.items.length; i++) { for (let i = 0; i < schema.items.length; i++) {
yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]); yield* Visit(schema.items[i], references, `${path}/${i}`, value[i]);
} }
} }
function* Undefined(schema, references, path, value) { function* Undefined(schema, references, path, value) {
if (!(value === undefined)) { if (!(value === undefined)) {
yield { type: ValueErrorType.Undefined, schema, path, value, message: `Expected undefined` }; yield { type: ValueErrorType.Undefined, schema, path, value, message: `Expected undefined` };
} }
} }
function* Union(schema, references, path, value) { function* Union(schema, references, path, value) {
const errors = []; const errors = [];
for (const inner of schema.anyOf) { for (const inner of schema.anyOf) {
const variantErrors = [...Visit(inner, references, path, value)]; const variantErrors = [...Visit(inner, references, path, value)];
if (variantErrors.length === 0) if (variantErrors.length === 0)
return; return;
errors.push(...variantErrors); errors.push(...variantErrors);
} }
for (const error of errors) { for (const error of errors) {
yield error; yield error;
} }
if (errors.length > 0) { if (errors.length > 0) {
yield { type: ValueErrorType.Union, schema, path, value, message: 'Expected value of union' }; yield { type: ValueErrorType.Union, schema, path, value, message: 'Expected value of union' };
} }
} }
function* Uint8Array(schema, references, path, value) { function* Uint8Array(schema, references, path, value) {
if (!(value instanceof globalThis.Uint8Array)) { if (!(value instanceof globalThis.Uint8Array)) {
return yield { type: ValueErrorType.Uint8Array, schema, path, value, message: `Expected Uint8Array` }; return yield { type: ValueErrorType.Uint8Array, schema, path, value, message: `Expected Uint8Array` };
} }
if (schema.maxByteLength && !(value.length <= schema.maxByteLength)) { 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}` }; 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)) { 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}` }; 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* Unknown(schema, references, path, value) { }
function* Void(schema, references, path, value) { function* Void(schema, references, path, value) {
if (!(value === null)) { if (!(value === null)) {
return yield { type: ValueErrorType.Void, schema, path, value, message: `Expected null` }; return yield { type: ValueErrorType.Void, schema, path, value, message: `Expected null` };
} }
} }
function* Visit(schema, references, path, value) { function* Visit(schema, references, path, value) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references]; const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema; const anySchema = schema;
switch (anySchema[Types.Kind]) { switch (anySchema[Types.Kind]) {
case 'Any': case 'Any':
return yield* Any(anySchema, anyReferences, path, value); return yield* Any(anySchema, anyReferences, path, value);
case 'Array': case 'Array':
return yield* Array(anySchema, anyReferences, path, value); return yield* Array(anySchema, anyReferences, path, value);
case 'Boolean': case 'Boolean':
return yield* Boolean(anySchema, anyReferences, path, value); return yield* Boolean(anySchema, anyReferences, path, value);
case 'Constructor': case 'Constructor':
return yield* Constructor(anySchema, anyReferences, path, value); return yield* Constructor(anySchema, anyReferences, path, value);
case 'Function': case 'Function':
return yield* Function(anySchema, anyReferences, path, value); return yield* Function(anySchema, anyReferences, path, value);
case 'Integer': case 'Integer':
return yield* Integer(anySchema, anyReferences, path, value); return yield* Integer(anySchema, anyReferences, path, value);
case 'Literal': case 'Literal':
return yield* Literal(anySchema, anyReferences, path, value); return yield* Literal(anySchema, anyReferences, path, value);
case 'Never': case 'Never':
return yield* Never(anySchema, anyReferences, path, value); return yield* Never(anySchema, anyReferences, path, value);
case 'Null': case 'Null':
return yield* Null(anySchema, anyReferences, path, value); return yield* Null(anySchema, anyReferences, path, value);
case 'Number': case 'Number':
return yield* Number(anySchema, anyReferences, path, value); return yield* Number(anySchema, anyReferences, path, value);
case 'Object': case 'Object':
return yield* Object(anySchema, anyReferences, path, value); return yield* Object(anySchema, anyReferences, path, value);
case 'Promise': case 'Promise':
return yield* Promise(anySchema, anyReferences, path, value); return yield* Promise(anySchema, anyReferences, path, value);
case 'Record': case 'Record':
return yield* Record(anySchema, anyReferences, path, value); return yield* Record(anySchema, anyReferences, path, value);
case 'Ref': case 'Ref':
return yield* Ref(anySchema, anyReferences, path, value); return yield* Ref(anySchema, anyReferences, path, value);
case 'Self': case 'Self':
return yield* Self(anySchema, anyReferences, path, value); return yield* Self(anySchema, anyReferences, path, value);
case 'String': case 'String':
return yield* String(anySchema, anyReferences, path, value); return yield* String(anySchema, anyReferences, path, value);
case 'Tuple': case 'Tuple':
return yield* Tuple(anySchema, anyReferences, path, value); return yield* Tuple(anySchema, anyReferences, path, value);
case 'Undefined': case 'Undefined':
return yield* Undefined(anySchema, anyReferences, path, value); return yield* Undefined(anySchema, anyReferences, path, value);
case 'Union': case 'Union':
return yield* Union(anySchema, anyReferences, path, value); return yield* Union(anySchema, anyReferences, path, value);
case 'Uint8Array': case 'Uint8Array':
return yield* Uint8Array(anySchema, anyReferences, path, value); return yield* Uint8Array(anySchema, anyReferences, path, value);
case 'Unknown': case 'Unknown':
return yield* Unknown(anySchema, anyReferences, path, value); return yield* Unknown(anySchema, anyReferences, path, value);
case 'Void': case 'Void':
return yield* Void(anySchema, anyReferences, path, value); return yield* Void(anySchema, anyReferences, path, value);
default: default:
throw new ValueErrorsUnknownTypeError(schema); throw new ValueErrorsUnknownTypeError(schema);
} }
} }
function* Errors(schema, references, value) { function* Errors(schema, references, value) {
yield* Visit(schema, references, '', value); yield* Visit(schema, references, '', value);
} }
ValueErrors.Errors = Errors; ValueErrors.Errors = Errors;
})(ValueErrors = exports.ValueErrors || (exports.ValueErrors = {})); })(ValueErrors = exports.ValueErrors || (exports.ValueErrors = {}));

View File

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

View File

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

View File

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

View File

@@ -1,55 +1,55 @@
"use strict"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/format @sinclair/typebox/format
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.Format = void 0; exports.Format = void 0;
/** Shared string formats used by the TypeCompiler and Value modules */ /** Shared string formats used by the TypeCompiler and Value modules */
var Format; var Format;
(function (Format) { (function (Format) {
const formats = new Map(); const formats = new Map();
/** Clears all formats */ /** Clears all formats */
function Clear() { function Clear() {
return formats.clear(); return formats.clear();
} }
Format.Clear = Clear; Format.Clear = Clear;
/** Returns true if the string format exists */ /** Returns true if the string format exists */
function Has(format) { function Has(format) {
return formats.has(format); return formats.has(format);
} }
Format.Has = Has; Format.Has = Has;
/** Sets a string format validation function */ /** Sets a string format validation function */
function Set(format, func) { function Set(format, func) {
formats.set(format, func); formats.set(format, func);
} }
Format.Set = Set; Format.Set = Set;
/** Gets a string format validation function */ /** Gets a string format validation function */
function Get(format) { function Get(format) {
return formats.get(format); return formats.get(format);
} }
Format.Get = Get; Format.Get = Get;
})(Format = exports.Format || (exports.Format = {})); })(Format = exports.Format || (exports.Format = {}));

View File

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

View File

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

View File

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

View File

@@ -1,351 +1,351 @@
"use strict"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/guard @sinclair/typebox/guard
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, dTribute, sublicense, and/or sell to use, copy, modify, merge, publish, dTribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.TypeGuard = exports.TypeGuardInvalidTypeError = void 0; exports.TypeGuard = exports.TypeGuardInvalidTypeError = void 0;
const Types = require("../typebox"); const Types = require("../typebox");
class TypeGuardInvalidTypeError extends Error { class TypeGuardInvalidTypeError extends Error {
constructor(schema) { constructor(schema) {
super('TypeGuard: Invalid type'); super('TypeGuard: Invalid type');
this.schema = schema; this.schema = schema;
} }
} }
exports.TypeGuardInvalidTypeError = TypeGuardInvalidTypeError; exports.TypeGuardInvalidTypeError = TypeGuardInvalidTypeError;
/** TypeGuard tests that values conform to a known TypeBox type specification */ /** TypeGuard tests that values conform to a known TypeBox type specification */
var TypeGuard; var TypeGuard;
(function (TypeGuard) { (function (TypeGuard) {
function IsObject(value) { function IsObject(value) {
return typeof value === 'object' && value !== null && !Array.isArray(value); return typeof value === 'object' && value !== null && !Array.isArray(value);
} }
function IsArray(value) { function IsArray(value) {
return typeof value === 'object' && value !== null && Array.isArray(value); return typeof value === 'object' && value !== null && Array.isArray(value);
} }
function IsPattern(value) { function IsPattern(value) {
try { try {
new RegExp(value); new RegExp(value);
return true; return true;
} }
catch { catch {
return false; return false;
} }
} }
function IsControlCharacterFree(value) { function IsControlCharacterFree(value) {
if (typeof value !== 'string') if (typeof value !== 'string')
return false; return false;
for (let i = 0; i < value.length; i++) { for (let i = 0; i < value.length; i++) {
const code = value.charCodeAt(i); const code = value.charCodeAt(i);
if ((code >= 7 && code <= 13) || code === 27 || code === 127) { if ((code >= 7 && code <= 13) || code === 27 || code === 127) {
return false; return false;
} }
} }
return true; return true;
} }
function IsString(value) { function IsString(value) {
return typeof value === 'string'; return typeof value === 'string';
} }
function IsNumber(value) { function IsNumber(value) {
return typeof value === 'number'; return typeof value === 'number';
} }
function IsBoolean(value) { function IsBoolean(value) {
return typeof value === 'boolean'; return typeof value === 'boolean';
} }
function IsOptionalNumber(value) { function IsOptionalNumber(value) {
return value === undefined || (value !== undefined && IsNumber(value)); return value === undefined || (value !== undefined && IsNumber(value));
} }
function IsOptionalBoolean(value) { function IsOptionalBoolean(value) {
return value === undefined || (value !== undefined && IsBoolean(value)); return value === undefined || (value !== undefined && IsBoolean(value));
} }
function IsOptionalString(value) { function IsOptionalString(value) {
return value === undefined || (value !== undefined && IsString(value)); return value === undefined || (value !== undefined && IsString(value));
} }
function IsOptionalPattern(value) { function IsOptionalPattern(value) {
return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value) && IsPattern(value)); return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value) && IsPattern(value));
} }
function IsOptionalFormat(value) { function IsOptionalFormat(value) {
return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value)); return value === undefined || (value !== undefined && IsString(value) && IsControlCharacterFree(value));
} }
function IsOptionalSchema(value) { function IsOptionalSchema(value) {
return value === undefined || TSchema(value); return value === undefined || TSchema(value);
} }
/** Returns true if the given schema is TAny */ /** Returns true if the given schema is TAny */
function TAny(schema) { function TAny(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Any' && IsOptionalString(schema.$id); return IsObject(schema) && schema[Types.Kind] === 'Any' && IsOptionalString(schema.$id);
} }
TypeGuard.TAny = TAny; TypeGuard.TAny = TAny;
/** Returns true if the given schema is TArray */ /** Returns true if the given schema is TArray */
function TArray(schema) { function TArray(schema) {
return (IsObject(schema) && return (IsObject(schema) &&
schema[Types.Kind] === 'Array' && schema[Types.Kind] === 'Array' &&
schema.type === 'array' && schema.type === 'array' &&
IsOptionalString(schema.$id) && IsOptionalString(schema.$id) &&
TSchema(schema.items) && TSchema(schema.items) &&
IsOptionalNumber(schema.minItems) && IsOptionalNumber(schema.minItems) &&
IsOptionalNumber(schema.maxItems) && IsOptionalNumber(schema.maxItems) &&
IsOptionalBoolean(schema.uniqueItems)); IsOptionalBoolean(schema.uniqueItems));
} }
TypeGuard.TArray = TArray; TypeGuard.TArray = TArray;
/** Returns true if the given schema is TBoolean */ /** Returns true if the given schema is TBoolean */
function TBoolean(schema) { function TBoolean(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Boolean' && schema.type === 'boolean' && IsOptionalString(schema.$id); return IsObject(schema) && schema[Types.Kind] === 'Boolean' && schema.type === 'boolean' && IsOptionalString(schema.$id);
} }
TypeGuard.TBoolean = TBoolean; TypeGuard.TBoolean = TBoolean;
/** Returns true if the given schema is TConstructor */ /** Returns true if the given schema is TConstructor */
function TConstructor(schema) { function TConstructor(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Constructor' && schema.type === 'constructor' && IsOptionalString(schema.$id) && IsArray(schema.parameters) && TSchema(schema.returns))) { if (!(IsObject(schema) && schema[Types.Kind] === 'Constructor' && schema.type === 'constructor' && IsOptionalString(schema.$id) && IsArray(schema.parameters) && TSchema(schema.returns))) {
return false; return false;
} }
for (const parameter of schema.parameters) { for (const parameter of schema.parameters) {
if (!TSchema(parameter)) if (!TSchema(parameter))
return false; return false;
} }
return true; return true;
} }
TypeGuard.TConstructor = TConstructor; TypeGuard.TConstructor = TConstructor;
/** Returns true if the given schema is TFunction */ /** Returns true if the given schema is TFunction */
function TFunction(schema) { function TFunction(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Function' && schema.type === 'function' && IsOptionalString(schema.$id) && IsArray(schema.parameters) && TSchema(schema.returns))) { if (!(IsObject(schema) && schema[Types.Kind] === 'Function' && schema.type === 'function' && IsOptionalString(schema.$id) && IsArray(schema.parameters) && TSchema(schema.returns))) {
return false; return false;
} }
for (const parameter of schema.parameters) { for (const parameter of schema.parameters) {
if (!TSchema(parameter)) if (!TSchema(parameter))
return false; return false;
} }
return true; return true;
} }
TypeGuard.TFunction = TFunction; TypeGuard.TFunction = TFunction;
/** Returns true if the given schema is TInteger */ /** Returns true if the given schema is TInteger */
function TInteger(schema) { function TInteger(schema) {
return (IsObject(schema) && return (IsObject(schema) &&
schema[Types.Kind] === 'Integer' && schema[Types.Kind] === 'Integer' &&
schema.type === 'integer' && schema.type === 'integer' &&
IsOptionalString(schema.$id) && IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.multipleOf) && IsOptionalNumber(schema.multipleOf) &&
IsOptionalNumber(schema.minimum) && IsOptionalNumber(schema.minimum) &&
IsOptionalNumber(schema.maximum) && IsOptionalNumber(schema.maximum) &&
IsOptionalNumber(schema.exclusiveMinimum) && IsOptionalNumber(schema.exclusiveMinimum) &&
IsOptionalNumber(schema.exclusiveMaximum)); IsOptionalNumber(schema.exclusiveMaximum));
} }
TypeGuard.TInteger = TInteger; TypeGuard.TInteger = TInteger;
/** Returns true if the given schema is TLiteral */ /** Returns true if the given schema is TLiteral */
function TLiteral(schema) { function TLiteral(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Literal' && IsOptionalString(schema.$id) && (IsString(schema.const) || IsNumber(schema.const) || IsBoolean(schema.const)); return IsObject(schema) && schema[Types.Kind] === 'Literal' && IsOptionalString(schema.$id) && (IsString(schema.const) || IsNumber(schema.const) || IsBoolean(schema.const));
} }
TypeGuard.TLiteral = TLiteral; TypeGuard.TLiteral = TLiteral;
/** Returns true if the given schema is TNever */ /** Returns true if the given schema is TNever */
function TNever(schema) { function TNever(schema) {
return (IsObject(schema) && return (IsObject(schema) &&
schema[Types.Kind] === 'Never' && schema[Types.Kind] === 'Never' &&
IsArray(schema.allOf) && IsArray(schema.allOf) &&
schema.allOf.length === 2 && schema.allOf.length === 2 &&
IsObject(schema.allOf[0]) && IsObject(schema.allOf[0]) &&
IsString(schema.allOf[0].type) && IsString(schema.allOf[0].type) &&
schema.allOf[0].type === 'boolean' && schema.allOf[0].type === 'boolean' &&
schema.allOf[0].const === false && schema.allOf[0].const === false &&
IsObject(schema.allOf[1]) && IsObject(schema.allOf[1]) &&
IsString(schema.allOf[1].type) && IsString(schema.allOf[1].type) &&
schema.allOf[1].type === 'boolean' && schema.allOf[1].type === 'boolean' &&
schema.allOf[1].const === true); schema.allOf[1].const === true);
} }
TypeGuard.TNever = TNever; TypeGuard.TNever = TNever;
/** Returns true if the given schema is TNull */ /** Returns true if the given schema is TNull */
function TNull(schema) { function TNull(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Null' && schema.type === 'null' && IsOptionalString(schema.$id); return IsObject(schema) && schema[Types.Kind] === 'Null' && schema.type === 'null' && IsOptionalString(schema.$id);
} }
TypeGuard.TNull = TNull; TypeGuard.TNull = TNull;
/** Returns true if the given schema is TNumber */ /** Returns true if the given schema is TNumber */
function TNumber(schema) { function TNumber(schema) {
return (IsObject(schema) && return (IsObject(schema) &&
schema[Types.Kind] === 'Number' && schema[Types.Kind] === 'Number' &&
schema.type === 'number' && schema.type === 'number' &&
IsOptionalString(schema.$id) && IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.multipleOf) && IsOptionalNumber(schema.multipleOf) &&
IsOptionalNumber(schema.minimum) && IsOptionalNumber(schema.minimum) &&
IsOptionalNumber(schema.maximum) && IsOptionalNumber(schema.maximum) &&
IsOptionalNumber(schema.exclusiveMinimum) && IsOptionalNumber(schema.exclusiveMinimum) &&
IsOptionalNumber(schema.exclusiveMaximum)); IsOptionalNumber(schema.exclusiveMaximum));
} }
TypeGuard.TNumber = TNumber; TypeGuard.TNumber = TNumber;
/** Returns true if the given schema is TObject */ /** Returns true if the given schema is TObject */
function TObject(schema) { function TObject(schema) {
if (!(IsObject(schema) && if (!(IsObject(schema) &&
schema[Types.Kind] === 'Object' && schema[Types.Kind] === 'Object' &&
schema.type === 'object' && schema.type === 'object' &&
IsOptionalString(schema.$id) && IsOptionalString(schema.$id) &&
IsObject(schema.properties) && IsObject(schema.properties) &&
(IsOptionalBoolean(schema.additionalProperties) || IsOptionalSchema(schema.additionalProperties)) && (IsOptionalBoolean(schema.additionalProperties) || IsOptionalSchema(schema.additionalProperties)) &&
IsOptionalNumber(schema.minProperties) && IsOptionalNumber(schema.minProperties) &&
IsOptionalNumber(schema.maxProperties))) { IsOptionalNumber(schema.maxProperties))) {
return false; return false;
} }
for (const [key, value] of Object.entries(schema.properties)) { for (const [key, value] of Object.entries(schema.properties)) {
if (!IsControlCharacterFree(key)) if (!IsControlCharacterFree(key))
return false; return false;
if (!TSchema(value)) if (!TSchema(value))
return false; return false;
} }
return true; return true;
} }
TypeGuard.TObject = TObject; TypeGuard.TObject = TObject;
/** Returns true if the given schema is TPromise */ /** Returns true if the given schema is TPromise */
function TPromise(schema) { function TPromise(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Promise' && schema.type === 'promise' && IsOptionalString(schema.$id) && TSchema(schema.item); return IsObject(schema) && schema[Types.Kind] === 'Promise' && schema.type === 'promise' && IsOptionalString(schema.$id) && TSchema(schema.item);
} }
TypeGuard.TPromise = TPromise; TypeGuard.TPromise = TPromise;
/** Returns true if the given schema is TRecord */ /** Returns true if the given schema is TRecord */
function TRecord(schema) { function TRecord(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Record' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.additionalProperties === false && IsObject(schema.patternProperties))) { if (!(IsObject(schema) && schema[Types.Kind] === 'Record' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.additionalProperties === false && IsObject(schema.patternProperties))) {
return false; return false;
} }
const keys = Object.keys(schema.patternProperties); const keys = Object.keys(schema.patternProperties);
if (keys.length !== 1) { if (keys.length !== 1) {
return false; return false;
} }
if (!IsPattern(keys[0])) { if (!IsPattern(keys[0])) {
return false; return false;
} }
if (!TSchema(schema.patternProperties[keys[0]])) { if (!TSchema(schema.patternProperties[keys[0]])) {
return false; return false;
} }
return true; return true;
} }
TypeGuard.TRecord = TRecord; TypeGuard.TRecord = TRecord;
/** Returns true if the given schema is TSelf */ /** Returns true if the given schema is TSelf */
function TSelf(schema) { function TSelf(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Self' && IsOptionalString(schema.$id) && IsString(schema.$ref); return IsObject(schema) && schema[Types.Kind] === 'Self' && IsOptionalString(schema.$id) && IsString(schema.$ref);
} }
TypeGuard.TSelf = TSelf; TypeGuard.TSelf = TSelf;
/** Returns true if the given schema is TRef */ /** Returns true if the given schema is TRef */
function TRef(schema) { function TRef(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Ref' && IsOptionalString(schema.$id) && IsString(schema.$ref); return IsObject(schema) && schema[Types.Kind] === 'Ref' && IsOptionalString(schema.$id) && IsString(schema.$ref);
} }
TypeGuard.TRef = TRef; TypeGuard.TRef = TRef;
/** Returns true if the given schema is TString */ /** Returns true if the given schema is TString */
function TString(schema) { function TString(schema) {
return (IsObject(schema) && return (IsObject(schema) &&
schema[Types.Kind] === 'String' && schema[Types.Kind] === 'String' &&
schema.type === 'string' && schema.type === 'string' &&
IsOptionalString(schema.$id) && IsOptionalString(schema.$id) &&
IsOptionalNumber(schema.minLength) && IsOptionalNumber(schema.minLength) &&
IsOptionalNumber(schema.maxLength) && IsOptionalNumber(schema.maxLength) &&
IsOptionalPattern(schema.pattern) && IsOptionalPattern(schema.pattern) &&
IsOptionalFormat(schema.format)); IsOptionalFormat(schema.format));
} }
TypeGuard.TString = TString; TypeGuard.TString = TString;
/** Returns true if the given schema is TTuple */ /** Returns true if the given schema is TTuple */
function TTuple(schema) { 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)) { 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; return false;
} }
if (schema.items === undefined && schema.additionalItems === undefined && schema.minItems === 0) { if (schema.items === undefined && schema.additionalItems === undefined && schema.minItems === 0) {
return true; return true;
} }
if (!IsArray(schema.items)) { if (!IsArray(schema.items)) {
return false; return false;
} }
for (const inner of schema.items) { for (const inner of schema.items) {
if (!TSchema(inner)) if (!TSchema(inner))
return false; return false;
} }
return true; return true;
} }
TypeGuard.TTuple = TTuple; TypeGuard.TTuple = TTuple;
/** Returns true if the given schema is TUndefined */ /** Returns true if the given schema is TUndefined */
function TUndefined(schema) { function TUndefined(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Undefined' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.specialized === 'Undefined'; return IsObject(schema) && schema[Types.Kind] === 'Undefined' && schema.type === 'object' && IsOptionalString(schema.$id) && schema.specialized === 'Undefined';
} }
TypeGuard.TUndefined = TUndefined; TypeGuard.TUndefined = TUndefined;
/** Returns true if the given schema is TUnion */ /** Returns true if the given schema is TUnion */
function TUnion(schema) { function TUnion(schema) {
if (!(IsObject(schema) && schema[Types.Kind] === 'Union' && IsArray(schema.anyOf) && IsOptionalString(schema.$id))) { if (!(IsObject(schema) && schema[Types.Kind] === 'Union' && IsArray(schema.anyOf) && IsOptionalString(schema.$id))) {
return false; return false;
} }
for (const inner of schema.anyOf) { for (const inner of schema.anyOf) {
if (!TSchema(inner)) if (!TSchema(inner))
return false; return false;
} }
return true; return true;
} }
TypeGuard.TUnion = TUnion; TypeGuard.TUnion = TUnion;
/** Returns true if the given schema is TUint8Array */ /** Returns true if the given schema is TUint8Array */
function TUint8Array(schema) { function TUint8Array(schema) {
return (IsObject(schema) && return (IsObject(schema) &&
schema[Types.Kind] === 'Uint8Array' && schema[Types.Kind] === 'Uint8Array' &&
schema.type === 'object' && schema.type === 'object' &&
IsOptionalString(schema.$id) && IsOptionalString(schema.$id) &&
schema.specialized === 'Uint8Array' && schema.specialized === 'Uint8Array' &&
IsOptionalNumber(schema.minByteLength) && IsOptionalNumber(schema.minByteLength) &&
IsOptionalNumber(schema.maxByteLength)); IsOptionalNumber(schema.maxByteLength));
} }
TypeGuard.TUint8Array = TUint8Array; TypeGuard.TUint8Array = TUint8Array;
/** Returns true if the given schema is TUnknown */ /** Returns true if the given schema is TUnknown */
function TUnknown(schema) { function TUnknown(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Unknown' && IsOptionalString(schema.$id); return IsObject(schema) && schema[Types.Kind] === 'Unknown' && IsOptionalString(schema.$id);
} }
TypeGuard.TUnknown = TUnknown; TypeGuard.TUnknown = TUnknown;
/** Returns true if the given schema is TVoid */ /** Returns true if the given schema is TVoid */
function TVoid(schema) { function TVoid(schema) {
return IsObject(schema) && schema[Types.Kind] === 'Void' && schema.type === 'null' && IsOptionalString(schema.$id); return IsObject(schema) && schema[Types.Kind] === 'Void' && schema.type === 'null' && IsOptionalString(schema.$id);
} }
TypeGuard.TVoid = TVoid; TypeGuard.TVoid = TVoid;
/** Returns true if the given schema is TSchema */ /** Returns true if the given schema is TSchema */
function TSchema(schema) { function TSchema(schema) {
return (TAny(schema) || return (TAny(schema) ||
TArray(schema) || TArray(schema) ||
TBoolean(schema) || TBoolean(schema) ||
TConstructor(schema) || TConstructor(schema) ||
TFunction(schema) || TFunction(schema) ||
TInteger(schema) || TInteger(schema) ||
TLiteral(schema) || TLiteral(schema) ||
TNever(schema) || TNever(schema) ||
TNull(schema) || TNull(schema) ||
TNumber(schema) || TNumber(schema) ||
TObject(schema) || TObject(schema) ||
TPromise(schema) || TPromise(schema) ||
TRecord(schema) || TRecord(schema) ||
TSelf(schema) || TSelf(schema) ||
TRef(schema) || TRef(schema) ||
TString(schema) || TString(schema) ||
TTuple(schema) || TTuple(schema) ||
TUndefined(schema) || TUndefined(schema) ||
TUnion(schema) || TUnion(schema) ||
TUint8Array(schema) || TUint8Array(schema) ||
TUnknown(schema) || TUnknown(schema) ||
TVoid(schema)); TVoid(schema));
} }
TypeGuard.TSchema = TSchema; TypeGuard.TSchema = TSchema;
/** Asserts if this schema and associated references are valid. */ /** Asserts if this schema and associated references are valid. */
function Assert(schema, references = []) { function Assert(schema, references = []) {
if (!TSchema(schema)) if (!TSchema(schema))
throw new TypeGuardInvalidTypeError(schema); throw new TypeGuardInvalidTypeError(schema);
for (const schema of references) { for (const schema of references) {
if (!TSchema(schema)) if (!TSchema(schema))
throw new TypeGuardInvalidTypeError(schema); throw new TypeGuardInvalidTypeError(schema);
} }
} }
TypeGuard.Assert = Assert; TypeGuard.Assert = Assert;
})(TypeGuard = exports.TypeGuard || (exports.TypeGuard = {})); })(TypeGuard = exports.TypeGuard || (exports.TypeGuard = {}));

View File

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

View File

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

View File

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

View File

@@ -1,40 +1,40 @@
{ {
"name": "@sinclair/typebox", "name": "@sinclair/typebox",
"version": "0.24.51", "version": "0.24.51",
"description": "JSONSchema Type Builder with Static Type Resolution for TypeScript", "description": "JSONSchema Type Builder with Static Type Resolution for TypeScript",
"keywords": [ "keywords": [
"typescript", "typescript",
"json-schema", "json-schema",
"validate", "validate",
"typecheck" "typecheck"
], ],
"author": "sinclairzx81", "author": "sinclairzx81",
"license": "MIT", "license": "MIT",
"main": "./typebox.js", "main": "./typebox.js",
"types": "./typebox.d.ts", "types": "./typebox.d.ts",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://github.com/sinclairzx81/typebox" "url": "https://github.com/sinclairzx81/typebox"
}, },
"scripts": { "scripts": {
"clean": "hammer task clean", "clean": "hammer task clean",
"format": "hammer task format", "format": "hammer task format",
"start": "hammer task start", "start": "hammer task start",
"test": "hammer task test", "test": "hammer task test",
"benchmark": "hammer task benchmark", "benchmark": "hammer task benchmark",
"build": "hammer task build", "build": "hammer task build",
"publish": "hammer task publish" "publish": "hammer task publish"
}, },
"devDependencies": { "devDependencies": {
"@sinclair/hammer": "^0.17.1", "@sinclair/hammer": "^0.17.1",
"@types/chai": "^4.3.3", "@types/chai": "^4.3.3",
"@types/mocha": "^9.1.1", "@types/mocha": "^9.1.1",
"@types/node": "^18.7.13", "@types/node": "^18.7.13",
"ajv": "^8.11.0", "ajv": "^8.11.0",
"ajv-formats": "^2.1.1", "ajv-formats": "^2.1.1",
"chai": "^4.3.6", "chai": "^4.3.6",
"mocha": "^9.2.2", "mocha": "^9.2.2",
"prettier": "^2.7.1", "prettier": "^2.7.1",
"typescript": "^4.8.2" "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 Kind: unique symbol;
export declare const Hint: unique symbol; export declare const Hint: unique symbol;
export declare const Modifier: unique symbol; export declare const Modifier: unique symbol;
export declare type TModifier = TReadonlyOptional<TSchema> | TOptional<TSchema> | TReadonly<TSchema>; export declare type TModifier = TReadonlyOptional<TSchema> | TOptional<TSchema> | TReadonly<TSchema>;
export declare type TReadonly<T extends TSchema> = T & { export declare type TReadonly<T extends TSchema> = T & {
[Modifier]: 'Readonly'; [Modifier]: 'Readonly';
}; };
export declare type TOptional<T extends TSchema> = T & { export declare type TOptional<T extends TSchema> = T & {
[Modifier]: 'Optional'; [Modifier]: 'Optional';
}; };
export declare type TReadonlyOptional<T extends TSchema> = T & { export declare type TReadonlyOptional<T extends TSchema> = T & {
[Modifier]: 'ReadonlyOptional'; [Modifier]: 'ReadonlyOptional';
}; };
export interface SchemaOptions { export interface SchemaOptions {
$schema?: string; $schema?: string;
/** Id for this schema */ /** Id for this schema */
$id?: string; $id?: string;
/** Title of this schema */ /** Title of this schema */
title?: string; title?: string;
/** Description of this schema */ /** Description of this schema */
description?: string; description?: string;
/** Default value for this schema */ /** Default value for this schema */
default?: any; default?: any;
/** Example values matching this schema. */ /** Example values matching this schema. */
examples?: any; examples?: any;
[prop: string]: any; [prop: string]: any;
} }
export interface TSchema extends SchemaOptions { export interface TSchema extends SchemaOptions {
[Kind]: string; [Kind]: string;
[Hint]?: string; [Hint]?: string;
[Modifier]?: string; [Modifier]?: string;
params: unknown[]; params: unknown[];
static: 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 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 { export interface NumericOptions extends SchemaOptions {
exclusiveMaximum?: number; exclusiveMaximum?: number;
exclusiveMinimum?: number; exclusiveMinimum?: number;
maximum?: number; maximum?: number;
minimum?: number; minimum?: number;
multipleOf?: number; multipleOf?: number;
} }
export declare type TNumeric = TInteger | TNumber; export declare type TNumeric = TInteger | TNumber;
export interface TAny extends TSchema { export interface TAny extends TSchema {
[Kind]: 'Any'; [Kind]: 'Any';
static: any; static: any;
} }
export interface ArrayOptions extends SchemaOptions { export interface ArrayOptions extends SchemaOptions {
uniqueItems?: boolean; uniqueItems?: boolean;
minItems?: number; minItems?: number;
maxItems?: number; maxItems?: number;
} }
export interface TArray<T extends TSchema = TSchema> extends TSchema, ArrayOptions { export interface TArray<T extends TSchema = TSchema> extends TSchema, ArrayOptions {
[Kind]: 'Array'; [Kind]: 'Array';
static: Array<Static<T, this['params']>>; static: Array<Static<T, this['params']>>;
type: 'array'; type: 'array';
items: T; items: T;
} }
export interface TBoolean extends TSchema { export interface TBoolean extends TSchema {
[Kind]: 'Boolean'; [Kind]: 'Boolean';
static: boolean; static: boolean;
type: 'boolean'; type: 'boolean';
} }
export declare type TConstructorParameters<T extends TConstructor<TSchema[], TSchema>> = TTuple<T['parameters']>; 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 TInstanceType<T extends TConstructor<TSchema[], TSchema>> = T['returns'];
export declare type StaticContructorParameters<T extends readonly TSchema[], P extends unknown[]> = [...{ export declare type StaticContructorParameters<T extends readonly TSchema[], P extends unknown[]> = [...{
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never; [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 { export interface TConstructor<T extends TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Constructor'; [Kind]: 'Constructor';
static: new (...param: StaticContructorParameters<T, this['params']>) => Static<U, this['params']>; static: new (...param: StaticContructorParameters<T, this['params']>) => Static<U, this['params']>;
type: 'constructor'; type: 'constructor';
parameters: T; parameters: T;
returns: U; returns: U;
} }
export interface TEnumOption<T> { export interface TEnumOption<T> {
type: 'number' | 'string'; type: 'number' | 'string';
const: T; const: T;
} }
export interface TEnum<T extends Record<string, string | number> = Record<string, string | number>> extends TSchema { export interface TEnum<T extends Record<string, string | number> = Record<string, string | number>> extends TSchema {
[Kind]: 'Union'; [Kind]: 'Union';
static: T[keyof T]; static: T[keyof T];
anyOf: TLiteral<string | number>[]; anyOf: TLiteral<string | number>[];
} }
export declare type TParameters<T extends TFunction> = TTuple<T['parameters']>; export declare type TParameters<T extends TFunction> = TTuple<T['parameters']>;
export declare type TReturnType<T extends TFunction> = T['returns']; export declare type TReturnType<T extends TFunction> = T['returns'];
export declare type StaticFunctionParameters<T extends readonly TSchema[], P extends unknown[]> = [...{ export declare type StaticFunctionParameters<T extends readonly TSchema[], P extends unknown[]> = [...{
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never; [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 { export interface TFunction<T extends readonly TSchema[] = TSchema[], U extends TSchema = TSchema> extends TSchema {
[Kind]: 'Function'; [Kind]: 'Function';
static: (...param: StaticFunctionParameters<T, this['params']>) => Static<U, this['params']>; static: (...param: StaticFunctionParameters<T, this['params']>) => Static<U, this['params']>;
type: 'function'; type: 'function';
parameters: T; parameters: T;
returns: U; returns: U;
} }
export interface TInteger extends TSchema, NumericOptions { export interface TInteger extends TSchema, NumericOptions {
[Kind]: 'Integer'; [Kind]: 'Integer';
static: number; static: number;
type: 'integer'; 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 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[]> = { export declare type IntersectEvaluate<T extends readonly TSchema[], P extends unknown[]> = {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never; [K in keyof T]: T[K] extends TSchema ? Static<T[K], P> : never;
}; };
export declare type IntersectProperties<T extends readonly TObject[]> = { export declare type IntersectProperties<T extends readonly TObject[]> = {
[K in keyof T]: T[K] extends TObject<infer P> ? P : {}; [K in keyof T]: T[K] extends TObject<infer P> ? P : {};
}; };
export interface TIntersect<T extends TObject[] = TObject[]> extends TObject { export interface TIntersect<T extends TObject[] = TObject[]> extends TObject {
static: IntersectReduce<unknown, IntersectEvaluate<T, this['params']>>; static: IntersectReduce<unknown, IntersectEvaluate<T, this['params']>>;
properties: IntersectReduce<unknown, IntersectProperties<T>>; 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 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 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 UnionToTuple<U, L = UnionLast<U>> = [U] extends [never] ? [] : [...UnionToTuple<Exclude<U, L>>, L];
export declare type UnionStringLiteralToTuple<T> = T extends TUnion<infer L> ? { export declare type UnionStringLiteralToTuple<T> = T extends TUnion<infer L> ? {
[I in keyof L]: L[I] extends TLiteral<infer C> ? C : never; [I in keyof L]: L[I] extends TLiteral<infer C> ? C : never;
} : never; } : never;
export declare type UnionLiteralsFromObject<T extends TObject> = { export declare type UnionLiteralsFromObject<T extends TObject> = {
[K in ObjectPropertyKeys<T>]: TLiteral<K>; [K in ObjectPropertyKeys<T>]: TLiteral<K>;
} extends infer R ? UnionToTuple<R[keyof R]> : never; } extends infer R ? UnionToTuple<R[keyof R]> : never;
export interface TKeyOf<T extends TObject> extends TUnion<UnionLiteralsFromObject<T>> { export interface TKeyOf<T extends TObject> extends TUnion<UnionLiteralsFromObject<T>> {
} }
export declare type TLiteralValue = string | number | boolean; export declare type TLiteralValue = string | number | boolean;
export interface TLiteral<T extends TLiteralValue = TLiteralValue> extends TSchema { export interface TLiteral<T extends TLiteralValue = TLiteralValue> extends TSchema {
[Kind]: 'Literal'; [Kind]: 'Literal';
static: T; static: T;
const: T; const: T;
} }
export interface TNever extends TSchema { export interface TNever extends TSchema {
[Kind]: 'Never'; [Kind]: 'Never';
static: never; static: never;
allOf: [{ allOf: [{
type: 'boolean'; type: 'boolean';
const: false; const: false;
}, { }, {
type: 'boolean'; type: 'boolean';
const: true; const: true;
}]; }];
} }
export interface TNull extends TSchema { export interface TNull extends TSchema {
[Kind]: 'Null'; [Kind]: 'Null';
static: null; static: null;
type: 'null'; type: 'null';
} }
export interface TNumber extends TSchema, NumericOptions { export interface TNumber extends TSchema, NumericOptions {
[Kind]: 'Number'; [Kind]: 'Number';
static: number; static: number;
type: 'number'; type: 'number';
} }
export declare type ReadonlyOptionalPropertyKeys<T extends TProperties> = { export declare type ReadonlyOptionalPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TReadonlyOptional<TSchema> ? K : never; [K in keyof T]: T[K] extends TReadonlyOptional<TSchema> ? K : never;
}[keyof T]; }[keyof T];
export declare type ReadonlyPropertyKeys<T extends TProperties> = { export declare type ReadonlyPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TReadonly<TSchema> ? K : never; [K in keyof T]: T[K] extends TReadonly<TSchema> ? K : never;
}[keyof T]; }[keyof T];
export declare type OptionalPropertyKeys<T extends TProperties> = { export declare type OptionalPropertyKeys<T extends TProperties> = {
[K in keyof T]: T[K] extends TOptional<TSchema> ? K : never; [K in keyof T]: T[K] extends TOptional<TSchema> ? K : never;
}[keyof T]; }[keyof T];
export declare type RequiredPropertyKeys<T extends TProperties> = keyof Omit<T, ReadonlyOptionalPropertyKeys<T> | ReadonlyPropertyKeys<T> | OptionalPropertyKeys<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[]> = { export declare type PropertiesReduce<T extends TProperties, P extends unknown[]> = {
readonly [K in ReadonlyOptionalPropertyKeys<T>]?: Static<T[K], P>; readonly [K in ReadonlyOptionalPropertyKeys<T>]?: Static<T[K], P>;
} & { } & {
readonly [K in ReadonlyPropertyKeys<T>]: Static<T[K], P>; readonly [K in ReadonlyPropertyKeys<T>]: Static<T[K], P>;
} & { } & {
[K in OptionalPropertyKeys<T>]?: Static<T[K], P>; [K in OptionalPropertyKeys<T>]?: Static<T[K], P>;
} & { } & {
[K in RequiredPropertyKeys<T>]: Static<T[K], P>; [K in RequiredPropertyKeys<T>]: Static<T[K], P>;
} extends infer R ? { } extends infer R ? {
[K in keyof R]: R[K]; [K in keyof R]: R[K];
} : never; } : never;
export declare type TRecordProperties<K extends TUnion<TLiteral[]>, T extends TSchema> = Static<K> extends string ? { export declare type TRecordProperties<K extends TUnion<TLiteral[]>, T extends TSchema> = Static<K> extends string ? {
[X in Static<K>]: T; [X in Static<K>]: T;
} : never; } : never;
export interface TProperties { export interface TProperties {
[key: string]: TSchema; [key: string]: TSchema;
} }
export declare type ObjectProperties<T> = T extends TObject<infer U> ? U : never; 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 ObjectPropertyKeys<T> = T extends TObject<infer U> ? keyof U : never;
export declare type TAdditionalProperties = undefined | TSchema | boolean; export declare type TAdditionalProperties = undefined | TSchema | boolean;
export interface ObjectOptions extends SchemaOptions { export interface ObjectOptions extends SchemaOptions {
additionalProperties?: TAdditionalProperties; additionalProperties?: TAdditionalProperties;
minProperties?: number; minProperties?: number;
maxProperties?: number; maxProperties?: number;
} }
export interface TObject<T extends TProperties = TProperties> extends TSchema, ObjectOptions { export interface TObject<T extends TProperties = TProperties> extends TSchema, ObjectOptions {
[Kind]: 'Object'; [Kind]: 'Object';
static: PropertiesReduce<T, this['params']>; static: PropertiesReduce<T, this['params']>;
additionalProperties?: TAdditionalProperties; additionalProperties?: TAdditionalProperties;
type: 'object'; type: 'object';
properties: T; properties: T;
required?: string[]; required?: string[];
} }
export interface TOmit<T extends TObject, Properties extends ObjectPropertyKeys<T>[]> extends TObject, ObjectOptions { export interface TOmit<T extends TObject, Properties extends ObjectPropertyKeys<T>[]> extends TObject, ObjectOptions {
static: Omit<Static<T, this['params']>, Properties[number]>; static: Omit<Static<T, this['params']>, Properties[number]>;
properties: T extends TObject ? Omit<T['properties'], Properties[number]> : never; properties: T extends TObject ? Omit<T['properties'], Properties[number]> : never;
} }
export interface TPartial<T extends TObject> extends TObject { export interface TPartial<T extends TObject> extends TObject {
static: Partial<Static<T, this['params']>>; static: Partial<Static<T, this['params']>>;
properties: { 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]>; [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<{ export declare type TPick<T extends TObject, Properties extends ObjectPropertyKeys<T>[]> = TObject<{
[K in Properties[number]]: T['properties'][K]; [K in Properties[number]]: T['properties'][K];
}>; }>;
export interface TPromise<T extends TSchema = TSchema> extends TSchema { export interface TPromise<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Promise'; [Kind]: 'Promise';
static: Promise<Static<T, this['params']>>; static: Promise<Static<T, this['params']>>;
type: 'promise'; type: 'promise';
item: TSchema; item: TSchema;
} }
export declare type TRecordKey = TString | TNumeric | TUnion<TLiteral<any>[]>; export declare type TRecordKey = TString | TNumeric | TUnion<TLiteral<any>[]>;
export interface TRecord<K extends TRecordKey = TRecordKey, T extends TSchema = TSchema> extends TSchema { export interface TRecord<K extends TRecordKey = TRecordKey, T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Record'; [Kind]: 'Record';
static: Record<Static<K>, Static<T, this['params']>>; static: Record<Static<K>, Static<T, this['params']>>;
type: 'object'; type: 'object';
patternProperties: { patternProperties: {
[pattern: string]: T; [pattern: string]: T;
}; };
additionalProperties: false; additionalProperties: false;
} }
export interface TSelf extends TSchema { export interface TSelf extends TSchema {
[Kind]: 'Self'; [Kind]: 'Self';
static: this['params'][0]; static: this['params'][0];
$ref: string; $ref: string;
} }
export declare type TRecursiveReduce<T extends TSchema> = Static<T, [TRecursiveReduce<T>]>; export declare type TRecursiveReduce<T extends TSchema> = Static<T, [TRecursiveReduce<T>]>;
export interface TRecursive<T extends TSchema> extends TSchema { export interface TRecursive<T extends TSchema> extends TSchema {
static: TRecursiveReduce<T>; static: TRecursiveReduce<T>;
} }
export interface TRef<T extends TSchema = TSchema> extends TSchema { export interface TRef<T extends TSchema = TSchema> extends TSchema {
[Kind]: 'Ref'; [Kind]: 'Ref';
static: Static<T, this['params']>; static: Static<T, this['params']>;
$ref: string; $ref: string;
} }
export interface TRequired<T extends TObject | TRef<TObject>> extends TObject { export interface TRequired<T extends TObject | TRef<TObject>> extends TObject {
static: Required<Static<T, this['params']>>; static: Required<Static<T, this['params']>>;
properties: { 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]; [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 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 { export interface StringOptions<Format extends string> extends SchemaOptions {
minLength?: number; minLength?: number;
maxLength?: number; maxLength?: number;
pattern?: string; pattern?: string;
format?: Format; format?: Format;
contentEncoding?: '7bit' | '8bit' | 'binary' | 'quoted-printable' | 'base64'; contentEncoding?: '7bit' | '8bit' | 'binary' | 'quoted-printable' | 'base64';
contentMediaType?: string; contentMediaType?: string;
} }
export interface TString<Format extends string = string> extends TSchema, StringOptions<Format> { export interface TString<Format extends string = string> extends TSchema, StringOptions<Format> {
[Kind]: 'String'; [Kind]: 'String';
static: string; static: string;
type: 'string'; type: 'string';
} }
export declare type TupleToArray<T extends TTuple<TSchema[]>> = T extends TTuple<infer R> ? R : never; export declare type TupleToArray<T extends TTuple<TSchema[]>> = T extends TTuple<infer R> ? R : never;
export interface TTuple<T extends TSchema[] = TSchema[]> extends TSchema { export interface TTuple<T extends TSchema[] = TSchema[]> extends TSchema {
[Kind]: 'Tuple'; [Kind]: 'Tuple';
static: { static: {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : T[K]; [K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : T[K];
}; };
type: 'array'; type: 'array';
items?: T; items?: T;
additionalItems?: false; additionalItems?: false;
minItems: number; minItems: number;
maxItems: number; maxItems: number;
} }
export interface TUndefined extends TSchema { export interface TUndefined extends TSchema {
[Kind]: 'Undefined'; [Kind]: 'Undefined';
specialized: 'Undefined'; specialized: 'Undefined';
static: undefined; static: undefined;
type: 'object'; type: 'object';
} }
export interface TUnion<T extends TSchema[] = TSchema[]> extends TSchema { export interface TUnion<T extends TSchema[] = TSchema[]> extends TSchema {
[Kind]: 'Union'; [Kind]: 'Union';
static: { static: {
[K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : never; [K in keyof T]: T[K] extends TSchema ? Static<T[K], this['params']> : never;
}[number]; }[number];
anyOf: T; anyOf: T;
} }
export interface Uint8ArrayOptions extends SchemaOptions { export interface Uint8ArrayOptions extends SchemaOptions {
maxByteLength?: number; maxByteLength?: number;
minByteLength?: number; minByteLength?: number;
} }
export interface TUint8Array extends TSchema, Uint8ArrayOptions { export interface TUint8Array extends TSchema, Uint8ArrayOptions {
[Kind]: 'Uint8Array'; [Kind]: 'Uint8Array';
static: Uint8Array; static: Uint8Array;
specialized: 'Uint8Array'; specialized: 'Uint8Array';
type: 'object'; type: 'object';
} }
export interface TUnknown extends TSchema { export interface TUnknown extends TSchema {
[Kind]: 'Unknown'; [Kind]: 'Unknown';
static: unknown; static: unknown;
} }
export interface UnsafeOptions extends SchemaOptions { export interface UnsafeOptions extends SchemaOptions {
[Kind]?: string; [Kind]?: string;
} }
export interface TUnsafe<T> extends TSchema { export interface TUnsafe<T> extends TSchema {
[Kind]: string; [Kind]: string;
static: T; static: T;
} }
export interface TVoid extends TSchema { export interface TVoid extends TSchema {
[Kind]: 'Void'; [Kind]: 'Void';
static: void; static: void;
type: 'null'; type: 'null';
} }
/** Creates a static type from a TypeBox type */ /** Creates a static type from a TypeBox type */
export declare type Static<T extends TSchema, P extends unknown[] = []> = (T & { export declare type Static<T extends TSchema, P extends unknown[] = []> = (T & {
params: P; params: P;
})['static']; })['static'];
export declare class TypeBuilder { export declare class TypeBuilder {
/** Creates a readonly optional property */ /** Creates a readonly optional property */
ReadonlyOptional<T extends TSchema>(item: T): TReadonlyOptional<T>; ReadonlyOptional<T extends TSchema>(item: T): TReadonlyOptional<T>;
/** Creates a readonly property */ /** Creates a readonly property */
Readonly<T extends TSchema>(item: T): TReadonly<T>; Readonly<T extends TSchema>(item: T): TReadonly<T>;
/** Creates a optional property */ /** Creates a optional property */
Optional<T extends TSchema>(item: T): TOptional<T>; Optional<T extends TSchema>(item: T): TOptional<T>;
/** Creates a any type */ /** Creates a any type */
Any(options?: SchemaOptions): TAny; Any(options?: SchemaOptions): TAny;
/** Creates a array type */ /** Creates a array type */
Array<T extends TSchema>(items: T, options?: ArrayOptions): TArray<T>; Array<T extends TSchema>(items: T, options?: ArrayOptions): TArray<T>;
/** Creates a boolean type */ /** Creates a boolean type */
Boolean(options?: SchemaOptions): TBoolean; Boolean(options?: SchemaOptions): TBoolean;
/** Creates a tuple type from this constructors parameters */ /** Creates a tuple type from this constructors parameters */
ConstructorParameters<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TConstructorParameters<T>; ConstructorParameters<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TConstructorParameters<T>;
/** Creates a constructor type */ /** Creates a constructor type */
Constructor<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TConstructor<TupleToArray<T>, U>; Constructor<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TConstructor<TupleToArray<T>, U>;
/** Creates a constructor type */ /** Creates a constructor type */
Constructor<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TConstructor<T, U>; Constructor<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TConstructor<T, U>;
/** Creates a enum type */ /** Creates a enum type */
Enum<T extends Record<string, string | number>>(item: T, options?: SchemaOptions): TEnum<T>; Enum<T extends Record<string, string | number>>(item: T, options?: SchemaOptions): TEnum<T>;
/** Creates a function type */ /** Creates a function type */
Function<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TFunction<TupleToArray<T>, U>; Function<T extends TTuple<TSchema[]>, U extends TSchema>(parameters: T, returns: U, options?: SchemaOptions): TFunction<TupleToArray<T>, U>;
/** Creates a function type */ /** Creates a function type */
Function<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TFunction<T, U>; Function<T extends TSchema[], U extends TSchema>(parameters: [...T], returns: U, options?: SchemaOptions): TFunction<T, U>;
/** Creates a type from this constructors instance type */ /** Creates a type from this constructors instance type */
InstanceType<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TInstanceType<T>; InstanceType<T extends TConstructor<any[], any>>(schema: T, options?: SchemaOptions): TInstanceType<T>;
/** Creates a integer type */ /** Creates a integer type */
Integer(options?: NumericOptions): TInteger; Integer(options?: NumericOptions): TInteger;
/** Creates a intersect type. */ /** Creates a intersect type. */
Intersect<T extends TObject[]>(objects: [...T], options?: ObjectOptions): TIntersect<T>; Intersect<T extends TObject[]>(objects: [...T], options?: ObjectOptions): TIntersect<T>;
/** Creates a keyof type */ /** Creates a keyof type */
KeyOf<T extends TObject>(object: T, options?: SchemaOptions): TKeyOf<T>; KeyOf<T extends TObject>(object: T, options?: SchemaOptions): TKeyOf<T>;
/** Creates a literal type. */ /** Creates a literal type. */
Literal<T extends TLiteralValue>(value: T, options?: SchemaOptions): TLiteral<T>; Literal<T extends TLiteralValue>(value: T, options?: SchemaOptions): TLiteral<T>;
/** Creates a never type */ /** Creates a never type */
Never(options?: SchemaOptions): TNever; Never(options?: SchemaOptions): TNever;
/** Creates a null type */ /** Creates a null type */
Null(options?: SchemaOptions): TNull; Null(options?: SchemaOptions): TNull;
/** Creates a number type */ /** Creates a number type */
Number(options?: NumericOptions): TNumber; Number(options?: NumericOptions): TNumber;
/** Creates an object type with the given properties */ /** Creates an object type with the given properties */
Object<T extends TProperties>(properties: T, options?: ObjectOptions): TObject<T>; Object<T extends TProperties>(properties: T, options?: ObjectOptions): TObject<T>;
/** Creates a new object whose properties are omitted from the given object */ /** 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>>; 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 */ /** 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>; 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 */ /** Creates a tuple type from this functions parameters */
Parameters<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TParameters<T>; Parameters<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TParameters<T>;
/** Creates an object type whose properties are all optional */ /** Creates an object type whose properties are all optional */
Partial<T extends TObject>(schema: T, options?: ObjectOptions): TPartial<T>; Partial<T extends TObject>(schema: T, options?: ObjectOptions): TPartial<T>;
/** Creates a object whose properties are picked from the given object */ /** 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>>; 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 */ /** 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>; 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. */ /** Creates a promise type. This type cannot be represented in schema. */
Promise<T extends TSchema>(item: T, options?: SchemaOptions): TPromise<T>; Promise<T extends TSchema>(item: T, options?: SchemaOptions): TPromise<T>;
/** Creates an object whose properties are derived from the given string literal union. */ /** 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>>; Record<K extends TUnion<TLiteral[]>, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): TObject<TRecordProperties<K, T>>;
/** Creates a record type */ /** Creates a record type */
Record<K extends TString | TNumeric, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): TRecord<K, T>; Record<K extends TString | TNumeric, T extends TSchema>(key: K, schema: T, options?: ObjectOptions): TRecord<K, T>;
/** Creates a recursive object type */ /** Creates a recursive object type */
Recursive<T extends TSchema>(callback: (self: TSelf) => T, options?: SchemaOptions): TRecursive<T>; Recursive<T extends TSchema>(callback: (self: TSelf) => T, options?: SchemaOptions): TRecursive<T>;
/** Creates a reference schema */ /** Creates a reference schema */
Ref<T extends TSchema>(schema: T, options?: SchemaOptions): TRef<T>; Ref<T extends TSchema>(schema: T, options?: SchemaOptions): TRef<T>;
/** Creates a string type from a regular expression */ /** Creates a string type from a regular expression */
RegEx(regex: RegExp, options?: SchemaOptions): TString; RegEx(regex: RegExp, options?: SchemaOptions): TString;
/** Creates an object type whose properties are all required */ /** Creates an object type whose properties are all required */
Required<T extends TObject>(schema: T, options?: SchemaOptions): TRequired<T>; Required<T extends TObject>(schema: T, options?: SchemaOptions): TRequired<T>;
/** Creates a type from this functions return type */ /** Creates a type from this functions return type */
ReturnType<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TReturnType<T>; ReturnType<T extends TFunction<any[], any>>(schema: T, options?: SchemaOptions): TReturnType<T>;
/** Removes Kind and Modifier symbol property keys from this schema */ /** Removes Kind and Modifier symbol property keys from this schema */
Strict<T extends TSchema>(schema: T): T; Strict<T extends TSchema>(schema: T): T;
/** Creates a string type */ /** Creates a string type */
String<Format extends string>(options?: StringOptions<StringFormatOption | Format>): TString<Format>; String<Format extends string>(options?: StringOptions<StringFormatOption | Format>): TString<Format>;
/** Creates a tuple type */ /** Creates a tuple type */
Tuple<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TTuple<T>; Tuple<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TTuple<T>;
/** Creates a undefined type */ /** Creates a undefined type */
Undefined(options?: SchemaOptions): TUndefined; Undefined(options?: SchemaOptions): TUndefined;
/** Creates a union type */ /** Creates a union type */
Union(items: [], options?: SchemaOptions): TNever; Union(items: [], options?: SchemaOptions): TNever;
Union<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TUnion<T>; Union<T extends TSchema[]>(items: [...T], options?: SchemaOptions): TUnion<T>;
/** Creates a Uint8Array type */ /** Creates a Uint8Array type */
Uint8Array(options?: Uint8ArrayOptions): TUint8Array; Uint8Array(options?: Uint8ArrayOptions): TUint8Array;
/** Creates an unknown type */ /** Creates an unknown type */
Unknown(options?: SchemaOptions): TUnknown; Unknown(options?: SchemaOptions): TUnknown;
/** Creates a user defined schema that infers as type T */ /** Creates a user defined schema that infers as type T */
Unsafe<T>(options?: UnsafeOptions): TUnsafe<T>; Unsafe<T>(options?: UnsafeOptions): TUnsafe<T>;
/** Creates a void type */ /** Creates a void type */
Void(options?: SchemaOptions): TVoid; Void(options?: SchemaOptions): TVoid;
/** Use this function to return TSchema with static and params omitted */ /** Use this function to return TSchema with static and params omitted */
protected Create<T>(schema: Omit<T, 'static' | 'params'>): T; protected Create<T>(schema: Omit<T, 'static' | 'params'>): T;
/** Clones the given value */ /** Clones the given value */
protected Clone(value: any): any; protected Clone(value: any): any;
} }
/** JSON Schema Type Builder with Static Type Resolution for TypeScript */ /** JSON Schema Type Builder with Static Type Resolution for TypeScript */
export declare const Type: TypeBuilder; export declare const Type: TypeBuilder;

View File

@@ -1,383 +1,383 @@
"use strict"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox @sinclair/typebox
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.Type = exports.TypeBuilder = exports.Modifier = exports.Hint = exports.Kind = void 0; exports.Type = exports.TypeBuilder = exports.Modifier = exports.Hint = exports.Kind = void 0;
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// Symbols // Symbols
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
exports.Kind = Symbol.for('TypeBox.Kind'); exports.Kind = Symbol.for('TypeBox.Kind');
exports.Hint = Symbol.for('TypeBox.Hint'); exports.Hint = Symbol.for('TypeBox.Hint');
exports.Modifier = Symbol.for('TypeBox.Modifier'); exports.Modifier = Symbol.for('TypeBox.Modifier');
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
// TypeBuilder // TypeBuilder
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
let TypeOrdinal = 0; let TypeOrdinal = 0;
class TypeBuilder { class TypeBuilder {
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// Modifiers // Modifiers
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
/** Creates a readonly optional property */ /** Creates a readonly optional property */
ReadonlyOptional(item) { ReadonlyOptional(item) {
return { [exports.Modifier]: 'ReadonlyOptional', ...item }; return { [exports.Modifier]: 'ReadonlyOptional', ...item };
} }
/** Creates a readonly property */ /** Creates a readonly property */
Readonly(item) { Readonly(item) {
return { [exports.Modifier]: 'Readonly', ...item }; return { [exports.Modifier]: 'Readonly', ...item };
} }
/** Creates a optional property */ /** Creates a optional property */
Optional(item) { Optional(item) {
return { [exports.Modifier]: 'Optional', ...item }; return { [exports.Modifier]: 'Optional', ...item };
} }
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
// Types // Types
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
/** Creates a any type */ /** Creates a any type */
Any(options = {}) { Any(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Any' }); return this.Create({ ...options, [exports.Kind]: 'Any' });
} }
/** Creates a array type */ /** Creates a array type */
Array(items, options = {}) { Array(items, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Array', type: 'array', items }); return this.Create({ ...options, [exports.Kind]: 'Array', type: 'array', items });
} }
/** Creates a boolean type */ /** Creates a boolean type */
Boolean(options = {}) { Boolean(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Boolean', type: 'boolean' }); return this.Create({ ...options, [exports.Kind]: 'Boolean', type: 'boolean' });
} }
/** Creates a tuple type from this constructors parameters */ /** Creates a tuple type from this constructors parameters */
ConstructorParameters(schema, options = {}) { ConstructorParameters(schema, options = {}) {
return this.Tuple([...schema.parameters], { ...options }); return this.Tuple([...schema.parameters], { ...options });
} }
/** Creates a constructor type */ /** Creates a constructor type */
Constructor(parameters, returns, options = {}) { Constructor(parameters, returns, options = {}) {
if (parameters[exports.Kind] === 'Tuple') { if (parameters[exports.Kind] === 'Tuple') {
const inner = parameters.items === undefined ? [] : parameters.items; const inner = parameters.items === undefined ? [] : parameters.items;
return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'constructor', parameters: inner, returns }); return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'constructor', parameters: inner, returns });
} }
else if (globalThis.Array.isArray(parameters)) { else if (globalThis.Array.isArray(parameters)) {
return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'constructor', parameters, returns }); return this.Create({ ...options, [exports.Kind]: 'Constructor', type: 'constructor', parameters, returns });
} }
else { else {
throw new Error('TypeBuilder.Constructor: Invalid parameters'); throw new Error('TypeBuilder.Constructor: Invalid parameters');
} }
} }
/** Creates a enum type */ /** Creates a enum type */
Enum(item, options = {}) { Enum(item, options = {}) {
const values = Object.keys(item) const values = Object.keys(item)
.filter((key) => isNaN(key)) .filter((key) => isNaN(key))
.map((key) => item[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 })); 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 }); return this.Create({ ...options, [exports.Kind]: 'Union', [exports.Hint]: 'Enum', anyOf });
} }
/** Creates a function type */ /** Creates a function type */
Function(parameters, returns, options = {}) { Function(parameters, returns, options = {}) {
if (parameters[exports.Kind] === 'Tuple') { if (parameters[exports.Kind] === 'Tuple') {
const inner = parameters.items === undefined ? [] : parameters.items; const inner = parameters.items === undefined ? [] : parameters.items;
return this.Create({ ...options, [exports.Kind]: 'Function', type: 'function', parameters: inner, returns }); return this.Create({ ...options, [exports.Kind]: 'Function', type: 'function', parameters: inner, returns });
} }
else if (globalThis.Array.isArray(parameters)) { else if (globalThis.Array.isArray(parameters)) {
return this.Create({ ...options, [exports.Kind]: 'Function', type: 'function', parameters, returns }); return this.Create({ ...options, [exports.Kind]: 'Function', type: 'function', parameters, returns });
} }
else { else {
throw new Error('TypeBuilder.Function: Invalid parameters'); throw new Error('TypeBuilder.Function: Invalid parameters');
} }
} }
/** Creates a type from this constructors instance type */ /** Creates a type from this constructors instance type */
InstanceType(schema, options = {}) { InstanceType(schema, options = {}) {
return { ...options, ...this.Clone(schema.returns) }; return { ...options, ...this.Clone(schema.returns) };
} }
/** Creates a integer type */ /** Creates a integer type */
Integer(options = {}) { Integer(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Integer', type: 'integer' }); return this.Create({ ...options, [exports.Kind]: 'Integer', type: 'integer' });
} }
/** Creates a intersect type. */ /** Creates a intersect type. */
Intersect(objects, options = {}) { Intersect(objects, options = {}) {
const isOptional = (schema) => (schema[exports.Modifier] && schema[exports.Modifier] === 'Optional') || schema[exports.Modifier] === 'ReadonlyOptional'; const isOptional = (schema) => (schema[exports.Modifier] && schema[exports.Modifier] === 'Optional') || schema[exports.Modifier] === 'ReadonlyOptional';
const [required, optional] = [new Set(), new Set()]; const [required, optional] = [new Set(), new Set()];
for (const object of objects) { for (const object of objects) {
for (const [key, schema] of Object.entries(object.properties)) { for (const [key, schema] of Object.entries(object.properties)) {
if (isOptional(schema)) if (isOptional(schema))
optional.add(key); optional.add(key);
} }
} }
for (const object of objects) { for (const object of objects) {
for (const key of Object.keys(object.properties)) { for (const key of Object.keys(object.properties)) {
if (!optional.has(key)) if (!optional.has(key))
required.add(key); required.add(key);
} }
} }
const properties = {}; const properties = {};
for (const object of objects) { for (const object of objects) {
for (const [key, schema] of Object.entries(object.properties)) { for (const [key, schema] of Object.entries(object.properties)) {
properties[key] = properties[key] === undefined ? schema : { [exports.Kind]: 'Union', anyOf: [properties[key], { ...schema }] }; properties[key] = properties[key] === undefined ? schema : { [exports.Kind]: 'Union', anyOf: [properties[key], { ...schema }] };
} }
} }
if (required.size > 0) { if (required.size > 0) {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties, required: [...required] }); return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties, required: [...required] });
} }
else { else {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties }); return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties });
} }
} }
/** Creates a keyof type */ /** Creates a keyof type */
KeyOf(object, options = {}) { KeyOf(object, options = {}) {
const items = Object.keys(object.properties).map((key) => this.Create({ ...options, [exports.Kind]: 'Literal', type: 'string', const: key })); 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 }); return this.Create({ ...options, [exports.Kind]: 'Union', [exports.Hint]: 'KeyOf', anyOf: items });
} }
/** Creates a literal type. */ /** Creates a literal type. */
Literal(value, options = {}) { Literal(value, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Literal', const: value, type: typeof value }); return this.Create({ ...options, [exports.Kind]: 'Literal', const: value, type: typeof value });
} }
/** Creates a never type */ /** Creates a never type */
Never(options = {}) { Never(options = {}) {
return this.Create({ return this.Create({
...options, ...options,
[exports.Kind]: 'Never', [exports.Kind]: 'Never',
allOf: [ allOf: [
{ type: 'boolean', const: false }, { type: 'boolean', const: false },
{ type: 'boolean', const: true }, { type: 'boolean', const: true },
], ],
}); });
} }
/** Creates a null type */ /** Creates a null type */
Null(options = {}) { Null(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Null', type: 'null' }); return this.Create({ ...options, [exports.Kind]: 'Null', type: 'null' });
} }
/** Creates a number type */ /** Creates a number type */
Number(options = {}) { Number(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Number', type: 'number' }); return this.Create({ ...options, [exports.Kind]: 'Number', type: 'number' });
} }
/** Creates an object type with the given properties */ /** Creates an object type with the given properties */
Object(properties, options = {}) { Object(properties, options = {}) {
const property_names = Object.keys(properties); const property_names = Object.keys(properties);
const optional = property_names.filter((name) => { const optional = property_names.filter((name) => {
const property = properties[name]; const property = properties[name];
const modifier = property[exports.Modifier]; const modifier = property[exports.Modifier];
return modifier && (modifier === 'Optional' || modifier === 'ReadonlyOptional'); return modifier && (modifier === 'Optional' || modifier === 'ReadonlyOptional');
}); });
const required = property_names.filter((name) => !optional.includes(name)); const required = property_names.filter((name) => !optional.includes(name));
if (required.length > 0) { if (required.length > 0) {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties, required }); return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties, required });
} }
else { else {
return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties }); return this.Create({ ...options, [exports.Kind]: 'Object', type: 'object', properties });
} }
} }
/** Creates a new object whose properties are omitted from the given object */ /** Creates a new object whose properties are omitted from the given object */
Omit(schema, keys, options = {}) { Omit(schema, keys, options = {}) {
const select = keys[exports.Kind] === 'Union' ? keys.anyOf.map((schema) => schema.const) : keys; const select = keys[exports.Kind] === 'Union' ? keys.anyOf.map((schema) => schema.const) : keys;
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Omit' }; const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Omit' };
if (next.required) { if (next.required) {
next.required = next.required.filter((key) => !select.includes(key)); next.required = next.required.filter((key) => !select.includes(key));
if (next.required.length === 0) if (next.required.length === 0)
delete next.required; delete next.required;
} }
for (const key of Object.keys(next.properties)) { for (const key of Object.keys(next.properties)) {
if (select.includes(key)) if (select.includes(key))
delete next.properties[key]; delete next.properties[key];
} }
return this.Create(next); return this.Create(next);
} }
/** Creates a tuple type from this functions parameters */ /** Creates a tuple type from this functions parameters */
Parameters(schema, options = {}) { Parameters(schema, options = {}) {
return exports.Type.Tuple(schema.parameters, { ...options }); return exports.Type.Tuple(schema.parameters, { ...options });
} }
/** Creates an object type whose properties are all optional */ /** Creates an object type whose properties are all optional */
Partial(schema, options = {}) { Partial(schema, options = {}) {
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Partial' }; const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Partial' };
delete next.required; delete next.required;
for (const key of Object.keys(next.properties)) { for (const key of Object.keys(next.properties)) {
const property = next.properties[key]; const property = next.properties[key];
const modifer = property[exports.Modifier]; const modifer = property[exports.Modifier];
switch (modifer) { switch (modifer) {
case 'ReadonlyOptional': case 'ReadonlyOptional':
property[exports.Modifier] = 'ReadonlyOptional'; property[exports.Modifier] = 'ReadonlyOptional';
break; break;
case 'Readonly': case 'Readonly':
property[exports.Modifier] = 'ReadonlyOptional'; property[exports.Modifier] = 'ReadonlyOptional';
break; break;
case 'Optional': case 'Optional':
property[exports.Modifier] = 'Optional'; property[exports.Modifier] = 'Optional';
break; break;
default: default:
property[exports.Modifier] = 'Optional'; property[exports.Modifier] = 'Optional';
break; break;
} }
} }
return this.Create(next); return this.Create(next);
} }
/** Creates a object whose properties are picked from the given object */ /** Creates a object whose properties are picked from the given object */
Pick(schema, keys, options = {}) { Pick(schema, keys, options = {}) {
const select = keys[exports.Kind] === 'Union' ? keys.anyOf.map((schema) => schema.const) : keys; const select = keys[exports.Kind] === 'Union' ? keys.anyOf.map((schema) => schema.const) : keys;
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Pick' }; const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Pick' };
if (next.required) { if (next.required) {
next.required = next.required.filter((key) => select.includes(key)); next.required = next.required.filter((key) => select.includes(key));
if (next.required.length === 0) if (next.required.length === 0)
delete next.required; delete next.required;
} }
for (const key of Object.keys(next.properties)) { for (const key of Object.keys(next.properties)) {
if (!select.includes(key)) if (!select.includes(key))
delete next.properties[key]; delete next.properties[key];
} }
return this.Create(next); return this.Create(next);
} }
/** Creates a promise type. This type cannot be represented in schema. */ /** Creates a promise type. This type cannot be represented in schema. */
Promise(item, options = {}) { Promise(item, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Promise', type: 'promise', item }); return this.Create({ ...options, [exports.Kind]: 'Promise', type: 'promise', item });
} }
/** Creates a record type */ /** Creates a record type */
Record(key, value, options = {}) { Record(key, value, options = {}) {
// If string literal union return TObject with properties extracted from union. // If string literal union return TObject with properties extracted from union.
if (key[exports.Kind] === 'Union') { if (key[exports.Kind] === 'Union') {
return this.Object(key.anyOf.reduce((acc, literal) => { return this.Object(key.anyOf.reduce((acc, literal) => {
return { ...acc, [literal.const]: value }; return { ...acc, [literal.const]: value };
}, {}), { ...options, [exports.Hint]: 'Record' }); }, {}), { ...options, [exports.Hint]: 'Record' });
} }
// otherwise return TRecord with patternProperties // 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 : '^.*$'; const pattern = ['Integer', 'Number'].includes(key[exports.Kind]) ? '^(0|[1-9][0-9]*)$' : key[exports.Kind] === 'String' && key.pattern ? key.pattern : '^.*$';
return this.Create({ return this.Create({
...options, ...options,
[exports.Kind]: 'Record', [exports.Kind]: 'Record',
type: 'object', type: 'object',
patternProperties: { [pattern]: value }, patternProperties: { [pattern]: value },
additionalProperties: false, additionalProperties: false,
}); });
} }
/** Creates a recursive object type */ /** Creates a recursive object type */
Recursive(callback, options = {}) { Recursive(callback, options = {}) {
if (options.$id === undefined) if (options.$id === undefined)
options.$id = `T${TypeOrdinal++}`; options.$id = `T${TypeOrdinal++}`;
const self = callback({ [exports.Kind]: 'Self', $ref: `${options.$id}` }); const self = callback({ [exports.Kind]: 'Self', $ref: `${options.$id}` });
self.$id = options.$id; self.$id = options.$id;
return this.Create({ ...options, ...self }); return this.Create({ ...options, ...self });
} }
/** Creates a reference schema */ /** Creates a reference schema */
Ref(schema, options = {}) { Ref(schema, options = {}) {
if (schema.$id === undefined) if (schema.$id === undefined)
throw Error('TypeBuilder.Ref: Referenced schema must specify an $id'); throw Error('TypeBuilder.Ref: Referenced schema must specify an $id');
return this.Create({ ...options, [exports.Kind]: 'Ref', $ref: schema.$id }); return this.Create({ ...options, [exports.Kind]: 'Ref', $ref: schema.$id });
} }
/** Creates a string type from a regular expression */ /** Creates a string type from a regular expression */
RegEx(regex, options = {}) { RegEx(regex, options = {}) {
return this.Create({ ...options, [exports.Kind]: 'String', type: 'string', pattern: regex.source }); return this.Create({ ...options, [exports.Kind]: 'String', type: 'string', pattern: regex.source });
} }
/** Creates an object type whose properties are all required */ /** Creates an object type whose properties are all required */
Required(schema, options = {}) { Required(schema, options = {}) {
const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Required' }; const next = { ...this.Clone(schema), ...options, [exports.Hint]: 'Required' };
next.required = Object.keys(next.properties); next.required = Object.keys(next.properties);
for (const key of Object.keys(next.properties)) { for (const key of Object.keys(next.properties)) {
const property = next.properties[key]; const property = next.properties[key];
const modifier = property[exports.Modifier]; const modifier = property[exports.Modifier];
switch (modifier) { switch (modifier) {
case 'ReadonlyOptional': case 'ReadonlyOptional':
property[exports.Modifier] = 'Readonly'; property[exports.Modifier] = 'Readonly';
break; break;
case 'Readonly': case 'Readonly':
property[exports.Modifier] = 'Readonly'; property[exports.Modifier] = 'Readonly';
break; break;
case 'Optional': case 'Optional':
delete property[exports.Modifier]; delete property[exports.Modifier];
break; break;
default: default:
delete property[exports.Modifier]; delete property[exports.Modifier];
break; break;
} }
} }
return this.Create(next); return this.Create(next);
} }
/** Creates a type from this functions return type */ /** Creates a type from this functions return type */
ReturnType(schema, options = {}) { ReturnType(schema, options = {}) {
return { ...options, ...this.Clone(schema.returns) }; return { ...options, ...this.Clone(schema.returns) };
} }
/** Removes Kind and Modifier symbol property keys from this schema */ /** Removes Kind and Modifier symbol property keys from this schema */
Strict(schema) { Strict(schema) {
return JSON.parse(JSON.stringify(schema)); return JSON.parse(JSON.stringify(schema));
} }
/** Creates a string type */ /** Creates a string type */
String(options = {}) { String(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'String', type: 'string' }); return this.Create({ ...options, [exports.Kind]: 'String', type: 'string' });
} }
/** Creates a tuple type */ /** Creates a tuple type */
Tuple(items, options = {}) { Tuple(items, options = {}) {
const additionalItems = false; const additionalItems = false;
const minItems = items.length; const minItems = items.length;
const maxItems = 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 }); 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); return this.Create(schema);
} }
/** Creates a undefined type */ /** Creates a undefined type */
Undefined(options = {}) { Undefined(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Undefined', type: 'object', specialized: 'Undefined' }); return this.Create({ ...options, [exports.Kind]: 'Undefined', type: 'object', specialized: 'Undefined' });
} }
Union(items, options = {}) { Union(items, options = {}) {
return items.length === 0 ? exports.Type.Never({ ...options }) : this.Create({ ...options, [exports.Kind]: 'Union', anyOf: items }); return items.length === 0 ? exports.Type.Never({ ...options }) : this.Create({ ...options, [exports.Kind]: 'Union', anyOf: items });
} }
/** Creates a Uint8Array type */ /** Creates a Uint8Array type */
Uint8Array(options = {}) { Uint8Array(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Uint8Array', type: 'object', specialized: 'Uint8Array' }); return this.Create({ ...options, [exports.Kind]: 'Uint8Array', type: 'object', specialized: 'Uint8Array' });
} }
/** Creates an unknown type */ /** Creates an unknown type */
Unknown(options = {}) { Unknown(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Unknown' }); return this.Create({ ...options, [exports.Kind]: 'Unknown' });
} }
/** Creates a user defined schema that infers as type T */ /** Creates a user defined schema that infers as type T */
Unsafe(options = {}) { Unsafe(options = {}) {
return this.Create({ ...options, [exports.Kind]: options[exports.Kind] || 'Unsafe' }); return this.Create({ ...options, [exports.Kind]: options[exports.Kind] || 'Unsafe' });
} }
/** Creates a void type */ /** Creates a void type */
Void(options = {}) { Void(options = {}) {
return this.Create({ ...options, [exports.Kind]: 'Void', type: 'null' }); return this.Create({ ...options, [exports.Kind]: 'Void', type: 'null' });
} }
/** Use this function to return TSchema with static and params omitted */ /** Use this function to return TSchema with static and params omitted */
Create(schema) { Create(schema) {
return schema; return schema;
} }
/** Clones the given value */ /** Clones the given value */
Clone(value) { Clone(value) {
const isObject = (object) => typeof object === 'object' && object !== null && !Array.isArray(object); const isObject = (object) => typeof object === 'object' && object !== null && !Array.isArray(object);
const isArray = (object) => typeof object === 'object' && object !== null && Array.isArray(object); const isArray = (object) => typeof object === 'object' && object !== null && Array.isArray(object);
if (isObject(value)) { if (isObject(value)) {
return Object.keys(value).reduce((acc, key) => ({ return Object.keys(value).reduce((acc, key) => ({
...acc, ...acc,
[key]: this.Clone(value[key]), [key]: this.Clone(value[key]),
}), Object.getOwnPropertySymbols(value).reduce((acc, key) => ({ }), Object.getOwnPropertySymbols(value).reduce((acc, key) => ({
...acc, ...acc,
[key]: this.Clone(value[key]), [key]: this.Clone(value[key]),
}), {})); }), {}));
} }
else if (isArray(value)) { else if (isArray(value)) {
return value.map((item) => this.Clone(item)); return value.map((item) => this.Clone(item));
} }
else { else {
return value; return value;
} }
} }
} }
exports.TypeBuilder = TypeBuilder; exports.TypeBuilder = TypeBuilder;
/** JSON Schema Type Builder with Static Type Resolution for TypeScript */ /** JSON Schema Type Builder with Static Type Resolution for TypeScript */
exports.Type = new TypeBuilder(); exports.Type = new TypeBuilder();

View File

@@ -1,26 +1,26 @@
import * as Types from '../typebox'; import * as Types from '../typebox';
export declare class ValueCastReferenceTypeError extends Error { export declare class ValueCastReferenceTypeError extends Error {
readonly schema: Types.TRef | Types.TSelf; readonly schema: Types.TRef | Types.TSelf;
constructor(schema: Types.TRef | Types.TSelf); constructor(schema: Types.TRef | Types.TSelf);
} }
export declare class ValueCastArrayUniqueItemsTypeError extends Error { export declare class ValueCastArrayUniqueItemsTypeError extends Error {
readonly schema: Types.TSchema; readonly schema: Types.TSchema;
readonly value: unknown; readonly value: unknown;
constructor(schema: Types.TSchema, value: unknown); constructor(schema: Types.TSchema, value: unknown);
} }
export declare class ValueCastNeverTypeError extends Error { export declare class ValueCastNeverTypeError extends Error {
readonly schema: Types.TSchema; readonly schema: Types.TSchema;
constructor(schema: Types.TSchema); constructor(schema: Types.TSchema);
} }
export declare class ValueCastRecursiveTypeError extends Error { export declare class ValueCastRecursiveTypeError extends Error {
readonly schema: Types.TSchema; readonly schema: Types.TSchema;
constructor(schema: Types.TSchema); constructor(schema: Types.TSchema);
} }
export declare class ValueCastUnknownTypeError extends Error { export declare class ValueCastUnknownTypeError extends Error {
readonly schema: Types.TSchema; readonly schema: Types.TSchema;
constructor(schema: Types.TSchema); constructor(schema: Types.TSchema);
} }
export declare namespace ValueCast { export declare namespace ValueCast {
function Visit(schema: Types.TSchema, references: Types.TSchema[], value: any): any; 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>; 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"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/value @sinclair/typebox/value
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueCast = exports.ValueCastUnknownTypeError = exports.ValueCastRecursiveTypeError = exports.ValueCastNeverTypeError = exports.ValueCastArrayUniqueItemsTypeError = exports.ValueCastReferenceTypeError = void 0; exports.ValueCast = exports.ValueCastUnknownTypeError = exports.ValueCastRecursiveTypeError = exports.ValueCastNeverTypeError = exports.ValueCastArrayUniqueItemsTypeError = exports.ValueCastReferenceTypeError = void 0;
const Types = require("../typebox"); const Types = require("../typebox");
const create_1 = require("./create"); const create_1 = require("./create");
const check_1 = require("./check"); const check_1 = require("./check");
const clone_1 = require("./clone"); const clone_1 = require("./clone");
var UnionValueCast; var UnionValueCast;
(function (UnionValueCast) { (function (UnionValueCast) {
// ---------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------
// The following will score a schema against a value. For objects, the score is the tally of // 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) // 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 // to prevent large property counts biasing results. Properties that match literal values are
// maximally awarded as literals are typically used as union discriminator fields. // maximally awarded as literals are typically used as union discriminator fields.
// ---------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------
function Score(schema, references, value) { function Score(schema, references, value) {
if (schema[Types.Kind] === 'Object' && typeof value === 'object' && value !== null) { if (schema[Types.Kind] === 'Object' && typeof value === 'object' && value !== null) {
const object = schema; const object = schema;
const keys = Object.keys(value); const keys = Object.keys(value);
const entries = globalThis.Object.entries(object.properties); const entries = globalThis.Object.entries(object.properties);
const [point, max] = [1 / entries.length, entries.length]; const [point, max] = [1 / entries.length, entries.length];
return entries.reduce((acc, [key, schema]) => { return entries.reduce((acc, [key, schema]) => {
const literal = schema[Types.Kind] === 'Literal' && schema.const === value[key] ? max : 0; 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 checks = check_1.ValueCheck.Check(schema, references, value[key]) ? point : 0;
const exists = keys.includes(key) ? point : 0; const exists = keys.includes(key) ? point : 0;
return acc + (literal + checks + exists); return acc + (literal + checks + exists);
}, 0); }, 0);
} }
else { else {
return check_1.ValueCheck.Check(schema, references, value) ? 1 : 0; return check_1.ValueCheck.Check(schema, references, value) ? 1 : 0;
} }
} }
function Select(union, references, value) { function Select(union, references, value) {
let [select, best] = [union.anyOf[0], 0]; let [select, best] = [union.anyOf[0], 0];
for (const schema of union.anyOf) { for (const schema of union.anyOf) {
const score = Score(schema, references, value); const score = Score(schema, references, value);
if (score > best) { if (score > best) {
select = schema; select = schema;
best = score; best = score;
} }
} }
return select; return select;
} }
function Create(union, references, value) { 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); 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.Create = Create;
})(UnionValueCast || (UnionValueCast = {})); })(UnionValueCast || (UnionValueCast = {}));
// ----------------------------------------------------------- // -----------------------------------------------------------
// Errors // Errors
// ----------------------------------------------------------- // -----------------------------------------------------------
class ValueCastReferenceTypeError extends Error { class ValueCastReferenceTypeError extends Error {
constructor(schema) { constructor(schema) {
super(`ValueCast: Cannot locate referenced schema with $id '${schema.$ref}'`); super(`ValueCast: Cannot locate referenced schema with $id '${schema.$ref}'`);
this.schema = schema; this.schema = schema;
} }
} }
exports.ValueCastReferenceTypeError = ValueCastReferenceTypeError; exports.ValueCastReferenceTypeError = ValueCastReferenceTypeError;
class ValueCastArrayUniqueItemsTypeError extends Error { class ValueCastArrayUniqueItemsTypeError extends Error {
constructor(schema, value) { constructor(schema, value) {
super('ValueCast: Array cast produced invalid data due to uniqueItems constraint'); super('ValueCast: Array cast produced invalid data due to uniqueItems constraint');
this.schema = schema; this.schema = schema;
this.value = value; this.value = value;
} }
} }
exports.ValueCastArrayUniqueItemsTypeError = ValueCastArrayUniqueItemsTypeError; exports.ValueCastArrayUniqueItemsTypeError = ValueCastArrayUniqueItemsTypeError;
class ValueCastNeverTypeError extends Error { class ValueCastNeverTypeError extends Error {
constructor(schema) { constructor(schema) {
super('ValueCast: Never types cannot be cast'); super('ValueCast: Never types cannot be cast');
this.schema = schema; this.schema = schema;
} }
} }
exports.ValueCastNeverTypeError = ValueCastNeverTypeError; exports.ValueCastNeverTypeError = ValueCastNeverTypeError;
class ValueCastRecursiveTypeError extends Error { class ValueCastRecursiveTypeError extends Error {
constructor(schema) { constructor(schema) {
super('ValueCast.Recursive: Cannot cast recursive schemas'); super('ValueCast.Recursive: Cannot cast recursive schemas');
this.schema = schema; this.schema = schema;
} }
} }
exports.ValueCastRecursiveTypeError = ValueCastRecursiveTypeError; exports.ValueCastRecursiveTypeError = ValueCastRecursiveTypeError;
class ValueCastUnknownTypeError extends Error { class ValueCastUnknownTypeError extends Error {
constructor(schema) { constructor(schema) {
super('ValueCast: Unknown type'); super('ValueCast: Unknown type');
this.schema = schema; this.schema = schema;
} }
} }
exports.ValueCastUnknownTypeError = ValueCastUnknownTypeError; exports.ValueCastUnknownTypeError = ValueCastUnknownTypeError;
var ValueCast; var ValueCast;
(function (ValueCast) { (function (ValueCast) {
// ----------------------------------------------------------- // -----------------------------------------------------------
// Guards // Guards
// ----------------------------------------------------------- // -----------------------------------------------------------
function IsArray(value) { function IsArray(value) {
return typeof value === 'object' && globalThis.Array.isArray(value); return typeof value === 'object' && globalThis.Array.isArray(value);
} }
function IsString(value) { function IsString(value) {
return typeof value === 'string'; return typeof value === 'string';
} }
function IsBoolean(value) { function IsBoolean(value) {
return typeof value === 'boolean'; return typeof value === 'boolean';
} }
function IsBigInt(value) { function IsBigInt(value) {
return typeof value === 'bigint'; return typeof value === 'bigint';
} }
function IsNumber(value) { function IsNumber(value) {
return typeof value === 'number'; return typeof value === 'number';
} }
function IsStringNumeric(value) { function IsStringNumeric(value) {
return IsString(value) && !isNaN(value) && !isNaN(parseFloat(value)); return IsString(value) && !isNaN(value) && !isNaN(parseFloat(value));
} }
function IsValueToString(value) { function IsValueToString(value) {
return IsBigInt(value) || IsBoolean(value) || IsNumber(value); return IsBigInt(value) || IsBoolean(value) || IsNumber(value);
} }
function IsValueTrue(value) { function IsValueTrue(value) {
return value === true || (IsNumber(value) && value === 1) || (IsBigInt(value) && value === 1n) || (IsString(value) && (value.toLowerCase() === 'true' || value === '1')); return value === true || (IsNumber(value) && value === 1) || (IsBigInt(value) && value === 1n) || (IsString(value) && (value.toLowerCase() === 'true' || value === '1'));
} }
function IsValueFalse(value) { function IsValueFalse(value) {
return value === false || (IsNumber(value) && value === 0) || (IsBigInt(value) && value === 0n) || (IsString(value) && (value.toLowerCase() === 'false' || value === '0')); return value === false || (IsNumber(value) && value === 0) || (IsBigInt(value) && value === 0n) || (IsString(value) && (value.toLowerCase() === 'false' || value === '0'));
} }
// ----------------------------------------------------------- // -----------------------------------------------------------
// Convert // Convert
// ----------------------------------------------------------- // -----------------------------------------------------------
function TryConvertString(value) { function TryConvertString(value) {
return IsValueToString(value) ? value.toString() : value; return IsValueToString(value) ? value.toString() : value;
} }
function TryConvertNumber(value) { function TryConvertNumber(value) {
return IsStringNumeric(value) ? parseFloat(value) : IsValueTrue(value) ? 1 : value; return IsStringNumeric(value) ? parseFloat(value) : IsValueTrue(value) ? 1 : value;
} }
function TryConvertInteger(value) { function TryConvertInteger(value) {
return IsStringNumeric(value) ? parseInt(value) : IsValueTrue(value) ? 1 : value; return IsStringNumeric(value) ? parseInt(value) : IsValueTrue(value) ? 1 : value;
} }
function TryConvertBoolean(value) { function TryConvertBoolean(value) {
return IsValueTrue(value) ? true : IsValueFalse(value) ? false : value; return IsValueTrue(value) ? true : IsValueFalse(value) ? false : value;
} }
// ----------------------------------------------------------- // -----------------------------------------------------------
// Cast // Cast
// ----------------------------------------------------------- // -----------------------------------------------------------
function Any(schema, references, value) { function Any(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
} }
function Array(schema, references, value) { function Array(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value)) if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(value); return clone_1.ValueClone.Clone(value);
const created = IsArray(value) ? clone_1.ValueClone.Clone(value) : create_1.ValueCreate.Create(schema, references); 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 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 maximum = IsNumber(schema.maxItems) && minimum.length > schema.maxItems ? minimum.slice(0, schema.maxItems) : minimum;
const casted = maximum.map((value) => Visit(schema.items, references, value)); const casted = maximum.map((value) => Visit(schema.items, references, value));
if (schema.uniqueItems !== true) if (schema.uniqueItems !== true)
return casted; return casted;
const unique = [...new Set(casted)]; const unique = [...new Set(casted)];
if (!check_1.ValueCheck.Check(schema, references, unique)) if (!check_1.ValueCheck.Check(schema, references, unique))
throw new ValueCastArrayUniqueItemsTypeError(schema, unique); throw new ValueCastArrayUniqueItemsTypeError(schema, unique);
return unique; return unique;
} }
function Boolean(schema, references, value) { function Boolean(schema, references, value) {
const conversion = TryConvertBoolean(value); const conversion = TryConvertBoolean(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references);
} }
function Constructor(schema, references, value) { function Constructor(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value)) if (check_1.ValueCheck.Check(schema, references, value))
return create_1.ValueCreate.Create(schema, references); return create_1.ValueCreate.Create(schema, references);
const required = new Set(schema.returns.required || []); const required = new Set(schema.returns.required || []);
const result = function () { }; const result = function () { };
for (const [key, property] of globalThis.Object.entries(schema.returns.properties)) { for (const [key, property] of globalThis.Object.entries(schema.returns.properties)) {
if (!required.has(key) && value.prototype[key] === undefined) if (!required.has(key) && value.prototype[key] === undefined)
continue; continue;
result.prototype[key] = Visit(property, references, value.prototype[key]); result.prototype[key] = Visit(property, references, value.prototype[key]);
} }
return result; return result;
} }
function Enum(schema, references, value) { function Enum(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
} }
function Function(schema, references, value) { function Function(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
} }
function Integer(schema, references, value) { function Integer(schema, references, value) {
const conversion = TryConvertInteger(value); const conversion = TryConvertInteger(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references);
} }
function Literal(schema, references, value) { function Literal(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
} }
function Never(schema, references, value) { function Never(schema, references, value) {
throw new ValueCastNeverTypeError(schema); throw new ValueCastNeverTypeError(schema);
} }
function Null(schema, references, value) { function Null(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
} }
function Number(schema, references, value) { function Number(schema, references, value) {
const conversion = TryConvertNumber(value); const conversion = TryConvertNumber(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references);
} }
function Object(schema, references, value) { function Object(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value)) if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(value); return clone_1.ValueClone.Clone(value);
if (value === null || typeof value !== 'object') if (value === null || typeof value !== 'object')
return create_1.ValueCreate.Create(schema, references); return create_1.ValueCreate.Create(schema, references);
const required = new Set(schema.required || []); const required = new Set(schema.required || []);
const result = {}; const result = {};
for (const [key, property] of globalThis.Object.entries(schema.properties)) { for (const [key, property] of globalThis.Object.entries(schema.properties)) {
if (!required.has(key) && value[key] === undefined) if (!required.has(key) && value[key] === undefined)
continue; continue;
result[key] = Visit(property, references, value[key]); result[key] = Visit(property, references, value[key]);
} }
// additional schema properties // additional schema properties
if (typeof schema.additionalProperties === 'object') { if (typeof schema.additionalProperties === 'object') {
const propertyKeys = globalThis.Object.keys(schema.properties); const propertyKeys = globalThis.Object.keys(schema.properties);
for (const objectKey of globalThis.Object.keys(value)) { for (const objectKey of globalThis.Object.keys(value)) {
if (propertyKeys.includes(objectKey)) if (propertyKeys.includes(objectKey))
continue; continue;
result[objectKey] = Visit(schema.additionalProperties, references, value[objectKey]); result[objectKey] = Visit(schema.additionalProperties, references, value[objectKey]);
} }
} }
return result; return result;
} }
function Promise(schema, references, value) { function Promise(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
} }
function Record(schema, references, value) { function Record(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value)) if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(value); return clone_1.ValueClone.Clone(value);
if (value === null || typeof value !== 'object' || globalThis.Array.isArray(value)) if (value === null || typeof value !== 'object' || globalThis.Array.isArray(value))
return create_1.ValueCreate.Create(schema, references); return create_1.ValueCreate.Create(schema, references);
const subschemaKey = globalThis.Object.keys(schema.patternProperties)[0]; const subschemaKey = globalThis.Object.keys(schema.patternProperties)[0];
const subschema = schema.patternProperties[subschemaKey]; const subschema = schema.patternProperties[subschemaKey];
const result = {}; const result = {};
for (const [propKey, propValue] of globalThis.Object.entries(value)) { for (const [propKey, propValue] of globalThis.Object.entries(value)) {
result[propKey] = Visit(subschema, references, propValue); result[propKey] = Visit(subschema, references, propValue);
} }
return result; return result;
} }
function Recursive(schema, references, value) { function Recursive(schema, references, value) {
throw new ValueCastRecursiveTypeError(schema); throw new ValueCastRecursiveTypeError(schema);
} }
function Ref(schema, references, value) { function Ref(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref); const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined) if (reference === undefined)
throw new ValueCastReferenceTypeError(schema); throw new ValueCastReferenceTypeError(schema);
return Visit(reference, references, value); return Visit(reference, references, value);
} }
function Self(schema, references, value) { function Self(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref); const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined) if (reference === undefined)
throw new ValueCastReferenceTypeError(schema); throw new ValueCastReferenceTypeError(schema);
return Visit(reference, references, value); return Visit(reference, references, value);
} }
function String(schema, references, value) { function String(schema, references, value) {
const conversion = TryConvertString(value); const conversion = TryConvertString(value);
return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, conversion) ? conversion : create_1.ValueCreate.Create(schema, references);
} }
function Tuple(schema, references, value) { function Tuple(schema, references, value) {
if (check_1.ValueCheck.Check(schema, references, value)) if (check_1.ValueCheck.Check(schema, references, value))
return clone_1.ValueClone.Clone(value); return clone_1.ValueClone.Clone(value);
if (!globalThis.Array.isArray(value)) if (!globalThis.Array.isArray(value))
return create_1.ValueCreate.Create(schema, references); return create_1.ValueCreate.Create(schema, references);
if (schema.items === undefined) if (schema.items === undefined)
return []; return [];
return schema.items.map((schema, index) => Visit(schema, references, value[index])); return schema.items.map((schema, index) => Visit(schema, references, value[index]));
} }
function Undefined(schema, references, value) { function Undefined(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
} }
function Union(schema, references, value) { function Union(schema, references, value) {
return UnionValueCast.Create(schema, references, value); return UnionValueCast.Create(schema, references, value);
} }
function Uint8Array(schema, references, value) { function Uint8Array(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
} }
function Unknown(schema, references, value) { function Unknown(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
} }
function Void(schema, references, value) { function Void(schema, references, value) {
return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references); return check_1.ValueCheck.Check(schema, references, value) ? value : create_1.ValueCreate.Create(schema, references);
} }
function Visit(schema, references, value) { function Visit(schema, references, value) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references]; const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema; const anySchema = schema;
switch (schema[Types.Kind]) { switch (schema[Types.Kind]) {
case 'Any': case 'Any':
return Any(anySchema, anyReferences, value); return Any(anySchema, anyReferences, value);
case 'Array': case 'Array':
return Array(anySchema, anyReferences, value); return Array(anySchema, anyReferences, value);
case 'Boolean': case 'Boolean':
return Boolean(anySchema, anyReferences, value); return Boolean(anySchema, anyReferences, value);
case 'Constructor': case 'Constructor':
return Constructor(anySchema, anyReferences, value); return Constructor(anySchema, anyReferences, value);
case 'Enum': case 'Enum':
return Enum(anySchema, anyReferences, value); return Enum(anySchema, anyReferences, value);
case 'Function': case 'Function':
return Function(anySchema, anyReferences, value); return Function(anySchema, anyReferences, value);
case 'Integer': case 'Integer':
return Integer(anySchema, anyReferences, value); return Integer(anySchema, anyReferences, value);
case 'Literal': case 'Literal':
return Literal(anySchema, anyReferences, value); return Literal(anySchema, anyReferences, value);
case 'Never': case 'Never':
return Never(anySchema, anyReferences, value); return Never(anySchema, anyReferences, value);
case 'Null': case 'Null':
return Null(anySchema, anyReferences, value); return Null(anySchema, anyReferences, value);
case 'Number': case 'Number':
return Number(anySchema, anyReferences, value); return Number(anySchema, anyReferences, value);
case 'Object': case 'Object':
return Object(anySchema, anyReferences, value); return Object(anySchema, anyReferences, value);
case 'Promise': case 'Promise':
return Promise(anySchema, anyReferences, value); return Promise(anySchema, anyReferences, value);
case 'Record': case 'Record':
return Record(anySchema, anyReferences, value); return Record(anySchema, anyReferences, value);
case 'Rec': case 'Rec':
return Recursive(anySchema, anyReferences, value); return Recursive(anySchema, anyReferences, value);
case 'Ref': case 'Ref':
return Ref(anySchema, anyReferences, value); return Ref(anySchema, anyReferences, value);
case 'Self': case 'Self':
return Self(anySchema, anyReferences, value); return Self(anySchema, anyReferences, value);
case 'String': case 'String':
return String(anySchema, anyReferences, value); return String(anySchema, anyReferences, value);
case 'Tuple': case 'Tuple':
return Tuple(anySchema, anyReferences, value); return Tuple(anySchema, anyReferences, value);
case 'Undefined': case 'Undefined':
return Undefined(anySchema, anyReferences, value); return Undefined(anySchema, anyReferences, value);
case 'Union': case 'Union':
return Union(anySchema, anyReferences, value); return Union(anySchema, anyReferences, value);
case 'Uint8Array': case 'Uint8Array':
return Uint8Array(anySchema, anyReferences, value); return Uint8Array(anySchema, anyReferences, value);
case 'Unknown': case 'Unknown':
return Unknown(anySchema, anyReferences, value); return Unknown(anySchema, anyReferences, value);
case 'Void': case 'Void':
return Void(anySchema, anyReferences, value); return Void(anySchema, anyReferences, value);
default: default:
throw new ValueCastUnknownTypeError(anySchema); throw new ValueCastUnknownTypeError(anySchema);
} }
} }
ValueCast.Visit = Visit; ValueCast.Visit = Visit;
function Cast(schema, references, value) { function Cast(schema, references, value) {
return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value); return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value);
} }
ValueCast.Cast = Cast; ValueCast.Cast = Cast;
})(ValueCast = exports.ValueCast || (exports.ValueCast = {})); })(ValueCast = exports.ValueCast || (exports.ValueCast = {}));

View File

@@ -1,8 +1,8 @@
import * as Types from '../typebox'; import * as Types from '../typebox';
export declare class ValueCheckUnknownTypeError extends Error { export declare class ValueCheckUnknownTypeError extends Error {
readonly schema: Types.TSchema; readonly schema: Types.TSchema;
constructor(schema: Types.TSchema); constructor(schema: Types.TSchema);
} }
export declare namespace ValueCheck { export declare namespace ValueCheck {
function Check<T extends Types.TSchema, R extends Types.TSchema[]>(schema: T, references: [...R], value: any): boolean; 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"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/value @sinclair/typebox/value
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueCheck = exports.ValueCheckUnknownTypeError = void 0; exports.ValueCheck = exports.ValueCheckUnknownTypeError = void 0;
const Types = require("../typebox"); const Types = require("../typebox");
const format_1 = require("../format"); const format_1 = require("../format");
class ValueCheckUnknownTypeError extends Error { class ValueCheckUnknownTypeError extends Error {
constructor(schema) { constructor(schema) {
super('ValueCheck: Unknown type'); super('ValueCheck: Unknown type');
this.schema = schema; this.schema = schema;
} }
} }
exports.ValueCheckUnknownTypeError = ValueCheckUnknownTypeError; exports.ValueCheckUnknownTypeError = ValueCheckUnknownTypeError;
var ValueCheck; var ValueCheck;
(function (ValueCheck) { (function (ValueCheck) {
function Any(schema, references, value) { function Any(schema, references, value) {
return true; return true;
} }
function Array(schema, references, value) { function Array(schema, references, value) {
if (!globalThis.Array.isArray(value)) { if (!globalThis.Array.isArray(value)) {
return false; return false;
} }
if (schema.minItems !== undefined && !(value.length >= schema.minItems)) { if (schema.minItems !== undefined && !(value.length >= schema.minItems)) {
return false; return false;
} }
if (schema.maxItems !== undefined && !(value.length <= schema.maxItems)) { if (schema.maxItems !== undefined && !(value.length <= schema.maxItems)) {
return false; return false;
} }
if (schema.uniqueItems === true && !(new Set(value).size === value.length)) { if (schema.uniqueItems === true && !(new Set(value).size === value.length)) {
return false; return false;
} }
return value.every((val) => Visit(schema.items, references, val)); return value.every((val) => Visit(schema.items, references, val));
} }
function Boolean(schema, references, value) { function Boolean(schema, references, value) {
return typeof value === 'boolean'; return typeof value === 'boolean';
} }
function Constructor(schema, references, value) { function Constructor(schema, references, value) {
return Visit(schema.returns, references, value.prototype); return Visit(schema.returns, references, value.prototype);
} }
function Function(schema, references, value) { function Function(schema, references, value) {
return typeof value === 'function'; return typeof value === 'function';
} }
function Integer(schema, references, value) { function Integer(schema, references, value) {
if (!(typeof value === 'number')) { if (!(typeof value === 'number')) {
return false; return false;
} }
if (!globalThis.Number.isInteger(value)) { if (!globalThis.Number.isInteger(value)) {
return false; return false;
} }
if (schema.multipleOf !== undefined && !(value % schema.multipleOf === 0)) { if (schema.multipleOf !== undefined && !(value % schema.multipleOf === 0)) {
return false; return false;
} }
if (schema.exclusiveMinimum !== undefined && !(value > schema.exclusiveMinimum)) { if (schema.exclusiveMinimum !== undefined && !(value > schema.exclusiveMinimum)) {
return false; return false;
} }
if (schema.exclusiveMaximum !== undefined && !(value < schema.exclusiveMaximum)) { if (schema.exclusiveMaximum !== undefined && !(value < schema.exclusiveMaximum)) {
return false; return false;
} }
if (schema.minimum !== undefined && !(value >= schema.minimum)) { if (schema.minimum !== undefined && !(value >= schema.minimum)) {
return false; return false;
} }
if (schema.maximum !== undefined && !(value <= schema.maximum)) { if (schema.maximum !== undefined && !(value <= schema.maximum)) {
return false; return false;
} }
return true; return true;
} }
function Literal(schema, references, value) { function Literal(schema, references, value) {
return value === schema.const; return value === schema.const;
} }
function Never(schema, references, value) { function Never(schema, references, value) {
return false; return false;
} }
function Null(schema, references, value) { function Null(schema, references, value) {
return value === null; return value === null;
} }
function Number(schema, references, value) { function Number(schema, references, value) {
if (!(typeof value === 'number')) { if (!(typeof value === 'number')) {
return false; return false;
} }
if (schema.multipleOf && !(value % schema.multipleOf === 0)) { if (schema.multipleOf && !(value % schema.multipleOf === 0)) {
return false; return false;
} }
if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) { if (schema.exclusiveMinimum && !(value > schema.exclusiveMinimum)) {
return false; return false;
} }
if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) { if (schema.exclusiveMaximum && !(value < schema.exclusiveMaximum)) {
return false; return false;
} }
if (schema.minimum && !(value >= schema.minimum)) { if (schema.minimum && !(value >= schema.minimum)) {
return false; return false;
} }
if (schema.maximum && !(value <= schema.maximum)) { if (schema.maximum && !(value <= schema.maximum)) {
return false; return false;
} }
return true; return true;
} }
function Object(schema, references, value) { function Object(schema, references, value) {
if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) { if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return false; return false;
} }
if (schema.minProperties !== undefined && !(globalThis.Object.keys(value).length >= schema.minProperties)) { if (schema.minProperties !== undefined && !(globalThis.Object.keys(value).length >= schema.minProperties)) {
return false; return false;
} }
if (schema.maxProperties !== undefined && !(globalThis.Object.keys(value).length <= schema.maxProperties)) { if (schema.maxProperties !== undefined && !(globalThis.Object.keys(value).length <= schema.maxProperties)) {
return false; return false;
} }
const propertyKeys = globalThis.Object.keys(schema.properties); const propertyKeys = globalThis.Object.keys(schema.properties);
if (schema.additionalProperties === false) { if (schema.additionalProperties === false) {
// optimization: If the property key length matches the required keys length // optimization: If the property key length matches the required keys length
// then we only need check that the values property key length matches that // 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 // of the property key length. This is because exhaustive testing for values
// will occur in subsequent property tests. // will occur in subsequent property tests.
if (schema.required && schema.required.length === propertyKeys.length && !(globalThis.Object.keys(value).length === propertyKeys.length)) { if (schema.required && schema.required.length === propertyKeys.length && !(globalThis.Object.keys(value).length === propertyKeys.length)) {
return false; return false;
} }
else { else {
if (!globalThis.Object.keys(value).every((key) => propertyKeys.includes(key))) { if (!globalThis.Object.keys(value).every((key) => propertyKeys.includes(key))) {
return false; return false;
} }
} }
} }
if (typeof schema.additionalProperties === 'object') { if (typeof schema.additionalProperties === 'object') {
for (const objectKey of globalThis.Object.keys(value)) { for (const objectKey of globalThis.Object.keys(value)) {
if (propertyKeys.includes(objectKey)) if (propertyKeys.includes(objectKey))
continue; continue;
if (!Visit(schema.additionalProperties, references, value[objectKey])) { if (!Visit(schema.additionalProperties, references, value[objectKey])) {
return false; return false;
} }
} }
} }
for (const propertyKey of propertyKeys) { for (const propertyKey of propertyKeys) {
const propertySchema = schema.properties[propertyKey]; const propertySchema = schema.properties[propertyKey];
if (schema.required && schema.required.includes(propertyKey)) { if (schema.required && schema.required.includes(propertyKey)) {
if (!Visit(propertySchema, references, value[propertyKey])) { if (!Visit(propertySchema, references, value[propertyKey])) {
return false; return false;
} }
} }
else { else {
if (value[propertyKey] !== undefined) { if (value[propertyKey] !== undefined) {
if (!Visit(propertySchema, references, value[propertyKey])) { if (!Visit(propertySchema, references, value[propertyKey])) {
return false; return false;
} }
} }
} }
} }
return true; return true;
} }
function Promise(schema, references, value) { function Promise(schema, references, value) {
return typeof value === 'object' && typeof value.then === 'function'; return typeof value === 'object' && typeof value.then === 'function';
} }
function Record(schema, references, value) { function Record(schema, references, value) {
if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) { if (!(typeof value === 'object' && value !== null && !globalThis.Array.isArray(value))) {
return false; return false;
} }
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
const regex = new RegExp(keyPattern); const regex = new RegExp(keyPattern);
if (!globalThis.Object.keys(value).every((key) => regex.test(key))) { if (!globalThis.Object.keys(value).every((key) => regex.test(key))) {
return false; return false;
} }
for (const propValue of globalThis.Object.values(value)) { for (const propValue of globalThis.Object.values(value)) {
if (!Visit(valueSchema, references, propValue)) if (!Visit(valueSchema, references, propValue))
return false; return false;
} }
return true; return true;
} }
function Ref(schema, references, value) { function Ref(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref); const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined) if (reference === undefined)
throw new Error(`ValueCheck.Ref: Cannot find schema with $id '${schema.$ref}'.`); throw new Error(`ValueCheck.Ref: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references, value); return Visit(reference, references, value);
} }
function Self(schema, references, value) { function Self(schema, references, value) {
const reference = references.find((reference) => reference.$id === schema.$ref); const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined) if (reference === undefined)
throw new Error(`ValueCheck.Self: Cannot find schema with $id '${schema.$ref}'.`); throw new Error(`ValueCheck.Self: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references, value); return Visit(reference, references, value);
} }
function String(schema, references, value) { function String(schema, references, value) {
if (!(typeof value === 'string')) { if (!(typeof value === 'string')) {
return false; return false;
} }
if (schema.minLength !== undefined) { if (schema.minLength !== undefined) {
if (!(value.length >= schema.minLength)) if (!(value.length >= schema.minLength))
return false; return false;
} }
if (schema.maxLength !== undefined) { if (schema.maxLength !== undefined) {
if (!(value.length <= schema.maxLength)) if (!(value.length <= schema.maxLength))
return false; return false;
} }
if (schema.pattern !== undefined) { if (schema.pattern !== undefined) {
const regex = new RegExp(schema.pattern); const regex = new RegExp(schema.pattern);
if (!regex.test(value)) if (!regex.test(value))
return false; return false;
} }
if (schema.format !== undefined) { if (schema.format !== undefined) {
if (!format_1.Format.Has(schema.format)) if (!format_1.Format.Has(schema.format))
return false; return false;
const func = format_1.Format.Get(schema.format); const func = format_1.Format.Get(schema.format);
return func(value); return func(value);
} }
return true; return true;
} }
function Tuple(schema, references, value) { function Tuple(schema, references, value) {
if (!globalThis.Array.isArray(value)) { if (!globalThis.Array.isArray(value)) {
return false; return false;
} }
if (schema.items === undefined && !(value.length === 0)) { if (schema.items === undefined && !(value.length === 0)) {
return false; return false;
} }
if (!(value.length === schema.maxItems)) { if (!(value.length === schema.maxItems)) {
return false; return false;
} }
if (!schema.items) { if (!schema.items) {
return true; return true;
} }
for (let i = 0; i < schema.items.length; i++) { for (let i = 0; i < schema.items.length; i++) {
if (!Visit(schema.items[i], references, value[i])) if (!Visit(schema.items[i], references, value[i]))
return false; return false;
} }
return true; return true;
} }
function Undefined(schema, references, value) { function Undefined(schema, references, value) {
return value === undefined; return value === undefined;
} }
function Union(schema, references, value) { function Union(schema, references, value) {
return schema.anyOf.some((inner) => Visit(inner, references, value)); return schema.anyOf.some((inner) => Visit(inner, references, value));
} }
function Uint8Array(schema, references, value) { function Uint8Array(schema, references, value) {
if (!(value instanceof globalThis.Uint8Array)) { if (!(value instanceof globalThis.Uint8Array)) {
return false; return false;
} }
if (schema.maxByteLength && !(value.length <= schema.maxByteLength)) { if (schema.maxByteLength && !(value.length <= schema.maxByteLength)) {
return false; return false;
} }
if (schema.minByteLength && !(value.length >= schema.minByteLength)) { if (schema.minByteLength && !(value.length >= schema.minByteLength)) {
return false; return false;
} }
return true; return true;
} }
function Unknown(schema, references, value) { function Unknown(schema, references, value) {
return true; return true;
} }
function Void(schema, references, value) { function Void(schema, references, value) {
return value === null; return value === null;
} }
function Visit(schema, references, value) { function Visit(schema, references, value) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references]; const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema; const anySchema = schema;
switch (anySchema[Types.Kind]) { switch (anySchema[Types.Kind]) {
case 'Any': case 'Any':
return Any(anySchema, anyReferences, value); return Any(anySchema, anyReferences, value);
case 'Array': case 'Array':
return Array(anySchema, anyReferences, value); return Array(anySchema, anyReferences, value);
case 'Boolean': case 'Boolean':
return Boolean(anySchema, anyReferences, value); return Boolean(anySchema, anyReferences, value);
case 'Constructor': case 'Constructor':
return Constructor(anySchema, anyReferences, value); return Constructor(anySchema, anyReferences, value);
case 'Function': case 'Function':
return Function(anySchema, anyReferences, value); return Function(anySchema, anyReferences, value);
case 'Integer': case 'Integer':
return Integer(anySchema, anyReferences, value); return Integer(anySchema, anyReferences, value);
case 'Literal': case 'Literal':
return Literal(anySchema, anyReferences, value); return Literal(anySchema, anyReferences, value);
case 'Never': case 'Never':
return Never(anySchema, anyReferences, value); return Never(anySchema, anyReferences, value);
case 'Null': case 'Null':
return Null(anySchema, anyReferences, value); return Null(anySchema, anyReferences, value);
case 'Number': case 'Number':
return Number(anySchema, anyReferences, value); return Number(anySchema, anyReferences, value);
case 'Object': case 'Object':
return Object(anySchema, anyReferences, value); return Object(anySchema, anyReferences, value);
case 'Promise': case 'Promise':
return Promise(anySchema, anyReferences, value); return Promise(anySchema, anyReferences, value);
case 'Record': case 'Record':
return Record(anySchema, anyReferences, value); return Record(anySchema, anyReferences, value);
case 'Ref': case 'Ref':
return Ref(anySchema, anyReferences, value); return Ref(anySchema, anyReferences, value);
case 'Self': case 'Self':
return Self(anySchema, anyReferences, value); return Self(anySchema, anyReferences, value);
case 'String': case 'String':
return String(anySchema, anyReferences, value); return String(anySchema, anyReferences, value);
case 'Tuple': case 'Tuple':
return Tuple(anySchema, anyReferences, value); return Tuple(anySchema, anyReferences, value);
case 'Undefined': case 'Undefined':
return Undefined(anySchema, anyReferences, value); return Undefined(anySchema, anyReferences, value);
case 'Union': case 'Union':
return Union(anySchema, anyReferences, value); return Union(anySchema, anyReferences, value);
case 'Uint8Array': case 'Uint8Array':
return Uint8Array(anySchema, anyReferences, value); return Uint8Array(anySchema, anyReferences, value);
case 'Unknown': case 'Unknown':
return Unknown(anySchema, anyReferences, value); return Unknown(anySchema, anyReferences, value);
case 'Void': case 'Void':
return Void(anySchema, anyReferences, value); return Void(anySchema, anyReferences, value);
default: default:
throw new ValueCheckUnknownTypeError(anySchema); throw new ValueCheckUnknownTypeError(anySchema);
} }
} }
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
// Check // Check
// ------------------------------------------------------------------------- // -------------------------------------------------------------------------
function Check(schema, references, value) { function Check(schema, references, value) {
return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value); return schema.$id === undefined ? Visit(schema, references, value) : Visit(schema, [schema, ...references], value);
} }
ValueCheck.Check = Check; ValueCheck.Check = Check;
})(ValueCheck = exports.ValueCheck || (exports.ValueCheck = {})); })(ValueCheck = exports.ValueCheck || (exports.ValueCheck = {}));

View File

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

View File

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

View File

@@ -1,14 +1,14 @@
import * as Types from '../typebox'; import * as Types from '../typebox';
export declare class ValueCreateUnknownTypeError extends Error { export declare class ValueCreateUnknownTypeError extends Error {
readonly schema: Types.TSchema; readonly schema: Types.TSchema;
constructor(schema: Types.TSchema); constructor(schema: Types.TSchema);
} }
export declare class ValueCreateNeverTypeError extends Error { export declare class ValueCreateNeverTypeError extends Error {
readonly schema: Types.TSchema; readonly schema: Types.TSchema;
constructor(schema: Types.TSchema); constructor(schema: Types.TSchema);
} }
export declare namespace ValueCreate { export declare namespace ValueCreate {
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */ /** 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 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>; 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"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/value @sinclair/typebox/value
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueCreate = exports.ValueCreateNeverTypeError = exports.ValueCreateUnknownTypeError = void 0; exports.ValueCreate = exports.ValueCreateNeverTypeError = exports.ValueCreateUnknownTypeError = void 0;
const Types = require("../typebox"); const Types = require("../typebox");
class ValueCreateUnknownTypeError extends Error { class ValueCreateUnknownTypeError extends Error {
constructor(schema) { constructor(schema) {
super('ValueCreate: Unknown type'); super('ValueCreate: Unknown type');
this.schema = schema; this.schema = schema;
} }
} }
exports.ValueCreateUnknownTypeError = ValueCreateUnknownTypeError; exports.ValueCreateUnknownTypeError = ValueCreateUnknownTypeError;
class ValueCreateNeverTypeError extends Error { class ValueCreateNeverTypeError extends Error {
constructor(schema) { constructor(schema) {
super('ValueCreate: Never types cannot be created'); super('ValueCreate: Never types cannot be created');
this.schema = schema; this.schema = schema;
} }
} }
exports.ValueCreateNeverTypeError = ValueCreateNeverTypeError; exports.ValueCreateNeverTypeError = ValueCreateNeverTypeError;
var ValueCreate; var ValueCreate;
(function (ValueCreate) { (function (ValueCreate) {
function Any(schema, references) { function Any(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else { else {
return {}; return {};
} }
} }
function Array(schema, references) { function Array(schema, references) {
if (schema.uniqueItems === true && schema.default === undefined) { if (schema.uniqueItems === true && schema.default === undefined) {
throw new Error('ValueCreate.Array: Arrays with uniqueItems require a default value'); throw new Error('ValueCreate.Array: Arrays with uniqueItems require a default value');
} }
else if (schema.default !== undefined) { else if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else if (schema.minItems !== undefined) { else if (schema.minItems !== undefined) {
return globalThis.Array.from({ length: schema.minItems }).map((item) => { return globalThis.Array.from({ length: schema.minItems }).map((item) => {
return ValueCreate.Create(schema.items, references); return ValueCreate.Create(schema.items, references);
}); });
} }
else { else {
return []; return [];
} }
} }
function Boolean(schema, references) { function Boolean(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else { else {
return false; return false;
} }
} }
function Constructor(schema, references) { function Constructor(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else { else {
const value = ValueCreate.Create(schema.returns, references); const value = ValueCreate.Create(schema.returns, references);
if (typeof value === 'object' && !globalThis.Array.isArray(value)) { if (typeof value === 'object' && !globalThis.Array.isArray(value)) {
return class { return class {
constructor() { constructor() {
for (const [key, val] of globalThis.Object.entries(value)) { for (const [key, val] of globalThis.Object.entries(value)) {
const self = this; const self = this;
self[key] = val; self[key] = val;
} }
} }
}; };
} }
else { else {
return class { return class {
}; };
} }
} }
} }
function Enum(schema, references) { function Enum(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else if (schema.anyOf.length === 0) { else if (schema.anyOf.length === 0) {
throw new Error('ValueCreate.Enum: Cannot create default enum value as this enum has no items'); throw new Error('ValueCreate.Enum: Cannot create default enum value as this enum has no items');
} }
else { else {
return schema.anyOf[0].const; return schema.anyOf[0].const;
} }
} }
function Function(schema, references) { function Function(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else { else {
return () => ValueCreate.Create(schema.returns, references); return () => ValueCreate.Create(schema.returns, references);
} }
} }
function Integer(schema, references) { function Integer(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else if (schema.minimum !== undefined) { else if (schema.minimum !== undefined) {
return schema.minimum; return schema.minimum;
} }
else { else {
return 0; return 0;
} }
} }
function Literal(schema, references) { function Literal(schema, references) {
return schema.const; return schema.const;
} }
function Never(schema, references) { function Never(schema, references) {
throw new ValueCreateNeverTypeError(schema); throw new ValueCreateNeverTypeError(schema);
} }
function Null(schema, references) { function Null(schema, references) {
return null; return null;
} }
function Number(schema, references) { function Number(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else if (schema.minimum !== undefined) { else if (schema.minimum !== undefined) {
return schema.minimum; return schema.minimum;
} }
else { else {
return 0; return 0;
} }
} }
function Object(schema, references) { function Object(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else { else {
const required = new Set(schema.required); const required = new Set(schema.required);
return (schema.default || return (schema.default ||
globalThis.Object.entries(schema.properties).reduce((acc, [key, schema]) => { globalThis.Object.entries(schema.properties).reduce((acc, [key, schema]) => {
return required.has(key) ? { ...acc, [key]: ValueCreate.Create(schema, references) } : { ...acc }; return required.has(key) ? { ...acc, [key]: ValueCreate.Create(schema, references) } : { ...acc };
}, {})); }, {}));
} }
} }
function Promise(schema, references) { function Promise(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else { else {
return globalThis.Promise.resolve(ValueCreate.Create(schema.item, references)); return globalThis.Promise.resolve(ValueCreate.Create(schema.item, references));
} }
} }
function Record(schema, references) { function Record(schema, references) {
const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0]; const [keyPattern, valueSchema] = globalThis.Object.entries(schema.patternProperties)[0];
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else if (!(keyPattern === '^.*$' || keyPattern === '^(0|[1-9][0-9]*)$')) { else if (!(keyPattern === '^.*$' || keyPattern === '^(0|[1-9][0-9]*)$')) {
const propertyKeys = keyPattern.slice(1, keyPattern.length - 1).split('|'); const propertyKeys = keyPattern.slice(1, keyPattern.length - 1).split('|');
return propertyKeys.reduce((acc, key) => { return propertyKeys.reduce((acc, key) => {
return { ...acc, [key]: Create(valueSchema, references) }; return { ...acc, [key]: Create(valueSchema, references) };
}, {}); }, {});
} }
else { else {
return {}; return {};
} }
} }
function Recursive(schema, references) { function Recursive(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else { else {
throw new Error('ValueCreate.Recursive: Recursive types require a default value'); throw new Error('ValueCreate.Recursive: Recursive types require a default value');
} }
} }
function Ref(schema, references) { function Ref(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else { else {
const reference = references.find((reference) => reference.$id === schema.$ref); const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined) if (reference === undefined)
throw new Error(`ValueCreate.Ref: Cannot find schema with $id '${schema.$ref}'.`); throw new Error(`ValueCreate.Ref: Cannot find schema with $id '${schema.$ref}'.`);
return Visit(reference, references); return Visit(reference, references);
} }
} }
function Self(schema, references) { function Self(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else { else {
const reference = references.find((reference) => reference.$id === schema.$ref); const reference = references.find((reference) => reference.$id === schema.$ref);
if (reference === undefined) if (reference === undefined)
throw new Error(`ValueCreate.Self: Cannot locate schema with $id '${schema.$ref}'`); throw new Error(`ValueCreate.Self: Cannot locate schema with $id '${schema.$ref}'`);
return Visit(reference, references); return Visit(reference, references);
} }
} }
function String(schema, references) { function String(schema, references) {
if (schema.pattern !== undefined) { if (schema.pattern !== undefined) {
if (schema.default === undefined) { if (schema.default === undefined) {
throw new Error('ValueCreate.String: String types with patterns must specify a default value'); throw new Error('ValueCreate.String: String types with patterns must specify a default value');
} }
else { else {
return schema.default; return schema.default;
} }
} }
else if (schema.format !== undefined) { else if (schema.format !== undefined) {
if (schema.default === undefined) { if (schema.default === undefined) {
throw new Error('ValueCreate.String: String types with formats must specify a default value'); throw new Error('ValueCreate.String: String types with formats must specify a default value');
} }
else { else {
return schema.default; return schema.default;
} }
} }
else { else {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else if (schema.minLength !== undefined) { else if (schema.minLength !== undefined) {
return globalThis.Array.from({ length: schema.minLength }) return globalThis.Array.from({ length: schema.minLength })
.map(() => '.') .map(() => '.')
.join(''); .join('');
} }
else { else {
return ''; return '';
} }
} }
} }
function Tuple(schema, references) { function Tuple(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
if (schema.items === undefined) { if (schema.items === undefined) {
return []; return [];
} }
else { else {
return globalThis.Array.from({ length: schema.minItems }).map((_, index) => ValueCreate.Create(schema.items[index], references)); return globalThis.Array.from({ length: schema.minItems }).map((_, index) => ValueCreate.Create(schema.items[index], references));
} }
} }
function Undefined(schema, references) { function Undefined(schema, references) {
return undefined; return undefined;
} }
function Union(schema, references) { function Union(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else if (schema.anyOf.length === 0) { else if (schema.anyOf.length === 0) {
throw new Error('ValueCreate.Union: Cannot create Union with zero variants'); throw new Error('ValueCreate.Union: Cannot create Union with zero variants');
} }
else { else {
return ValueCreate.Create(schema.anyOf[0], references); return ValueCreate.Create(schema.anyOf[0], references);
} }
} }
function Uint8Array(schema, references) { function Uint8Array(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else if (schema.minByteLength !== undefined) { else if (schema.minByteLength !== undefined) {
return new globalThis.Uint8Array(schema.minByteLength); return new globalThis.Uint8Array(schema.minByteLength);
} }
else { else {
return new globalThis.Uint8Array(0); return new globalThis.Uint8Array(0);
} }
} }
function Unknown(schema, references) { function Unknown(schema, references) {
if (schema.default !== undefined) { if (schema.default !== undefined) {
return schema.default; return schema.default;
} }
else { else {
return {}; return {};
} }
} }
function Void(schema, references) { function Void(schema, references) {
return null; return null;
} }
/** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */ /** Creates a value from the given schema. If the schema specifies a default value, then that value is returned. */
function Visit(schema, references) { function Visit(schema, references) {
const anyReferences = schema.$id === undefined ? references : [schema, ...references]; const anyReferences = schema.$id === undefined ? references : [schema, ...references];
const anySchema = schema; const anySchema = schema;
switch (anySchema[Types.Kind]) { switch (anySchema[Types.Kind]) {
case 'Any': case 'Any':
return Any(anySchema, anyReferences); return Any(anySchema, anyReferences);
case 'Array': case 'Array':
return Array(anySchema, anyReferences); return Array(anySchema, anyReferences);
case 'Boolean': case 'Boolean':
return Boolean(anySchema, anyReferences); return Boolean(anySchema, anyReferences);
case 'Constructor': case 'Constructor':
return Constructor(anySchema, anyReferences); return Constructor(anySchema, anyReferences);
case 'Enum': case 'Enum':
return Enum(anySchema, anyReferences); return Enum(anySchema, anyReferences);
case 'Function': case 'Function':
return Function(anySchema, anyReferences); return Function(anySchema, anyReferences);
case 'Integer': case 'Integer':
return Integer(anySchema, anyReferences); return Integer(anySchema, anyReferences);
case 'Literal': case 'Literal':
return Literal(anySchema, anyReferences); return Literal(anySchema, anyReferences);
case 'Never': case 'Never':
return Never(anySchema, anyReferences); return Never(anySchema, anyReferences);
case 'Null': case 'Null':
return Null(anySchema, anyReferences); return Null(anySchema, anyReferences);
case 'Number': case 'Number':
return Number(anySchema, anyReferences); return Number(anySchema, anyReferences);
case 'Object': case 'Object':
return Object(anySchema, anyReferences); return Object(anySchema, anyReferences);
case 'Promise': case 'Promise':
return Promise(anySchema, anyReferences); return Promise(anySchema, anyReferences);
case 'Record': case 'Record':
return Record(anySchema, anyReferences); return Record(anySchema, anyReferences);
case 'Rec': case 'Rec':
return Recursive(anySchema, anyReferences); return Recursive(anySchema, anyReferences);
case 'Ref': case 'Ref':
return Ref(anySchema, anyReferences); return Ref(anySchema, anyReferences);
case 'Self': case 'Self':
return Self(anySchema, anyReferences); return Self(anySchema, anyReferences);
case 'String': case 'String':
return String(anySchema, anyReferences); return String(anySchema, anyReferences);
case 'Tuple': case 'Tuple':
return Tuple(anySchema, anyReferences); return Tuple(anySchema, anyReferences);
case 'Undefined': case 'Undefined':
return Undefined(anySchema, anyReferences); return Undefined(anySchema, anyReferences);
case 'Union': case 'Union':
return Union(anySchema, anyReferences); return Union(anySchema, anyReferences);
case 'Uint8Array': case 'Uint8Array':
return Uint8Array(anySchema, anyReferences); return Uint8Array(anySchema, anyReferences);
case 'Unknown': case 'Unknown':
return Unknown(anySchema, anyReferences); return Unknown(anySchema, anyReferences);
case 'Void': case 'Void':
return Void(anySchema, anyReferences); return Void(anySchema, anyReferences);
default: default:
throw new ValueCreateUnknownTypeError(anySchema); throw new ValueCreateUnknownTypeError(anySchema);
} }
} }
ValueCreate.Visit = Visit; ValueCreate.Visit = Visit;
function Create(schema, references) { function Create(schema, references) {
return Visit(schema, references); return Visit(schema, references);
} }
ValueCreate.Create = Create; ValueCreate.Create = Create;
})(ValueCreate = exports.ValueCreate || (exports.ValueCreate = {})); })(ValueCreate = exports.ValueCreate || (exports.ValueCreate = {}));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,48 +1,48 @@
"use strict"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/value @sinclair/typebox/value
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k; if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k); var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } }; desc = { enumerable: true, get: function() { return m[k]; } };
} }
Object.defineProperty(o, k2, desc); Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) { }) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k; if (k2 === undefined) k2 = k;
o[k2] = m[k]; o[k2] = m[k];
})); }));
var __exportStar = (this && this.__exportStar) || function(m, exports) { 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); for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
}; };
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.ValueErrorType = void 0; exports.ValueErrorType = void 0;
var index_1 = require("../errors/index"); var index_1 = require("../errors/index");
Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } }); Object.defineProperty(exports, "ValueErrorType", { enumerable: true, get: function () { return index_1.ValueErrorType; } });
__exportStar(require("./pointer"), exports); __exportStar(require("./pointer"), exports);
__exportStar(require("./value"), 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 ValueType = null | undefined | Function | symbol | bigint | number | boolean | string;
export declare type ObjectType = Record<string | number | symbol, unknown>; 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 TypedArrayType = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
export declare type ArrayType = unknown[]; export declare type ArrayType = unknown[];
export declare namespace Is { export declare namespace Is {
function Object(value: unknown): value is ObjectType; function Object(value: unknown): value is ObjectType;
function Array(value: unknown): value is ArrayType; function Array(value: unknown): value is ArrayType;
function Value(value: unknown): value is ValueType; function Value(value: unknown): value is ValueType;
function TypedArray(value: unknown): value is TypedArrayType; function TypedArray(value: unknown): value is TypedArrayType;
} }

View File

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

View File

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

View File

@@ -1,142 +1,142 @@
"use strict"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/value @sinclair/typebox/value
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.ValuePointer = exports.ValuePointerRootDeleteError = exports.ValuePointerRootSetError = void 0; exports.ValuePointer = exports.ValuePointerRootDeleteError = exports.ValuePointerRootSetError = void 0;
class ValuePointerRootSetError extends Error { class ValuePointerRootSetError extends Error {
constructor(value, path, update) { constructor(value, path, update) {
super('ValuePointer: Cannot set root value'); super('ValuePointer: Cannot set root value');
this.value = value; this.value = value;
this.path = path; this.path = path;
this.update = update; this.update = update;
} }
} }
exports.ValuePointerRootSetError = ValuePointerRootSetError; exports.ValuePointerRootSetError = ValuePointerRootSetError;
class ValuePointerRootDeleteError extends Error { class ValuePointerRootDeleteError extends Error {
constructor(value, path) { constructor(value, path) {
super('ValuePointer: Cannot delete root value'); super('ValuePointer: Cannot delete root value');
this.value = value; this.value = value;
this.path = path; this.path = path;
} }
} }
exports.ValuePointerRootDeleteError = ValuePointerRootDeleteError; exports.ValuePointerRootDeleteError = ValuePointerRootDeleteError;
/** ValuePointer performs mutable operations on values using RFC6901 Json Pointers */ /** ValuePointer performs mutable operations on values using RFC6901 Json Pointers */
var ValuePointer; var ValuePointer;
(function (ValuePointer) { (function (ValuePointer) {
function Escape(component) { function Escape(component) {
return component.indexOf('~') === -1 ? component : component.replace(/~1/g, '/').replace(/~0/g, '~'); return component.indexOf('~') === -1 ? component : component.replace(/~1/g, '/').replace(/~0/g, '~');
} }
/** Formats the given pointer into navigable key components */ /** Formats the given pointer into navigable key components */
function* Format(pointer) { function* Format(pointer) {
if (pointer === '') if (pointer === '')
return; return;
let [start, end] = [0, 0]; let [start, end] = [0, 0];
for (let i = 0; i < pointer.length; i++) { for (let i = 0; i < pointer.length; i++) {
const char = pointer.charAt(i); const char = pointer.charAt(i);
if (char === '/') { if (char === '/') {
if (i === 0) { if (i === 0) {
start = i + 1; start = i + 1;
} }
else { else {
end = i; end = i;
yield Escape(pointer.slice(start, end)); yield Escape(pointer.slice(start, end));
start = i + 1; start = i + 1;
} }
} }
else { else {
end = i; end = i;
} }
} }
yield Escape(pointer.slice(start)); yield Escape(pointer.slice(start));
} }
ValuePointer.Format = Format; ValuePointer.Format = Format;
/** Sets the value at the given pointer. If the value at the pointer does not exist it is created */ /** Sets the value at the given pointer. If the value at the pointer does not exist it is created */
function Set(value, pointer, update) { function Set(value, pointer, update) {
if (pointer === '') if (pointer === '')
throw new ValuePointerRootSetError(value, pointer, update); throw new ValuePointerRootSetError(value, pointer, update);
let [owner, next, key] = [null, value, '']; let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) { for (const component of Format(pointer)) {
if (next[component] === undefined) if (next[component] === undefined)
next[component] = {}; next[component] = {};
owner = next; owner = next;
next = next[component]; next = next[component];
key = component; key = component;
} }
owner[key] = update; owner[key] = update;
} }
ValuePointer.Set = Set; ValuePointer.Set = Set;
/** Deletes a value at the given pointer */ /** Deletes a value at the given pointer */
function Delete(value, pointer) { function Delete(value, pointer) {
if (pointer === '') if (pointer === '')
throw new ValuePointerRootDeleteError(value, pointer); throw new ValuePointerRootDeleteError(value, pointer);
let [owner, next, key] = [null, value, '']; let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) { for (const component of Format(pointer)) {
if (next[component] === undefined || next[component] === null) if (next[component] === undefined || next[component] === null)
return; return;
owner = next; owner = next;
next = next[component]; next = next[component];
key = component; key = component;
} }
if (globalThis.Array.isArray(owner)) { if (globalThis.Array.isArray(owner)) {
const index = parseInt(key); const index = parseInt(key);
owner.splice(index, 1); owner.splice(index, 1);
} }
else { else {
delete owner[key]; delete owner[key];
} }
} }
ValuePointer.Delete = Delete; ValuePointer.Delete = Delete;
/** Returns true if a value exists at the given pointer */ /** Returns true if a value exists at the given pointer */
function Has(value, pointer) { function Has(value, pointer) {
if (pointer === '') if (pointer === '')
return true; return true;
let [owner, next, key] = [null, value, '']; let [owner, next, key] = [null, value, ''];
for (const component of Format(pointer)) { for (const component of Format(pointer)) {
if (next[component] === undefined) if (next[component] === undefined)
return false; return false;
owner = next; owner = next;
next = next[component]; next = next[component];
key = component; key = component;
} }
return globalThis.Object.getOwnPropertyNames(owner).includes(key); return globalThis.Object.getOwnPropertyNames(owner).includes(key);
} }
ValuePointer.Has = Has; ValuePointer.Has = Has;
/** Gets the value at the given pointer */ /** Gets the value at the given pointer */
function Get(value, pointer) { function Get(value, pointer) {
if (pointer === '') if (pointer === '')
return value; return value;
let current = value; let current = value;
for (const component of Format(pointer)) { for (const component of Format(pointer)) {
if (current[component] === undefined) if (current[component] === undefined)
return undefined; return undefined;
current = current[component]; current = current[component];
} }
return current; return current;
} }
ValuePointer.Get = Get; ValuePointer.Get = Get;
})(ValuePointer = exports.ValuePointer || (exports.ValuePointer = {})); })(ValuePointer = exports.ValuePointer || (exports.ValuePointer = {}));

View File

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

View File

@@ -1,81 +1,81 @@
"use strict"; "use strict";
/*-------------------------------------------------------------------------- /*--------------------------------------------------------------------------
@sinclair/typebox/value @sinclair/typebox/value
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com> Copyright (c) 2022 Haydn Paterson (sinclair) <haydn.developer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions: furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software. all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
---------------------------------------------------------------------------*/ ---------------------------------------------------------------------------*/
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
exports.Value = void 0; exports.Value = void 0;
const index_1 = require("../errors/index"); const index_1 = require("../errors/index");
const equal_1 = require("./equal"); const equal_1 = require("./equal");
const cast_1 = require("./cast"); const cast_1 = require("./cast");
const clone_1 = require("./clone"); const clone_1 = require("./clone");
const create_1 = require("./create"); const create_1 = require("./create");
const check_1 = require("./check"); const check_1 = require("./check");
const delta_1 = require("./delta"); const delta_1 = require("./delta");
/** Value performs immutable operations on values */ /** Value performs immutable operations on values */
var Value; var Value;
(function (Value) { (function (Value) {
function Cast(...args) { function Cast(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]]; 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); return cast_1.ValueCast.Cast(schema, references, value);
} }
Value.Cast = Cast; Value.Cast = Cast;
function Create(...args) { function Create(...args) {
const [schema, references] = args.length === 2 ? [args[0], args[1]] : [args[0], []]; const [schema, references] = args.length === 2 ? [args[0], args[1]] : [args[0], []];
return create_1.ValueCreate.Create(schema, references); return create_1.ValueCreate.Create(schema, references);
} }
Value.Create = Create; Value.Create = Create;
function Check(...args) { function Check(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]]; 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); return check_1.ValueCheck.Check(schema, references, value);
} }
Value.Check = Check; Value.Check = Check;
function* Errors(...args) { function* Errors(...args) {
const [schema, references, value] = args.length === 3 ? [args[0], args[1], args[2]] : [args[0], [], args[1]]; 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); yield* index_1.ValueErrors.Errors(schema, references, value);
} }
Value.Errors = Errors; Value.Errors = Errors;
/** Returns true if left and right values are structurally equal */ /** Returns true if left and right values are structurally equal */
function Equal(left, right) { function Equal(left, right) {
return equal_1.ValueEqual.Equal(left, right); return equal_1.ValueEqual.Equal(left, right);
} }
Value.Equal = Equal; Value.Equal = Equal;
/** Returns a structural clone of the given value */ /** Returns a structural clone of the given value */
function Clone(value) { function Clone(value) {
return clone_1.ValueClone.Clone(value); return clone_1.ValueClone.Clone(value);
} }
Value.Clone = Clone; Value.Clone = Clone;
/** Returns edits to transform the current value into the next value */ /** Returns edits to transform the current value into the next value */
function Diff(current, next) { function Diff(current, next) {
return delta_1.ValueDelta.Diff(current, next); return delta_1.ValueDelta.Diff(current, next);
} }
Value.Diff = Diff; Value.Diff = Diff;
/** Returns a new value with edits applied to the given value */ /** Returns a new value with edits applied to the given value */
function Patch(current, edits) { function Patch(current, edits) {
return delta_1.ValueDelta.Patch(current, edits); return delta_1.ValueDelta.Patch(current, edits);
} }
Value.Patch = Patch; Value.Patch = Patch;
})(Value = exports.Value || (exports.Value = {})); })(Value = exports.Value || (exports.Value = {}));

View File

@@ -1,16 +1,16 @@
# Installation # Installation
> `npm install --save @types/babel__core` > `npm install --save @types/babel__core`
# Summary # Summary
This package contains type definitions for @babel/core (https://github.com/babel/babel/tree/master/packages/babel-core). This package contains type definitions for @babel/core (https://github.com/babel/babel/tree/master/packages/babel-core).
# Details # Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__core. Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__core.
### Additional Details ### Additional Details
* Last updated: Mon, 07 Nov 2022 20:33:43 GMT * 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) * 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` * Global values: `babel`
# Credits # 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). 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 # Installation
> `npm install --save @types/babel__generator` > `npm install --save @types/babel__generator`
# Summary # Summary
This package contains type definitions for @babel/generator (https://github.com/babel/babel/tree/master/packages/babel-generator). This package contains type definitions for @babel/generator (https://github.com/babel/babel/tree/master/packages/babel-generator).
# Details # Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__generator. Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__generator.
### Additional Details ### Additional Details
* Last updated: Thu, 23 Dec 2021 23:34:17 GMT * Last updated: Thu, 23 Dec 2021 23:34:17 GMT
* Dependencies: [@types/babel__types](https://npmjs.com/package/@types/babel__types) * Dependencies: [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: none * Global values: none
# Credits # 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). 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 # Installation
> `npm install --save @types/babel__template` > `npm install --save @types/babel__template`
# Summary # Summary
This package contains type definitions for @babel/template (https://github.com/babel/babel/tree/master/packages/babel-template). This package contains type definitions for @babel/template (https://github.com/babel/babel/tree/master/packages/babel-template).
# Details # Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__template. Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__template.
### Additional Details ### Additional Details
* Last updated: Tue, 06 Jul 2021 18:05:41 GMT * 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) * Dependencies: [@types/babel__parser](https://npmjs.com/package/@types/babel__parser), [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: none * Global values: none
# Credits # 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). 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 # Installation
> `npm install --save @types/babel__traverse` > `npm install --save @types/babel__traverse`
# Summary # Summary
This package contains type definitions for @babel/traverse (https://github.com/babel/babel/tree/main/packages/babel-traverse). This package contains type definitions for @babel/traverse (https://github.com/babel/babel/tree/main/packages/babel-traverse).
# Details # Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__traverse. Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/babel__traverse.
### Additional Details ### Additional Details
* Last updated: Mon, 28 Nov 2022 17:02:52 GMT * Last updated: Mon, 28 Nov 2022 17:02:52 GMT
* Dependencies: [@types/babel__types](https://npmjs.com/package/@types/babel__types) * Dependencies: [@types/babel__types](https://npmjs.com/package/@types/babel__types)
* Global values: none * Global values: none
# Credits # 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). 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 # Installation
> `npm install --save @types/graceful-fs` > `npm install --save @types/graceful-fs`
# Summary # Summary
This package contains type definitions for graceful-fs (https://github.com/isaacs/node-graceful-fs). This package contains type definitions for graceful-fs (https://github.com/isaacs/node-graceful-fs).
# Details # Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/graceful-fs. Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/graceful-fs.
### Additional Details ### Additional Details
* Last updated: Thu, 11 Feb 2021 21:48:33 GMT * Last updated: Thu, 11 Feb 2021 21:48:33 GMT
* Dependencies: [@types/node](https://npmjs.com/package/@types/node) * Dependencies: [@types/node](https://npmjs.com/package/@types/node)
* Global values: none * Global values: none
# Credits # Credits
These definitions were written by [Bart van der Schoor](https://github.com/Bartvds), and [BendingBender](https://github.com/BendingBender). 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 # Installation
> `npm install --save @types/istanbul-lib-coverage` > `npm install --save @types/istanbul-lib-coverage`
# Summary # Summary
This package contains type definitions for istanbul-lib-coverage (https://istanbul.js.org). This package contains type definitions for istanbul-lib-coverage (https://istanbul.js.org).
# Details # Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-lib-coverage. Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-lib-coverage.
### Additional Details ### Additional Details
* Last updated: Thu, 23 Dec 2021 23:34:53 GMT * Last updated: Thu, 23 Dec 2021 23:34:53 GMT
* Dependencies: none * Dependencies: none
* Global values: none * Global values: none
# Credits # Credits
These definitions were written by [Jason Cheatham](https://github.com/jason0x43). These definitions were written by [Jason Cheatham](https://github.com/jason0x43).

View File

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

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