diff --git a/.github/workflows/PSScriptAnalyzer.yml b/.github/workflows/PSScriptAnalyzer.yml new file mode 100644 index 000000000..10a80b7ce --- /dev/null +++ b/.github/workflows/PSScriptAnalyzer.yml @@ -0,0 +1,49 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# +# https://github.com/microsoft/action-psscriptanalyzer +# For more information on PSScriptAnalyzer in general, see +# https://github.com/PowerShell/PSScriptAnalyzer + +name: PSScriptAnalyzer + +on: + push: + branches: [ "develop" ] + pull_request: + branches: [ "develop" ] + schedule: + - cron: '20 16 * * 6' + +permissions: + contents: read + +jobs: + build: + permissions: + contents: read # for actions/checkout to fetch code + security-events: write # for github/codeql-action/upload-sarif to upload SARIF results + actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status + name: PSScriptAnalyzer + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Run PSScriptAnalyzer + uses: microsoft/psscriptanalyzer-action@6b2948b1944407914a58661c49941824d149734f + with: + # Check https://github.com/microsoft/action-psscriptanalyzer for more info about the options. + # The below set up runs PSScriptAnalyzer to your entire repository and runs some basic security rules. + path: .\ + recurse: true + # Include your own basic security rules. Removing this option will run all the rules + includeRule: '"PSAvoidUsingCmdletAliases" ,"PSAvoidUsingPlainTextForPassword","PSAvoidUsingWriteHost","PSAvoidUsingInvokeExpression","PSUseShouldProcessForStateChangingFunctions","PSAvoidUsingUsernameAndPasswordParams","PSUseProcessBlockForPipelineCommand","PSAvoidUsingConvertToSecureStringWithPlainText","PSUseSingularNouns","PSReviewUnusedParameter"' + output: results.sarif + + # Upload the SARIF file generated in the previous step + - name: Upload SARIF results file + uses: github/codeql-action/upload-sarif@v3 + with: + sarif_file: results.sarif diff --git a/.github/workflows/ci-coverage.yml b/.github/workflows/ci-coverage.yml index ec505f8cc..c31363e51 100644 --- a/.github/workflows/ci-coverage.yml +++ b/.github/workflows/ci-coverage.yml @@ -15,13 +15,22 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 + + - name: Check PowerShell version + shell: pwsh + run: | + $PSVersionTable.PSVersion + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x - name: Install Invoke-Build shell: pwsh run: | - [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 - Install-Module -Name InvokeBuild -RequiredVersion '5.5.1' -Force + Install-Module -Name InvokeBuild -RequiredVersion '5.10.5' -Force - name: Run Pester Tests shell: pwsh @@ -29,5 +38,4 @@ jobs: PODE_COVERALLS_TOKEN: ${{ secrets.PODE_COVERALLS_TOKEN }} PODE_RUN_CODE_COVERAGE: false run: | - [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 Invoke-Build Test \ No newline at end of file diff --git a/.github/workflows/ci-powershell.yml b/.github/workflows/ci-powershell.yml new file mode 100644 index 000000000..0287d587e --- /dev/null +++ b/.github/workflows/ci-powershell.yml @@ -0,0 +1,43 @@ +name: Pode CI - Powershell Desktop + +on: + push: + branches: + - '*' + - '!gh-pages' + pull_request: + branches: + - '*' + +jobs: + build: + + runs-on: windows-latest + + strategy: + fail-fast: false + + steps: + - uses: actions/checkout@v4 + + - name: Check PowerShell version + shell: powershell + run: | + $PSVersionTable.PSVersion + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - name: Install Invoke-Build + shell: powershell + run: | + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + Install-Module -Name InvokeBuild -RequiredVersion '5.10.5' -Force + + - name: Run Pester Tests + shell: powershell + run: | + [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + Invoke-Build Test \ No newline at end of file diff --git a/.github/workflows/ci-pwsh7_2.yml b/.github/workflows/ci-pwsh7_2.yml new file mode 100644 index 000000000..644de40d4 --- /dev/null +++ b/.github/workflows/ci-pwsh7_2.yml @@ -0,0 +1,53 @@ +name: Pode CI - pwsh 7.2 + +on: + push: + branches: + - '*' + - '!gh-pages' + pull_request: + branches: + - '*' + +jobs: + build: + + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + + steps: + - uses: actions/checkout@v4 + + - name: Setup Powershell + uses: bjompen/UpdatePWSHAction@v1.0.0 + with: + FixedVersion: '7.2.18' + + - name: Check PowerShell version + shell: pwsh + run: | + $PSVersionTable.PSVersion + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - name: Install Invoke-Build + shell: pwsh + run: | + Install-Module -Name InvokeBuild -RequiredVersion '5.10.5' -Force + + - name: Run Pester Tests + shell: pwsh + run: | + Invoke-Build Test + + - name: Test docker builds + shell: pwsh + run: | + Invoke-Build DockerPack -Version '0.0.0' \ No newline at end of file diff --git a/.github/workflows/ci-pwsh7_3.yml b/.github/workflows/ci-pwsh7_3.yml new file mode 100644 index 000000000..82e03e4ee --- /dev/null +++ b/.github/workflows/ci-pwsh7_3.yml @@ -0,0 +1,53 @@ +name: Pode CI - pwsh 7.3 + +on: + push: + branches: + - '*' + - '!gh-pages' + pull_request: + branches: + - '*' + +jobs: + build: + + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + + steps: + - uses: actions/checkout@v4 + + - name: Setup Powershell + uses: bjompen/UpdatePWSHAction@v1.0.0 + with: + FixedVersion: '7.3.11' + + - name: Check PowerShell version + shell: pwsh + run: | + $PSVersionTable.PSVersion + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - name: Install Invoke-Build + shell: pwsh + run: | + Install-Module -Name InvokeBuild -RequiredVersion '5.10.5' -Force + + - name: Run Pester Tests + shell: pwsh + run: | + Invoke-Build Test + + - name: Test docker builds + shell: pwsh + run: | + Invoke-Build DockerPack -Version '0.0.0' \ No newline at end of file diff --git a/.github/workflows/ci-pwsh_lts.yml b/.github/workflows/ci-pwsh_lts.yml new file mode 100644 index 000000000..ee811c145 --- /dev/null +++ b/.github/workflows/ci-pwsh_lts.yml @@ -0,0 +1,53 @@ +name: Pode CI - pwsh lts + +on: + push: + branches: + - '*' + - '!gh-pages' + pull_request: + branches: + - '*' + +jobs: + build: + + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macOS-latest] + + steps: + - uses: actions/checkout@v4 + + - name: Setup Powershell + uses: bjompen/UpdatePWSHAction@v1.0.0 + with: + ReleaseVersion: 'lts' + + - name: Check PowerShell version + shell: pwsh + run: | + $PSVersionTable.PSVersion + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - name: Install Invoke-Build + shell: pwsh + run: | + Install-Module -Name InvokeBuild -RequiredVersion '5.10.5' -Force + + - name: Run Pester Tests + shell: pwsh + run: | + Invoke-Build Test + + - name: Test docker builds + shell: pwsh + run: | + Invoke-Build DockerPack -Version '0.0.0' \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci-pwsh_preview.yml similarity index 60% rename from .github/workflows/ci.yml rename to .github/workflows/ci-pwsh_preview.yml index ff02d022d..110e3d92f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci-pwsh_preview.yml @@ -1,4 +1,4 @@ -name: Pode CI +name: Pode CI - pwsh preview on: push: @@ -20,23 +20,31 @@ jobs: os: [ubuntu-latest, windows-latest, macOS-latest] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 + + - name: Setup Powershell + uses: bjompen/UpdatePWSHAction@v1.0.0 + with: + ReleaseVersion: 'Preview' + + - name: Check PowerShell version + shell: pwsh + run: | + $PSVersionTable.PSVersion - name: Setup .NET - uses: actions/setup-dotnet@v1.9.0 + uses: actions/setup-dotnet@v4 with: - dotnet-version: 7.0.x + dotnet-version: 8.0.x - name: Install Invoke-Build shell: pwsh run: | - [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 - Install-Module -Name InvokeBuild -RequiredVersion '5.5.1' -Force + Install-Module -Name InvokeBuild -RequiredVersion '5.10.5' -Force - name: Run Pester Tests shell: pwsh - run: | - [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 + run: | Invoke-Build Test - name: Test docker builds diff --git a/.gitignore b/.gitignore index 3d08e5422..aa5c0e490 100644 --- a/.gitignore +++ b/.gitignore @@ -9,9 +9,9 @@ examples/state.json examples/issue-* examples/issues/ pkg/ +deliverable/ .vs/ - # Code Runner tempCodeRunnerFile.ps1 @@ -189,7 +189,6 @@ ClientBin/ *.publishsettings node_modules/ - # RIA/Silverlight projects Generated_Code/ @@ -258,4 +257,11 @@ $RECYCLE.BIN/ *.msp # Windows shortcuts -*.lnk \ No newline at end of file +*.lnk +.vscode/launch.json +Pode.sln +examples/FileBrowser/wwwFiles/ +examples/PetStore/data/PetData.json + +packers/choco/pode.nuspec +packers/choco/tools/ChocolateyInstall.ps1 diff --git a/.vscode/settings.json b/.vscode/settings.json index 0eada4b5d..559d3ecf2 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -20,5 +20,17 @@ "powershell.codeFormatting.whitespaceBeforeOpenParen": true, "powershell.codeFormatting.whitespaceBetweenParameters": false, "powershell.codeFormatting.whitespaceInsideBrace": true, - "files.trimTrailingWhitespace": true + "powershell.scriptAnalysis.settingsPath": "PSScriptAnalyzerSettings.psd1", + "files.trimTrailingWhitespace": true, + "files.associations": { + "*.pode": "html" + }, + "[html]": { + "editor.formatOnSave": false + }, + "javascript.format.insertSpaceAfterCommaDelimiter": true, + "javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": false, + "javascript.format.insertSpaceAfterKeywordsInControlFlowStatements": true, + "javascript.format.insertSpaceBeforeAndAfterBinaryOperators": true, + "javascript.format.insertSpaceBeforeFunctionParenthesis": false } \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt index e6d70bc0b..504a54493 100644 --- a/LICENSE.txt +++ b/LICENSE.txt @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) [2017-2023] [Matthew Kelly (Badgerati)] +Copyright (c) [2017-2024] [Matthew Kelly (Badgerati)] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +18,1196 @@ 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. \ No newline at end of file +SOFTWARE. + + + +=========================================================================== + +Pode includes a number of components with separate copyright notices and license terms. This product does not necessarily use all the open source components referred to below. Your use of the source code for these components is subject to the terms and conditions of the following licenses. + +=============== TABLE OF CONTENTS ============================= + + +SECTION 1: Apache License, V2.0 + >>> Authress-Engineering/openapi-explorer + >>> stoplightio/elements + >>> swagger-api/swagger-editor + >>> swagger-api/swagger-ui + >>> cloudbase/powershell-yaml +SECTION 2: BSD-STYLE, MIT-STYLE, OR SIMILAR STYLE LICENSES + >>> mrin9/RapiPdf + >>> Redocly/redoc + >>> Phil-Factor/PSYaml + +-------------------- SECTION 1: Apache License, V2.0 -------------------- + + + >>> Authress-Engineering/openapi-explorer + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS"," BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS"," BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + ADDITIONAL LICENSE INFORMATION + name: openapi-explorer + version: 0.0.0 + description: OpenAPI Explorer - API viewer with dynamically generated components, documentation, and interaction console + author: Authress Developers + + >>> stoplightio/elements + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS"," BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2018 Stoplight, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS"," BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + ADDITIONAL LICENSE INFORMATION + author: Stoplight + + >>> swagger-api/swagger-editor + + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS"," BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS"," BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + ADDITIONAL LICENSE INFORMATION + name: swagger-editor + description: Swagger Editor + version: 4.11.2 + contributors (in alphabetical order): + Anna Bodnia + Buu Nguyen + Josh Ponelat + Kyle Shockey + Robert Barnwell + Sahar Jafari " + + >>> swagger-api/swagger-ui + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS"," BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS"," BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + ADDITIONAL LICENSE INFORMATION + name: swagger-ui + version: 5.10.5 + contributors (in alphabetical order) : + Anna Bodnia + Buu Nguyen + Josh Ponelat + Kyle Shockey + Robert Barnwell + Sahar Jafari + Vladimir Gorej " + + >>> cloudbase/powershell-yaml + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2016-2023 Cloudbase Solutions SRL + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + ADDITIONAL LICENSE INFORMATION + name: powershell-yaml + version: 0.4.7 + description: Powershell module for serializing and deserializing YAML + author: Gabriel Adrian Samfira,Alessandro Pilotti + CompanyName: Cloudbase Solutions SRL + + + +-------------------- SECTION 2: BSD-STYLE, MIT-STYLE, OR SIMILAR STYLE LICENSES -------------------- + + >>> mrin9/RapiPdf + MIT License + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + ADDITIONAL LICENSE INFORMATION + name: rapipdf + version: 2.2.1 + description: RapiPdf - Generate PDF from Open API spec + author: Mrinmoy Majumdar + + >>> Redocly/redoc + The MIT License (MIT) + + Copyright (c) 2015-present, Rebilly, Inc. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + + ADDITIONAL LICENSE INFORMATION + name: redoc + version: 2.1.3 + description: ReDoc + author: Roman Hotsiy + + + >>> rapi-doc/RapiDoc + MIT License + + Copyright (c) 2022 Mrinmoy Majumdar + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + ADDITIONAL LICENSE INFORMATION + name: rapidoc + version: 9.3.5-beta + description: RapiDoc - Open API spec viewer with built in console + author: Mrinmoy Majumdar + + >>> Phil-Factor/PSYaml + The MIT License (MIT) + + Copyright (c) 2016 Jakku Labs + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. + + ADDITIONAL LICENSE INFORMATION + name: PSYaml + version: 1.0.3 + description: PowerShell module used to intrepret Yaml formatted strings + author: Phil-Factor, Pezhore diff --git a/PSScriptAnalyzerSettings.psd1 b/PSScriptAnalyzerSettings.psd1 new file mode 100644 index 000000000..2141ac49d --- /dev/null +++ b/PSScriptAnalyzerSettings.psd1 @@ -0,0 +1,15 @@ +# PSScriptAnalyzerSettings.psd1 +@{ + Severity = @('Error', 'Warning', 'Information') + + Rules = @{ + PSReviewUnusedParameter = @{ + CommandsToTraverse = @( + 'Where-Object','Remove-PodeRoute' + ) + } + } + ExcludeRules = @('PSAvoidUsingCmdletAliases' ,'PSAvoidUsingPlainTextForPassword','PSAvoidUsingWriteHost','PSAvoidUsingInvokeExpression','PSUseShouldProcessForStateChangingFunctions', + 'PSAvoidUsingUsernameAndPasswordParams','PSUseProcessBlockForPipelineCommand','PSAvoidUsingConvertToSecureStringWithPlainText','PSUseSingularNouns','PSReviewUnusedParameter' ) + +} \ No newline at end of file diff --git a/Pode.sln b/Pode.sln new file mode 100644 index 000000000..66eb3805a --- /dev/null +++ b/Pode.sln @@ -0,0 +1,30 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.002.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{41F81369-8680-4BC5-BA16-C7891D245717}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Pode", "src\Listener\Pode.csproj", "{772D5C9F-1B25-46A7-8977-412A5F7F77D1}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {772D5C9F-1B25-46A7-8977-412A5F7F77D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {772D5C9F-1B25-46A7-8977-412A5F7F77D1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {772D5C9F-1B25-46A7-8977-412A5F7F77D1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {772D5C9F-1B25-46A7-8977-412A5F7F77D1}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {772D5C9F-1B25-46A7-8977-412A5F7F77D1} = {41F81369-8680-4BC5-BA16-C7891D245717} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F24001DC-2986-4305-B1B5-8E73BCDF1A77} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md index 9ba22b6c6..4d14d2289 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,7 @@ Then navigate to `http://127.0.0.1:8000` in your browser. * Azure Functions, AWS Lambda, and IIS support * OpenAPI, Swagger, and ReDoc support * Listen on a single or multiple IP address/hostnames -* Cross-platform support for HTTP(S), SMTP(S), and TCP(S) -* Cross-platform support for WebSockets, including secure WebSockets +* Cross-platform support for HTTP(S), WS(S), SSE, SMTP(S), and TCP(S) * Host REST APIs, Web Pages, and Static Content (with caching) * Support for custom error pages * Request and Response compression using GZip/Deflate @@ -72,6 +71,7 @@ Then navigate to `http://127.0.0.1:8000` in your browser. * Generate/bind self-signed certificates * Secret management support to load secrets from vaults * Support for File Watchers +* In-memory caching, with optional support for external providers (such as Redis) * (Windows) Open the hosted server as a desktop application ## 📦 Install @@ -107,6 +107,8 @@ To just build Pode, before running any examples, run the following: Invoke-Build Build ``` +More information on how to build Pode can be [found here](./docs/Getting-Started/build.md) + To work on issues you can fork Pode, and then open a Pull Request for approval. Pull Requests should be made against the `develop` branch. Each Pull Request should also have an appropriate issue created. ## 🌎 Roadmap diff --git a/docs/Getting-Started/Debug.md b/docs/Getting-Started/Debug.md new file mode 100644 index 000000000..a4647d3c5 --- /dev/null +++ b/docs/Getting-Started/Debug.md @@ -0,0 +1,176 @@ +# Debugging Pode + +When using Pode there will often be times when you need to debug aspects of your scripts. Debugging in Pode can be achieved in a couple of ways: + +1. Write messages to the console. +2. Use PowerShell's debugger. + +## Messages + +To output messages from your Routes, Timers, etc. you can either call PowerShell's `Out-Default`, or Pode's [`Out-PodeHost`](../../Functions/Utilities/Out-PodeHost). The latter is just a wrapper around `Out-Default` however, it respects the `-Quiet` switch if supplied to [`Start-PodeServer`](../../Functions/Core/Start-PodeServer) - suppressing the messages when not needed. + +For example, the following will output messages and variables from a Route: + +```powershell +Start-PodeServer { + Add-PodeEndpoint -Address localhost -Port 8080 -Protocol Http + + Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + 'Start of / Route' | Out-PodeHost + $processes = Get-Process + "Processes found: $($processes.Length)" | Out-PodeHost + $processes[0] | Out-PodeHost + Write-PodeJsonResponse -Value @{ Process = $processes[0] } + } +} +``` + +This will output 3 messages to the host window where Pode is running when the Route is invoked, as follows: + +```powershell +Invoke-RestMethod -Uri 'http://localhost:8080/' +``` + +```plain +Start of / Route +Processes found: 393 + + NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName + ------ ----- ----- ------ -- -- ----------- + 7 2.45 3.66 3.48 7044 0 AggregatorHost +``` + +!!! tip + You can leave the `Out-PodeHost` lines in place, and suppress them by passing `-Quiet` to `Start-PodeServer`. + +## Debugger + +You can breakpoint directly into a running Pode server by using either PowerShell's `Wait-Debugger` or Pode's [`Wait-PodeDebugger`](../../Functions/Core/Wait-PodeDebugger). The latter is just a wrapper around `Wait-Debugger` however, it respects the `-EnableBreakpoints` switch if supplied to [`Start-PodeServer`](../../Functions/Core/Start-PodeServer) - allowing you to suppress the breakpoints when not needed. Regardless of the Wait command chosen, the process to attach to the Pode process is the same. + +For example, the following will create a breakpoint for PowerShell's debugger when the Route is invoked: + +```powershell +Start-PodeServer -EnableBreakpoints { + Add-PodeEndpoint -Address localhost -Port 8080 -Protocol Http + + Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + Wait-PodeDebugger + $processes = Get-Process + Write-PodeJsonResponse -Value @{ Process = $processes[0] } + } +} +``` + +The steps to attach to the Pode process are as follows: + +1. In a PowerShell console, start the above Pode server. You will see the following output, and you'll need the PID that is shown: + ```plain + Pode v2.10.0 (PID: 28324) + Listening on the following 1 endpoint(s) [1 thread(s)]: + - http://localhost:8080/ + ``` + +2. In a browser or a new PowerShell console, invoke the `[GET] http://localhost:8080` Route to hit the breakpoint. + ```powershell + Invoke-RestMethod -Uri 'http://localhost:8080/' + ``` + +3. Open another new PowerShell console, and run the following command to enter the first PowerShell console running Pode - you'll need the PID as well: + ```powershell + Enter-PSHostProcess -Id '' + ``` + +4. Once you have entered the PowerShell console running Pode, run the below command to attach to the breakpoint: + ```powershell + Get-Runspace | + Where-Object { $_.Debugger.InBreakpoint } | + Select-Object -First 1 | + Debug-Runspace -Confirm:$false + ``` + + 1. If you used `Wait-PodeDebugger` you'll need to hit the `s` key twice to get to the next actual line. + +5. Hit the `h` key to see the debugger commands you can use. In general, you'll be after: + 1. `s`: step into the next line, function, script + 2. `v`: step over the next line + 3. `o`: step out of the current function + 4. `d`: detach from the debugger, and let the script complete + +6. You'll also be able to query variables as well, such as `$WebEvent` and other variables you might have created. + +7. When you are done debugging the current request, hit the `d` key. + +8. When you're done with debugging altogether, you can exit the entered process as follows: + ```powershell + exit + ``` + +### Toggle Breakpoints + +If you're using [`Wait-PodeDebugger`](../../Functions/Core/Wait-PodeDebugger) then you can leave these breakpoint lines in place, and toggle them in non-developer environments by passing `-EnableBreakpoints` to [`Start-PodeServer`](../../Functions/Core/Start-PodeServer). If you don't supply `-EnableBreakpoints`, or you explicitly pass `-EnableBreakpoints:$false`, then this will disable the breakpoints from being set. + +You can also toggle breakpoints via the `server.psd1` [configuration file](../../Tutorials/Configuration): +```powershell +@{ + Server = @{ + Debug = @{ + Breakpoints = @{ + Enable = $true + } + } + } +} +``` + +!!! note + The default state is disabled. + +### Add-Debugger + +You can also use the [Add-Debugger](https://www.powershellgallery.com/packages/Add-Debugger) script from the PowerShell Gallery, allowing you to debug your Pode server within the same console that started Pode - making the debug process smoother, and not requiring multiple PowerShell consoles. + +To install `Add-Debugger`, you can do the following: + +```powershell +Install-Script -Name Add-Debugger +``` + +Once installed, you'll be able to use the `Add-Debugger` command within your Routes/etc., alongside `Wait-Debugger`/`Wait-PodeDebugger`. + +!!! note + If you're using `-EnableBreakpoints`, then setting this to false will not suppress calls to `Add-Debugger`. + +```powershell +Start-PodeServer -EnableBreakpoints { + Add-PodeEndpoint -Address localhost -Port 8080 -Protocol Http + + Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + Add-Debugger + Wait-PodeDebugger + $processes = Get-Process + Write-PodeJsonResponse -Value @{ Process = $processes[0] } + } +} +``` + +The steps to attach to the Pode process are as follows: + +1. In a PowerShell console, start the above Pode server. + +2. In a browser or a new PowerShell console, invoke the `[GET] http://localhost:8080` Route to hit the breakpoint. + ```powershell + Invoke-RestMethod -Uri 'http://localhost:8080/' + ``` + +3. Back in the PowerShell console running Pode, you'll see that it is now attached to the breakpoint for debugging. + 1. If you used `Wait-PodeDebugger` you'll need to hit the `s` key twice to get to the next actual line. + +4. Hit the `h` key to see the debugger commands you can use. In general, you'll be after: + 1. `s`: step into the next line, function, script + 2. `v`: step over the next line + 3. `o`: step out of the current function + 4. `d`: detach from the debugger, and let the script complete + +5. You'll also be able to query variables as well, such as `$WebEvent` and other variables you might have created. + +6. When you are done debugging the current request, hit the `d` key. diff --git a/docs/Getting-Started/KnownIssues.md b/docs/Getting-Started/KnownIssues.md index 903df8cb1..161be8fd5 100644 --- a/docs/Getting-Started/KnownIssues.md +++ b/docs/Getting-Started/KnownIssues.md @@ -6,9 +6,9 @@ Below is a list of reported issues when using Pode and, if possible, how to reso Reported in issue [#45](https://github.com/Badgerati/Pode/issues/45). -On Windows systems there is a limit on the maximum length of URL segments. It's usually about 260 characters, and anything above this will cause Pode to throw a 400 Bad Request error. +On Windows systems, there is a limit on the maximum length of URL segments. It's usually about 260 characters and anything above this will cause Pode to throw a 400 Bad Request error. -To resolve, you can set the `UrlSegmentMaxLength` registry setting to 0 (for unlimited), or any other value. The below PowerShell will set the value to unlimited: +To resolve this, you can set the `UrlSegmentMaxLength` registry setting to 0 (for unlimited), or any other value. The below PowerShell will set the value to unlimited: ```powershell New-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Services\HTTP\Parameters' -Name 'UrlSegmentMaxLength' -Value 0 -PropertyType DWord -Force @@ -18,7 +18,7 @@ New-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Services\HTTP\Parameters' ## PowerShell Classes -Pode uses Runspaces to deal with multithreading and other background tasks. Due to this, PowerShell classes do not work as intended, and are unsafe to use. +Pode uses Runspaces to deal with multithreading and other background tasks. Due to this, PowerShell classes do not work as intended and are unsafe to use. You can find more information about this issue [here on PowerShell](https://github.com/PowerShell/PowerShell/issues/3651). @@ -26,7 +26,7 @@ The crux of the issue is that if you create an instance of a class in one Runspa It's recommended to switch to either Hashtables or PSObjects, but if you need to use classes then the following should let classes work: -* Create a module (CreateClassInstanceHelper.psm1) with content: +* Create a module (CreateClassInstanceHelper.psm1) with the content: ```powershell $Script:powershell = $null @@ -105,3 +105,10 @@ Start-PodeServer { ## Loader Errors / Pode Types If on importing the module you receive Loader Exceptions, or when starting your server you get an error similar to `[PodeListener] not found`, then you will need to update to .NET 4.7.2. + +## Slow Requests + +If you are experiencing slow response times on Windows using either `Invoke-WebRequest` or `Invoke-RestMethod`, this could be due to a quirk in how these functions work - whereby they try to send the request using IPv6 first, then try IPv4. To potentially resolve the slowness, you can either: + +1. Use the IPv4 address instead of the hostname. For example, using `http://127.0.0.1:8080` instead of `http://localhost:8080`. +2. Enable [Dual Mode](../../Tutorials/Endpoints/Basics#dual-mode) on your [`Add-PodeEndpoint`](../../Functions/Core/Add-PodeEndpoint) so that it listens on both IPv4 and IPv6. diff --git a/docs/Getting-Started/build.md b/docs/Getting-Started/build.md new file mode 100644 index 000000000..419d6acf8 --- /dev/null +++ b/docs/Getting-Started/build.md @@ -0,0 +1,191 @@ + +# Building Pode + +If you have Pode's source code checked out locally on your machine, you can follow these steps to build Pode: + +## Windows + +1. Install InvokeBuild Module + + ### Using Powershell Gallery + + ```powershell + Install-Module InvokeBuild -Scope CurrentUser + ``` + + ### Using Chocolatey + + ```powershell + choco install invoke-build + ``` + +2. Test + + To run the unit tests, run the following command from the root of the repository (this will build Pode and, if needed, auto-install Pester/.NET): + + ```powershell + Invoke-Build Test + ``` + +3. Build + + To just build Pode, before running any examples, run the following: + + ```powershell + Invoke-Build Build + ``` + +4. Packaging + + To create a Pode package. Please note that docker has to be present to create the containers. + + ```powershell + Invoke-Build Pack + ``` + +5. Install locally + + To install Pode from the repository, run the following: + + ```powershell + Invoke-Build Install-Module + ``` + + To uninstall, use: + ```powershell + Invoke-Build Remove-Module + ``` + + +6. CleanUp + + To clean up after a build or a pack, run the following: + + ```powershell + Invoke-Build clean + ``` + +## Linux + +1. Register the Microsoft Repository + + #### CentOS + ```shell + sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc + sudo curl -o /etc/yum.repos.d/microsoft.repo https://packages.microsoft.com/config/centos/8/prod.repo + ``` + + #### RedHat + ```shell + sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc + sudo curl -o /etc/yum.repos.d/microsoft.repo https://packages.microsoft.com/config/rhel/9/prod.repo + ``` + + #### Debian / Ubuntu + ```shell + sudo apt-get update + sudo apt-get install -y wget apt-transport-https software-properties-common + wget https://packages.microsoft.com/config/debian/$(lsb_release -rs)/packages-microsoft-prod.deb -O packages-microsoft-prod.deb + sudo apt-get update; + ``` + + +2. Install InvokeBuild Module + + ```powershell + Install-Module InvokeBuild -Scope CurrentUser + ``` + + +3. Test + + To run the unit tests, run the following command from the root of the repository (this will build Pode and, if needed, auto-install Pester/.NET): + + ```powershell + Invoke-Build Test + ``` + +4. Build + + To just build Pode, before running any examples, run the following: + + ```powershell + Invoke-Build Build + ``` + +5. Packaging + + To create a Pode package. Please note that docker has to be present to create the containers. + + ```powershell + Invoke-Build Pack + ``` + +6. Install locally + + To install Pode from the repository, run the following: + + ```powershell + Invoke-Build Install-Module + ``` + + To uninstall, use: + + ```powershell + Invoke-Build Remove-Module + ``` + + +## MacOS + +An easy way to install the required components is to use [brew](https://brew.sh/): + +1. Install dotnet: + + ```shell + brew install dotnet + ``` + +2. Install InvokeBuild Module + + ```powershell + Install-Module InvokeBuild -Scope CurrentUser + ``` + +3. Test + + To run the unit tests, run the following command from the root of the repository (this will build Pode and, if needed, auto-install Pester/.NET): + + ```powershell + Invoke-Build Test + ``` + +4. Build + + To just build Pode, before running any examples, run the following: + + ```powershell + Invoke-Build Build + ``` + +5. Packaging + + To create a Pode package. Please note that docker has to be present to create the containers. + + ```powershell + Invoke-Build Pack + ``` + +6. Install locally + + To install Pode from the repository, run the following: + + ```powershell + Invoke-Build Install-Module + ``` + + To uninstall, use: + + ```powershell + Invoke-Build Remove-Module + ``` diff --git a/docs/Getting-Started/pwshsupportpolicy.md b/docs/Getting-Started/pwshsupportpolicy.md new file mode 100644 index 000000000..d2060cbe0 --- /dev/null +++ b/docs/Getting-Started/pwshsupportpolicy.md @@ -0,0 +1,30 @@ +# PowerShell Support Policy + +## Overview +This document details the support policy for PowerShell versions as they relate to Pode releases. Our aim is to provide clarity on which versions of PowerShell are supported by each release of Pode, ensuring a secure, efficient, and compatible development environment. + +## Policy Statement +Pode commits to supporting PowerShell versions that are not end of life (EOL) at the moment of each Pode release. This dynamic approach allows Pode to adapt to the evolving PowerShell ecosystem, ensuring compatibility with recent and supported PowerShell versions while maintaining a high security standard. + +### Support Lifecycle +- For each Pode release, support is extended to versions of PowerShell that are not EOL at the time of release. +- Subsequent Pode releases may not support previously compatible PowerShell versions if those versions have reached EOL in the interim. +- This policy applies to all versions of PowerShell, including PowerShell (version 7.x), PowerShell Core (versions 6.x) and Windows PowerShell 5.1. +- Windows Powershell 5.1 will be supported by any Pode version released prior the Jan 7 2027 + +### Example +- **Pode 2.10 Release (April 2024)**: Supports PowerShell 7.2, 7.3, 7.4, and Windows PowerShell 5.1, assuming none are EOL at the time of release. +- **Pode 2.11 Release (Late 2024)**: With PowerShell 7.2 and 7.3 reaching EOL, support for these versions would be discontinued. Pode 2.11 would then support PowerShell Core 7.4 and any newer, non-EOL versions, along with Windows PowerShell 5.1. + +## Testing Strategy +Pode is tested against the PowerShell versions it supports at the time of each release. Testing focuses on ensuring compatibility with non-EOL versions of PowerShell, reflecting the policy stated above. + +## Warning Mechanism +A warning mechanism within Pode detects the PowerShell version in use at runtime. If a version no longer supported by the current release of Pode is detected—due to reaching EOL—a warning will be issued, advising on the potential risks and recommending an update to a supported version. + +## Version Updates and Communication +Updates to the PowerShell version support policy will be documented in Pode’s release notes and official documentation. Users are encouraged to review these sources to stay informed about which PowerShell versions are supported by their version of Pode. + +## Feedback and Contributions +Feedback on Pode's PowerShell version support policy is invaluable. We welcome suggestions and contributions from our community to help refine and improve our approach. Please share your thoughts through our GitHub repository or community forums. + diff --git a/docs/Hosting/RunAsService.md b/docs/Hosting/RunAsService.md index e5ad7f420..f880dc63c 100644 --- a/docs/Hosting/RunAsService.md +++ b/docs/Hosting/RunAsService.md @@ -81,3 +81,58 @@ To stop the service afterwards, you can use the following: ```powershell sudo systemctl stop pode-server ``` +### Using Ports Below 1024 + +#### Introduction + +Traditionally in Linux, binding to ports below 1024 requires root privileges. This is a security measure, as these low-numbered ports are considered privileged. However, running applications as the root user poses significant security risks. This article explores methods to use these privileged ports with PowerShell (`pwsh`) in Linux, without running it as the root user. +There are different methods to achieve the goals. +Reverse Proxy is the right approach for a production environment, primarily if the server is connected directly to the internet. +The other solutions are reasonable after an in-depth risk analysis. + +#### Using a Reverse Proxy + +A reverse proxy like Nginx can listen on the privileged port and forward requests to your application running on an unprivileged port. + +**Configuration:** + +* Configure Nginx to listen on port 443 and forward requests to the port where your PowerShell script is listening. +* This method is widely used in web applications for its additional benefits like load balancing and SSL termination. + +#### iptables Redirection + +Using iptables, you can redirect traffic from a privileged port to a higher, unprivileged port. + +**Implementation:** + +* Set up an iptables rule to redirect traffic from, say, port 443 to a higher port where your PowerShell script is listening. +* `sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8080` + +**Benefits:** + +* This approach doesn't require changing the privileges of the PowerShell executable or script. + +#### Using `setcap` Command + +The `setcap` utility can grant specific capabilities to an executable, like `pwsh`, enabling it to bind to privileged ports. + +**How it Works:** + +* Run `sudo setcap 'cap_net_bind_service=+ep' $(which pwsh)`. This command sets the `CAP_NET_BIND_SERVICE` capability on the PowerShell executable, allowing it to bind to any port below 1024. + +**Security Consideration:** + +* This method enhances security by avoiding running PowerShell as root, but it still grants significant privileges to the PowerShell process. + +#### Utilizing Authbind + +Authbind is a tool that allows a non-root user to bind to privileged ports. + +**Setup:** + +* Install Authbind, configure it to allow the desired port, and then start your PowerShell script using Authbind. +* For instance, `authbind --deep pwsh yourscript.ps1` allows the script to bind to a privileged port. + +**Advantages:** + +* It provides a finer-grained control over port access and doesn't require setting special capabilities on the PowerShell binary itself. diff --git a/docs/Tutorials/Authentication/Overview.md b/docs/Tutorials/Authentication/Overview.md index a38b3ba7f..19ddacece 100644 --- a/docs/Tutorials/Authentication/Overview.md +++ b/docs/Tutorials/Authentication/Overview.md @@ -1,13 +1,13 @@ # Overview -Authentication can either be sessionless (requiring validation on every request), or session-persistent (only requiring validation once, and then checks against a session signed-cookie/header). +Authentication can either be sessionless (requiring validation on every request), or session-persistent (only requiring validation once, and then checks against a session-signed cookie/header). !!! info To use session-persistent authentication you will also need to use [Session Middleware](../../Middleware/Types/Sessions). -To setup and use authentication in Pode you need to use the [`New-PodeAuthScheme`](../../../Functions/Authentication/New-PodeAuthScheme) and [`Add-PodeAuth`](../../../Functions/Authentication/Add-PodeAuth) functions. +To set up and use authentication in Pode you need to use the [`New-PodeAuthScheme`](../../../Functions/Authentication/New-PodeAuthScheme) and [`Add-PodeAuth`](../../../Functions/Authentication/Add-PodeAuth) functions. -You can also setup [Authorisation](../../Authorisation/Overview) for use with Authentication as well. +You can also set up [Authorisation](../../Authorisation/Overview) for use with Authentication as well. ## Schemes @@ -82,9 +82,9 @@ New-PodeAuthScheme -Basic | Add-PodeAuth -Name 'Login' -Sessionless -ScriptBlock ``` If you're defining an authenticator that needs to send back a Challenge, then you can also do this by setting the response Code property to 401, and/or by also supplying a Challenge property. -This Challenge property is a string, and will be automatically appended onto the `WWW-Authenticate` Header. It *does not* need to include the Authentication Type or Realm (these will be added for you). +This Challenge property is a string and will be automatically appended onto the `WWW-Authenticate` Header. It *does not* need to include the Authentication Type or Realm (these will be added for you). -For example, in Digest you could return: +For example, in Digest, you could return: ```powershell return @{ @@ -95,9 +95,9 @@ return @{ ### Authenticate Type/Realm -When authentication fails, and a 401 response is returned, then Pode will also attempt to Response back to the client with a `WWW-Authenticate` header (if you've manually set this header using the custom headers from above, then the custom header will be used instead). For the inbuilt types, such as Basic, this Header will always be returned on a 401 response. +When authentication fails, and a 401 response is returned, then Pode will also attempt to respond to the client with a `WWW-Authenticate` header (if you've manually set this header using the custom headers from above, then the custom header will be used instead). For the inbuilt types, such as Basic, this Header will always be returned on a 401 response. -You can set the `-Name` and `-Realm` of the header using the [`New-PodeAuthScheme`](../../../Functions/Authentication/New-PodeAuthScheme) function. If no Name is supplied, then the header will not be returned - also if there is no Realm, then this will not be added onto the header. +You can set the `-Name` and `-Realm` of the header using the [`New-PodeAuthScheme`](../../../Functions/Authentication/New-PodeAuthScheme) function. If no Name is supplied, then the header will not be returned - also if there is no Realm, then this will not be added to the header. For example, if you setup Basic authenticate with a custom Realm as follows: @@ -105,7 +105,7 @@ For example, if you setup Basic authenticate with a custom Realm as follows: New-PodeAuthScheme -Basic -Realm 'Enter creds to access site' ``` -Then on a 401 response the `WWW-Authenticate` header will look as follows: +Then on a 401 response, the `WWW-Authenticate`` header will look as follows: ```plain WWW-Authenticate: Basic realm="Enter creds to access site" @@ -116,7 +116,7 @@ WWW-Authenticate: Basic realm="Enter creds to access site" ### Redirecting -When building custom authenticators, it might be required that you have to redirect mid-auth and stop processing the current request. To achieve this you can return the following from the scriptblock of `New-PodeAuthScheme` or `Add-PodeAuth`: +When building custom authenticators, it might be required that you redirect mid-auth and stop processing the current request. To achieve this you can return the following from the scriptblock of `New-PodeAuthScheme` or `Add-PodeAuth`: ```powershell return @{ IsRedirected = $true } @@ -126,7 +126,7 @@ An example of this could be OAuth2, where the authentication needs to redirect t ## Routes/Middleware -To use an authentication on a specific route, you can use the `-Authentication` parameter on the [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute) function; this takes the Name supplied to the `-Name` parameter on [`Add-PodeAuth`](../../../Functions/Authentication/Add-PodeAuth). This will set the authentication up to run before other route middleware. +To use authentication on a specific route, you can use the `-Authentication` parameter on the [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute) function; this takes the Name supplied to the `-Name` parameter on [`Add-PodeAuth`](../../../Functions/Authentication/Add-PodeAuth). This will set the authentication up to run before other route middleware. An example of using some Basic authentication on a REST API route is as follows: @@ -138,7 +138,7 @@ Start-PodeServer { } ``` -The [`Add-PodeAuthMiddleware`](../../../Functions/Authentication/Add-PodeAuthMiddleware) function lets you setup authentication as global middleware - so it will run against all routes. +The [`Add-PodeAuthMiddleware`](../../../Functions/Authentication/Add-PodeAuthMiddleware) function lets you set up authentication as global middleware - so it will run against all routes. An example of using some Basic authentication on all REST API routes is as follows: @@ -150,7 +150,7 @@ Start-PodeServer { If any of the authentication middleware fails, then a 401 response is returned for the route. On success, it will allow the Route logic to be invoked. If Session Middleware has been configured then an authenticated session is also created for future requests, using a signed session cookie/header. -When the user makes another call using the same authenticated session and that cookie/header is present, then the authentication middleware will detect the already authenticated session and skip validation. If you're using sessions and you don't want to check the session, or store the user against a session, then use the `-Sessionless` switch on [`Add-PodeAuth`](../../../Functions/Authentication/Add-PodeAuth). +When the user makes another call using the same authenticated session and that cookie/header is present, then the authentication middleware will detect the already authenticated session and skip validation. If you're using sessions and you don't want to check the session or store the user against a session, then use the `-Sessionless` switch on [`Add-PodeAuth`](../../../Functions/Authentication/Add-PodeAuth). ## Users @@ -158,15 +158,15 @@ After successful validation, an `Auth` object will be created for use against th The `Auth` object will also contain: -| Name | Description | -| ---- | ----------- | -| User | Details about the authenticated user | -| IsAuthenticated | States if the request is for an authenticated user, can be `$true`, `$false` or `$null` | -| Store | States whether the authentication is for a session, and will be stored as a cookie | -| IsAuthorised | If using [Authorisation](../../Authorisation/Overview), this value will be `$true` or `$false` depending on whether or not the authenticated user is authorised to access the Route. If not using Authorisation this value will just be `$true` | -| Name | The name(s) of the Authentication methods which passed - useful if you're using merged Authentications and you want to know which one(s) passed | +| Name | Description | +| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| User | Details about the authenticated user | +| IsAuthenticated | States if the request is for an authenticated user, can be `$true`, `$false` or `$null` | +| Store | States whether the authentication is for a session, and will be stored as a cookie | +| IsAuthorised | If using [Authorisation](../../Authorisation/Overview), this value will be `$true` or `$false` depending on whether or not the authenticated user is authorised to access the Route. If not using Authorisation this value will just be `$true` | +| Name | The name(s) of the Authentication methods which passed - useful if you're using merged Authentications and you want to know which one(s) passed | -The following example get the user's name from the `Auth` object: +The following example gets the user's name from the `Auth` object: ```powershell Add-PodeRoute -Method Get -Path '/' -Authentication 'Login' -Login -ScriptBlock { @@ -178,13 +178,13 @@ Add-PodeRoute -Method Get -Path '/' -Authentication 'Login' -Login -ScriptBlock ## Merging -For advanced authentication scenarios, you can merge multiple authentication methods together using [`Merge-PodeAuth`](../../../Functions/Authentication/Merge-PodeAuth). This allows you to have an authentication strategy where multiple authentications are required to pass for a user to be fully authenticated, or you could have fallback authentications should the primary authentication fail. +For advanced authentication scenarios, you can merge multiple authentication methods using [`Merge-PodeAuth`](../../../Functions/Authentication/Merge-PodeAuth). This allows you to have an authentication strategy where multiple authentications are required to pass for a user to be fully authenticated, or you could have fallback authentications should the primary authentication fail. -When you merge authentication methods together, it becomes a new authentication method which you can supply to `-Authentication` on Routes. By default the merged authentications expect just one to pass, but you can state that you require all to pass via the `-Valid` parameter on [`Merge-PodeAuth`](../../../Functions/Authentication/Merge-PodeAuth). +When you merge authentication methods, they become a new authentication method that you can supply to `-Authentication` on Routes. By default the merged authentications expect just one to pass, but you can state that you require all to pass via the `-Valid` parameter on [`Merge-PodeAuth`](../../../Functions/Authentication/Merge-PodeAuth). ### All -For example, you might require an API Key and Basic authentication for a user to view a Route, in which case you would set something up as follows: +For example, you might require both an API Key and Basic authentication for a user to view a Route, in which case you would set something up as follows - in the below example we assume that the User object returned by the Basic authentication method is the User details we want to use for the Route, by specifying `-MergeDefault` on [`Merge-PodeAuth`](../../../Functions/Authentication/Merge-PodeAuth): ```powershell # setup apikey auth @@ -193,7 +193,10 @@ New-PodeAuthScheme -ApiKey -Location Header | Add-PodeAuth -Name 'ApiKey' -Sessi # here you'd check a real user storage, this is just for example if ($key -ieq 'test-api-key') { - return @{ User = @{ Name = 'Morty' } } + return @{ + User = @{ Name = 'Morty-API' } + Groups = @('Software') + } } return $null @@ -205,17 +208,80 @@ New-PodeAuthScheme -Basic | Add-PodeAuth -Name 'Basic' -Sessionless -ScriptBlock # here you'd check a real user storage, this is just for example if ($username -eq 'morty' -and $password -eq 'pickle') { - return @{ User = @{ Name = 'Morty' } } + return @{ + User = @{ Name = 'Morty-BASIC' } + Groups = @('Platform') + } + } + + return @{ Message = 'Invalid details supplied' } +} + +# merge the authentications together, and require all to pass - using the User result object of Basic +Merge-PodeAuth -Name 'MergedAuth' -Authentication 'ApiKey', 'Basic' -Valid All -MergeDefault 'Basic' + +# use the merged auth in a route +Add-PodeRoute -Method Get -Path '/users' -Authentication 'MergedAuth' -ScriptBlock { + # this would write back "Name = Morty-BASIC" + Write-PodeJsonResponse -Value @{ + Users = $WebEvent.Auth.User + } +} +``` + +The above example assumes a simple scenario of using the Basic authentication's User object, but what if we did want to use both authentication User objects and merge them into one? Well to achieve this you can supply a `-ScriptBlock`. This scriptblock will be supplied a hashtable of all the result objects, from all authentication methods used in the Valid=All merged authentication method, which you can then use to construct a single result object. The result objects themselves will contain a User and Headers hashtable - more commonly just the User. + +Using a similar example to the example above, the following will use a `-ScriptBlock` instead to merge the User objects from the API key and Basic authentication methods into one User object: + +```powershell +# setup apikey auth +New-PodeAuthScheme -ApiKey -Location Header | Add-PodeAuth -Name 'ApiKey' -Sessionless -ScriptBlock { + param($key) + + # here you'd check a real user storage, this is just for example + if ($key -ieq 'test-api-key') { + return @{ User = @{ + Name = 'Morty' + Groups = @('Software') + } } + } + + return $null +} + +# setup basic auth +New-PodeAuthScheme -Basic | Add-PodeAuth -Name 'Basic' -Sessionless -ScriptBlock { + param($username, $password) + + # here you'd check a real user storage, this is just for example + if ($username -eq 'morty' -and $password -eq 'pickle') { + return @{ User = @{ + Name = 'Morty' + Groups = @('Platform') + } } } return @{ Message = 'Invalid details supplied' } } -# merge the authentications together, and require all to pass -Merge-PodeAuth -Name 'MergedAuth' -Authentication 'ApiKey', 'Basic' -Valid All +# merge the authentications together, and require all to pass - using the User result object of Basic +Merge-PodeAuth -Name 'MergedAuth' -Authentication 'ApiKey', 'Basic' -Valid All -ScriptBlock { + param($results) + + $apiUser = $results['ApiKey'].User + $basicUser = $results['Basic'].User + + return @{ + User = @{ + User = $basicUser.Username + Groups = @($apiUser.Groups + $basicUser.Groups) | Sort-Object -Unique + } + } +} # use the merged auth in a route Add-PodeRoute -Method Get -Path '/users' -Authentication 'MergedAuth' -ScriptBlock { + # this would write back "Name = Morty" and "Groups = Platform, Software" Write-PodeJsonResponse -Value @{ Users = $WebEvent.Auth.User } @@ -256,7 +322,7 @@ Add-PodeRoute -Method Get -Path '/users' -Authentication 'MergedAuth' -ScriptBlo ### Advanced -You can also merge together other merged authentication methods. This lets you build scenarios where you require an API key, and then need either a JWT Bearer token or OAuth2 to pass. As a very brief example: +You can also merge other merged authentication methods. This lets you build scenarios where you require an API key, and then need either a JWT Bearer token or OAuth2 to pass. As a very brief example: ```powershell # setup apikey auth @@ -291,7 +357,7 @@ $scheme | Add-PodeAuth -Name 'AzureAD' -Sessionless -ScriptBlock { Merge-PodeAuth -Name 'JwtMergedAuth' -Authentication 'Bearer', 'AzureAD' -Valid One # merge the above merged auth with the apikey auth, and require both to pass -Merge-PodeAuth -Name 'ApiMergedAuth' -Authentication 'ApiKey', 'JwtMergedAuth' -Valid All +Merge-PodeAuth -Name 'ApiMergedAuth' -Authentication 'ApiKey', 'JwtMergedAuth' -Valid All -MergeDefault 'ApiKey' # use the merged auth in a route Add-PodeRoute -Method Get -Path '/users' -Authentication 'ApiMergedAuth' -ScriptBlock { @@ -303,17 +369,17 @@ Add-PodeRoute -Method Get -Path '/users' -Authentication 'ApiMergedAuth' -Script ### Users -When using a single authentication method, the authenticated user's details will be accessible at `$WebEvent.Auth.User`. However, when you're using a merged authentication method you could end up with 2 or more user objects being returned from each authentication method. +When using a single authentication method, the authenticated user's details will be accessible at `$WebEvent.Auth.User`. -Because of this, when using a merged authentication, the user object will instead be found at `$WebEvent.Auth.User[]`. For example, if you have a authentication method with name "BearerAuth", then the user's details would be at `$WebEvent.Auth.User['BearerAuth']` - not `$WebEvent.Auth.User`. +The same still applies for merged authentication methods; if you're using `Merge-PodeAuth -Valid One` then there will only be one User object to set, but if you're using `Merge-PodeAuth -Valid All` then the User objects of all authentication methods will need to be merged into one User object - this can be done by either supplying `-MergeDefault` or `-ScriptBlock` to [`Merge-PodeAuth`](../../../Functions/Authentication/Merge-PodeAuth) when `-Valid` is set to All. ([see All for more info](#all)). ### Parameters -Similar to [`Add-PodeAuth`](../../../Functions/Authentication/Add-PodeAuth) the [`Merge-PodeAuth`](../../../Functions/Authentication/Merge-PodeAuth) function also supports the `-FailureUrl`, `-SuccessUrl`, etc. parameters. When set on the merged authentication method, these fails will be used as a fallback if the initial authentication methods don't have them set. This means you can setup 2 authentication methods without Failure URLs, and then merge them together with a default one of `/login` on the merged authentication. +Similar to [`Add-PodeAuth`](../../../Functions/Authentication/Add-PodeAuth) the [`Merge-PodeAuth`](../../../Functions/Authentication/Merge-PodeAuth) function also supports the `-FailureUrl`, `-SuccessUrl`, etc. parameters. When set on the merged authentication method, they will be used as a fallback if the initial authentication methods don't have them set. This means you can set up 2 authentication methods without Failure URLs, and then merge them with a default Failure URL of `/login` on the merged authentication. ## Inbuilt Authenticators -Overtime Pode will start to support inbuilt authentication methods - such as [Windows Active Directory](../Inbuilt/WindowsAD). More information can be found in the Inbuilt section. +Over time Pode will start to support inbuilt authentication methods - such as [Windows Active Directory](../Inbuilt/WindowsAD). More information can be found in the Inbuilt section. For example, the below would use the inbuilt Windows AD authentication method: diff --git a/docs/Tutorials/Authorisation/Overview.md b/docs/Tutorials/Authorisation/Overview.md index fb59aa807..5fe85c4ec 100644 --- a/docs/Tutorials/Authorisation/Overview.md +++ b/docs/Tutorials/Authorisation/Overview.md @@ -1,18 +1,18 @@ # Overview -Authorisation can either be used in conjunction with [Authentication](../../Authentication/Overview) and [Routes](../../Routes/Overview), or on it's own for custom scenarios. +Authorisation can either be used in conjunction with [Authentication](../../Authentication/Overview) and [Routes](../../Routes/Overview), or on its own for custom scenarios. When used with Authentication, Pode can automatically authorise access to Routes based on Roles; Groups; Scopes; Users; or custom validation logic for you, using the currently authenticated User's details. When authorisation fails Pode will respond with an HTTP 403 status code. With authentication, Pode will set the following properties on the `$WebEvent.Auth` object: -| Name | Description | -| ---- | ----------- | +| Name | Description | +| ------------ | --------------------------------------------------------------------------------------------------------------------------- | | IsAuthorised | This value will be `$true` or `$false` depending on whether or not the authenticated user is authorised to access the Route | ## Create an Access Method -To validate authorisation in Pode you'll first need to create an Access scheme using [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme), and then an Access method using [`Add-PodeAccess`](../../../Functions/Authentication/Add-PodeAccess). At its most simple you'll just need a Name, Type and possibly a Match type. +To validate authorisation in Pode you'll first need to create an Access scheme using [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme), and then an Access method using [`Add-PodeAccess`](../../../Functions/Access/Add-PodeAccess). At its most simple you'll just need a Name, Type, and possibly a Match type. For example, you can create a simple Access method for any of the inbuilt types as follows: @@ -25,15 +25,15 @@ New-PodeAccessScheme -Type User | Add-PodeAccess -Name 'UserExample' ### Match Type -Pode supports 3 inbuilt "Match" types for validating access to resources: One, All and None. The default Match type is One; each of them are applied as follows: +Pode supports 3 inbuilt "Match" types for validating access to resources: One, All, and None. The default Match type is One; each of them is applied as follows: -| Type | Description | -| ---- | ----------- | -| One | If the Source's (ie: User's) access values contain at least one of the Destination's (ie: Route's) access values, then authorisation is granted. | -| All | The Source's access values must contain all of the Destination's access values for authorisation to be granted. | -| None | The Source's access values must contain none of the Destination's access values for authorisation to be granted. | +| Type | Description | +| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| One | If the Source's (ie: User's) access values contain at least one of the Destination's (ie: Route's) access values, then authorisation is granted. | +| All | The Source's access values must contain all of the Destination's access values for authorisation to be granted. | +| None | The Source's access values must contain none of the Destination's access values for authorisation to be granted. | -For example, to setup an Access method where a User must be in every Group that a Route specifies: +For example, to set an Access method where a User must be in every Group that a Route specifies: ```powershell New-PodeAccessScheme -Type Group | Add-PodeAccess -Name 'GroupExample' -Match All @@ -41,20 +41,20 @@ New-PodeAccessScheme -Type Group | Add-PodeAccess -Name 'GroupExample' -Match Al ### User Access Lookup -When using Access methods with Authentication and Routes, Pode will lookup the User's "access values" from the `$WebEvent.Auth.User` object. The property within this object that Pode uses depends on the `-Type` supplied to [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme): +When using Access methods with Authentication and Routes, Pode will look up the User's "access values" from the `$WebEvent.Auth.User` object. The property within this object that Pode uses depends on the `-Type` supplied to [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme): -| Type | Property | -| ---- | -------- | -| Role | Roles | -| Group | Groups | -| Scope | Scopes | -| User | Username | +| Type | Property | +| ------ | ----------------------------------------------------------------------------------------------------------------------------- | +| Role | Roles | +| Group | Groups | +| Scope | Scopes | +| User | Username | | Custom | n/a - you must supply a `-Path` or `-ScriptBlock` to [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme) | -You can override this default lookup in one of two ways, by either supplying a custom property `-Path` or a `-ScriptBlock` for more a more advanced lookup (ie: external sources). +You can override this default lookup in one of two ways, by either supplying a custom property `-Path` or a `-ScriptBlock` for a more advanced lookup (ie: external sources). !!! note - If you're using Access methods in a more adhoc manner via [`Test-PodeAccess`](../../../Functions/Authentication/Test-PodeAccess), the `-Path` property does nothing. However, if you don't supply a `-Source` to this function then the `-ScriptBlock` will be invoked. + If you're using Access methods in a more adhoc manner via [`Test-PodeAccess`](../../../Functions/Access/Test-PodeAccess), the `-Path` property does nothing. However, if you don't supply a `-Source` to this function then the `-ScriptBlock` will be invoked. #### Lookup Path @@ -79,10 +79,10 @@ And Pode will retrieve the appropriate data for you. #### Lookup ScriptBlock -If the source access values you require are not stored in the `$WebEvent.Auth.User` object but else where (ie: external source), then you can supply a `-ScriptBlock` on [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme). When Pode attempts to retrieve access values for the User, or another Source, this scriptblock will be invoked. +If the source access values you require are not stored in the `$WebEvent.Auth.User` object but elsewhere (ie: external source), then you can supply a `-ScriptBlock` on [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme). When Pode attempts to retrieve access values for the User, or another Source, this scriptblock will be invoked. !!! note - When using this scriptblock with Authentication the currently authenticated User will be supplied as the first parameter, followed by the `-ArgumentList` values. When using the Access methods in a more adhoc manner via [`Test-PodeAccess`](../../../Functions/Authentication/Test-PodeAccess), just the `-ArgumentList` values are supplied. + When using this scriptblock with Authentication the currently authenticated User will be supplied as the first parameter, followed by the `-ArgumentList` values. When using the Access methods in a more adhoc manner via [`Test-PodeAccess`](../../../Functions/Access/Test-PodeAccess), just the `-ArgumentList` values are supplied. For example, if the Role values you need to retrieve are stored in some SQL database: @@ -112,7 +112,7 @@ By default Pode will perform basic array contains checks, to see if the Source/D For example, if the User has just the Role value `Developer`, and Route has `-Role` values of `Developer` and `QA` supplied, and the `-Match` type is left as `One`, then "if the User Role is contained within the Routes Roles" access is authorised. -However, if you require a more custom/advanced validation logic to be applied, you can supply a `-ScriptBlock` to [`Add-PodeAccess`](../../../Functions/Authentication/Add-PodeAccess). The scriptblock will be supplied with the "Source" access values as the first parameter; the "Destination" access values as the second parameter; and then followed by the `-ArgumentList` values. This scriptblock should return a boolean value: true if authorisation granted, or false otherwise. +However, if you require a more custom/advanced validation logic to be applied, you can supply a `-ScriptBlock` to [`Add-PodeAccess`](../../../Functions/Access/Add-PodeAccess). The scriptblock will be supplied with the "Source" access values as the first parameter; the "Destination" access values as the second parameter; and then followed by the `-ArgumentList` values. This scriptblock should return a boolean value: true if authorisation is granted, or false otherwise. !!! note Supplying a `-ScriptBlock` will override the `-Match` type supplied, as this scriptblock will be used for validation instead of Pode's inbuilt Match logic. @@ -139,11 +139,11 @@ New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'ScopeExample' -ScriptBl ## Using with Routes -The Access methods will most commonly be used in conjunction with [Authentication](../../Authentication/Overview) and [Routes](../../Routes/Overview). When used together, Pode will automatically validate Route Authorisation for after the Authentication flow. If authorisation fails, an HTTP 403 status code will be returned. +The Access methods will most commonly be used in conjunction with [Authentication](../../Authentication/Overview) and [Routes](../../Routes/Overview). When used together, Pode will automatically validate Route Authorisation after the Authentication flow. If authorisation fails, an HTTP 403 status code will be returned. After creating an Access method as outlined above, you can supply the Access method Name to [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute), and other Route functions, using the `-Access` parameter. -On [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute) and [`Add-PodeRouteGroup`](../../../Functions/Routes/Add-PodeRouteGroup) there are also the following parameters: `-Role`, `-Group`, `-Scope`, and `-User`. You can supply one ore more string values to these parameters, depending on which Access method type you're using. +On [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute) and [`Add-PodeRouteGroup`](../../../Functions/Routes/Add-PodeRouteGroup) there are also the following parameters: `-Role`, `-Group`, `-Scope`, and `-User`. You can supply one or more string values to these parameters, depending on which Access method type you're using. For example, to verify access to a Route to authorise only Developer role users: @@ -198,11 +198,11 @@ Invoke-RestMethod -Uri http://localhost:8080/route2 -Method Get -Headers @{ Auth ## Merging -Similar to Authentication methods, you can also merge Access methods using [`Merge-PodeAccess`](../../../Functions/Authentication/Merge-PodeAccess). This allows you to have an access strategy where multiple authorisations are required to pass for a user to be fully authorised, or just one of several possible methods. +Similar to Authentication methods, you can also merge Access methods using [`Merge-PodeAccess`](../../../Functions/Access/Merge-PodeAccess). This allows you to have an access strategy where multiple authorisations are required to pass for a user to be fully authorised, or just one of several possible methods. -When you merge access methods together, it becomes a new access method which you can supply to `-Access` on [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute). By default the merged access method expects just one to pass, but you can state that you require all to pass via the `-Valid` parameter on [`Merge-PodeAccess`](../../../Functions/Authentication/Merge-PodeAccess). +When you merge access methods, it becomes a new access method that you can supply to `-Access` on [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute). By default the merged access method expects just one to pass, but you can state that you require all to pass via the `-Valid` parameter on [`Merge-PodeAccess`](../../../Functions/Access/Merge-PodeAccess). -Using the same example above, we could add Group authorisation to this as well so the Developers have to be in a Software Group, and the Admins in a Operations Group: +Using the same example above, we could add Group authorisation to this as well so the Developers have to be in a Software Group, and the Admins in an Operations Group: ```powershell Start-PodeServer { @@ -248,7 +248,7 @@ Start-PodeServer { ## Custom Access -Pode has inbuilt support for Roles, Groups, Scopes, and Users authorisation on Routes. However, if you need to setup a more Custom authorisation policy on Routes you can create a custom Access scheme by supplying `-Custom` to [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme), and add custom access values to a Route using [`Add-PodeAccessCustom`](../../../Functions/Authentication/Add-PodeAccessCustom). +Pode has inbuilt support for Roles, Groups, Scopes, and Users authorisation on Routes. However, if you need to set up a more Custom authorisation policy on Routes you can create a custom Access scheme by supplying `-Custom` to [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme), and adding custom access values to a Route using [`Add-PodeAccessCustom`](../../../Functions/Access/Add-PodeAccessCustom). Custom access values for a User won't be automatically loaded from the authenticated User object, and a `-Path` or `-ScriptBlock` on [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme) will be required. @@ -303,7 +303,7 @@ Start-PodeServer { ## Using Adhoc -It is possible to invoke the Access method validation in an adhoc manner, without (or while) using Authentication, using [`Test-PodeAccess`](../../../Functions/Authentication/Test-PodeAccess). +It is possible to invoke the Access method validation in an adhoc manner, without (or while) using Authentication, using [`Test-PodeAccess`](../../../Functions/Access/Test-PodeAccess). When using the Access methods outside of Authentication/Routes, the `-Type` doesn't really have any bearing. @@ -332,4 +332,4 @@ Start-PodeServer { } ``` -The `-ArgumentList`, on [`Test-PodeAccess`](../../../Functions/Authentication/Test-PodeAccess), will supply values as the first set of parameters to the `-ScriptBlock` defined on [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme). +The `-ArgumentList`, on [`Test-PodeAccess`](../../../Functions/Access/Test-PodeAccess), will supply values as the first set of parameters to the `-ScriptBlock` defined on [`New-PodeAccessScheme`](../../../Functions/Access/New-PodeAccessScheme). diff --git a/docs/Tutorials/Caching.md b/docs/Tutorials/Caching.md new file mode 100644 index 000000000..3c5904b30 --- /dev/null +++ b/docs/Tutorials/Caching.md @@ -0,0 +1,153 @@ +# Caching + +Pode has an inbuilt in-memory caching feature, allowing you to cache values for a duration of time to speed up slower queries. You can also set up custom caching storage solutions - such as Redis, and others. + +The default TTL for cached items is 3,600 seconds (1 hour), and this value can be customised either globally or per item. There is also a `$cache:` scoped variable available for use. + +## Caching Items + +To add an item to the cache use [`Set-PodeCache`](../../Functions/Caching/Set-PodeCache), and then to retrieve the value from the cache use [`Get-PodeCache`](../../Functions/Caching/Get-PodeCache). If the item has expired when `Get-PodeCache` is called then `$null` will be returned. + +For example, the following would retrieve the current CPU on Windows machines and cache it for 60 seconds: + +```powershell +Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + # check cache + $cpu = Get-PodeCache -Key 'cpu' + if ($null -ne $cpu) { + Write-PodeJsonResponse -Value @{ CPU = $cpu } + return + } + + # get cpu, and cache for 60s + $cpu = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue + $cpu | Set-PodeCache -Key 'cpu' -Ttl 60 + + Write-PodeJsonResponse -Value @{ CPU = $cpu } +} +``` + +Alternatively, you could use the `$cache:` scoped variable instead. However, using this there is no way to pass the TTL when setting new cached items, so all items cached in this manner will use the default TTL (1 hour, unless changed). Changing the default TTL is discussed [below](#default-ttl). + +```powershell +Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + # check cache + $cpu = $cache:cpu + if ($null -ne $cpu) { + Write-PodeJsonResponse -Value @{ CPU = $cpu } + return + } + + # get cpu, and cache for 1hr + $cache:cpu = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue + Write-PodeJsonResponse -Value @{ CPU = $cache:cpu } +} +``` + +You can test if an item exists in the cache, and isn't expired, using [`Test-PodeCache`](../../Functions/Caching/Test-PodeCache) - this is useful to call if the cached value for a key happens to genuinely be `$null`, so you can see if the key does exist. + +If you need to invalidate a cached value you can use [`Remove-PodeCache`](../../Functions/Caching/Remove-PodeCache), or if you need to invalidate the whole cache you can use [`Clear-PodeCache`](../../Functions/Caching/Clear-PodeCache). + +### Default TTL + +The default TTL for cached items, when the server starts, is 1 hour. This can be changed by using [`Set-PodeCacheDefaultTtl`](../../Functions/Caching/Set-PodeCacheDefaultTtl). The following updates the default TTL to 60 seconds: + +```powershell +Start-PodeServer { + Set-PodeCacheDefaultTtl -Value 60 +} +``` + +All new cached items will use this TTL by default unless the one is explicitly specified on [`Set-PodeCache`](../../Functions/Caching/Set-PodeCache) using the `-Ttl` parameter. + +## Custom Storage + +The inbuilt storage used by Pode is a simple in-memory synchronized hashtable, if you're running multiple instances of your Pode server then you'll have multiple caches as well - potentially with different values for the keys. + +You can set up custom storage devices for your cached values using [`Add-PodeCacheStorage`](../../Functions/Caching/Add-PodeCacheStorage) - you can also set up multiple different storages, and specify where certain items should be cached using the `-Storage` parameter on `Get-PodeCache` and `Set-PodeCache`. + +When setting up a new cache storage, you are required to specific a series of scriptblocks for: + +* Setting a cached item (create/update). (`-Set`) +* Getting a cached item's value. (`-Get`) +* Testing if a cached item exists. (`-Test`) +* Removing a cached item. (`-Remove`) +* Clearing a cache of all items. (`-Clear`) + +!!! note + Not all providers will support all options, such as clearing the whole cache. When this is the case simply pass an empty scriptblock to the parameter. + +The `-Test` and `-Remove` scriptblocks will each be supplied the key for the cached item; the `-Test` scriptblock should return a boolean value. The `-Set` scriptblock will be supplied with the key, value, and TTL for the cached item. The `-Get` scriptblock will be supplied with the key of the item to retrieve, but also a boolean "metadata" flag - if this metadata flag is false, just return the item's value, but if it's true return a hashtable of the value and other metadata properties for expiry and ttl. + +For example, say you want to use Redis to store your cached items, then you would have a similar setup to the one below. + +```powershell +$params = @{ + Set = { + param($key, $value, $ttl) + $null = redis-cli -h localhost -p 6379 SET $key "$($value)" EX $ttl + } + Get = { + param($key, $metadata) + $result = redis-cli -h localhost -p 6379 GET $key + $result = [System.Management.Automation.Internal.StringDecorated]::new($result).ToString('PlainText') + if ([string]::IsNullOrEmpty($result) -or ($result -ieq '(nil)')) { + return $null + } + + if ($metadata) { + $ttl = redis-cli -h localhost -p 6379 TTL $key + $ttl = [int]([System.Management.Automation.Internal.StringDecorated]::new($result).ToString('PlainText')) + + $result = @{ + Value = $result + Ttl = $ttl + Expiry = [datetime]::UtcNow.AddSeconds($ttl) + } + } + + return $result + } + Test = { + param($key) + $result = redis-cli -h localhost -p 6379 EXISTS $key + return ([System.Management.Automation.Internal.StringDecorated]::new($result).ToString('PlainText') -eq '1') + } + Remove = { + param($key) + $null = redis-cli -h localhost -p 6379 EXPIRE $key -1 + } + Clear = {} +} + +Add-PodeCacheStorage -Name 'Redis' @params +``` + +Then to use the storage, pass the name to the `-Storage` parameter: + +```powershell +Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + # check cache + $cpu = Get-PodeCache -Key 'cpu' -Storage 'Redis' + if ($null -ne $cpu) { + Write-PodeJsonResponse -Value @{ CPU = $cpu } + return + } + + # get cpu, and cache for 60s + $cpu = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue + $cpu | Set-PodeCache -Key 'cpu' -Ttl 60 -Storage 'Redis' + + Write-PodeJsonResponse -Value @{ CPU = $cpu } +} +``` + +### Default Storage + +Similar to the TTL, you can change the default cache storage from Pode's in-memory one to a custom-added one. This default storage will be used for all cached items when `-Storage` is supplied, and when using `$cache:` as well. + +```powershell +Start-PodeServer { + Set-PodeCacheDefaultStorage -Name 'Redis' +} +``` diff --git a/docs/Tutorials/Configuration.md b/docs/Tutorials/Configuration.md index 7e91cfa0b..89c59d724 100644 --- a/docs/Tutorials/Configuration.md +++ b/docs/Tutorials/Configuration.md @@ -68,17 +68,19 @@ A "path" like `Server.Ssl.Protocols` looks like the below in the file: } ``` -| Path | Description | Docs | -| ---- | ----------- | ---- | -| Server.Ssl.Protocols | Indicates the SSL Protocols that should be used | [link](../Certificates) | -| Server.Request | Defines request timeout and maximum body size | [link](../RequestLimits) | -| Server.AutoImport | Defines the AutoImport scoping rules for Modules, SnapIns and Functions | [link](../Scoping) | -| Server.Logging | Defines extra configuration for Logging, like masking sensitive data | [link](../Logging/Overview) | -| Server.Root | Overrides root path of the server | [link](../Misc/ServerRoot) | -| Server.Restart | Defines configuration for automatically restarting the server | [link](../Restarting/Types/AutoRestarting) | -| Server.FileMonitor | Defines configuration for restarting the server based on file updates | [link](../Restarting/Types/FileMonitoring) | -| Web.TransferEncoding | Sets the Request TransferEncoding | [link](../Compression/Requests) | -| Web.Compression | Sets any compression to use on the Response | [link](../Compression/Responses) | -| Web.ContentType | Define expected Content Types for certain Routes | [link](../Routes/Utilities/ContentTypes) | -| Web.ErrorPages | Defines configuration for custom error pages | [link](../Routes/Utilities/ErrorPages) | -| Web.Static | Defines configuration for static content, such as caching | [link](../Routes/Utilities/StaticContent) | +| Path | Description | Docs | +| -------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------ | +| Server.Ssl.Protocols | Indicates the SSL Protocols that should be used | [link](../Certificates) | +| Server.Request | Defines request timeout and maximum body size | [link](../RequestLimits) | +| Server.AutoImport | Defines the AutoImport scoping rules for Modules, SnapIns and Functions | [link](../Scoping) | +| Server.Logging | Defines extra configuration for Logging, like masking sensitive data | [link](../Logging/Overview) | +| Server.Root | Overrides root path of the server | [link](../Misc/ServerRoot) | +| Server.Restart | Defines configuration for automatically restarting the server | [link](../Restarting/Types/AutoRestarting) | +| Server.FileMonitor | Defines configuration for restarting the server based on file updates | [link](../Restarting/Types/FileMonitoring) | +| Web.OpenApi.DefaultDefinitionTag | Define the primary tag name for OpenAPI ( 'default' is the default) | [link](../OpenAPI/OpenAPI) | +| Web.Static.ValidateLast | Changes the way routes are processed. | [link](../Routes/Utilities/StaticContent) | +| Web.TransferEncoding | Sets the Request TransferEncoding | [link](../Compression/Requests) | +| Web.Compression | Sets any compression to use on the Response | [link](../Compression/Responses) | +| Web.ContentType | Define expected Content Types for certain Routes | [link](../Routes/Utilities/ContentTypes) | +| Web.ErrorPages | Defines configuration for custom error pages | [link](../Routes/Utilities/ErrorPages) | +| Web.Static | Defines configuration for static content, such as caching | [link](../Routes/Utilities/StaticContent) | diff --git a/docs/Tutorials/Endpoints/Basics.md b/docs/Tutorials/Endpoints/Basics.md index 9bd89a81d..f4dbd93f8 100644 --- a/docs/Tutorials/Endpoints/Basics.md +++ b/docs/Tutorials/Endpoints/Basics.md @@ -1,10 +1,13 @@ # Basics -Endpoints in Pode are used to bind your server to specific IPs, Hostnames and ports, over specific protocols (such as HTTP or HTTPS). Endpoints can have unique names, so you can bind Routes to certain endpoints only. +Endpoints in Pode are used to bind your server to specific IPs, Hostnames, and ports over specific protocols (such as HTTP or HTTPS). Endpoints can have unique names, so you can bind Routes to certain endpoints only. + +!!! tip + Endpoints support both IPv4 and IPv6 addresses. ## Usage -To add new endpoints to your server, you can use [`Add-PodeEndpoint`](../../../Functions/Core/Add-PodeEndpoint). A quick and simple example is the following, which will bind your server to `http://localhost:8080`: +To add new endpoints to your server you use [`Add-PodeEndpoint`](../../../Functions/Core/Add-PodeEndpoint). A quick and simple example is the following, which will bind your server to `http://localhost:8080`: ```powershell Start-PodeServer { @@ -12,10 +15,41 @@ Start-PodeServer { } ``` -The `-Address` can be local or private IP address. The `-Port` is any valid port number, and the `-Protocol` defines which protocol the endpoint will use: HTTP, HTTPS, SMTP, TCP, WS and WSS. +The `-Address` can be a local or a private IP address. The `-Port` is any valid port number, and the `-Protocol` defines which protocol the endpoint will use: HTTP, HTTPS, SMTP, TCP, WS, or WSS. You can also supply an optional unique `-Name` to your endpoint. This name will allow you to bind routes to certain endpoints; so if you have endpoint A and B, and you bind some route to endpoint A, then it won't be accessible over endpoint B. +```powershell +Add-PodeEndpoint -Address localhost -Port 8080 -Protocol Http -Name EndpointA +Add-PodeEndpoint -Address localhost -Port 8080 -Protocol Http -Name EndpointB + +Add-PodeRoute -Method Get -Path '/page-a' -EndpointName EndpointA -ScriptBlock { + # logic +} + +Add-PodeRoute -Method Get -Path '/page-b' -EndpointName EndpointB -ScriptBlock { + # logic +} +``` + +## Dual Mode + +When you create an Endpoint in Pode, it will listen on either just the IPv4 or IPv6 address that you supplied - for localhost, this will be `127.0.0.1`, and for "*", this will be `0.0.0.0`, unless the IPv6 equivalents of `::1` or `::` were directly supplied. + +This means if you have the following endpoint to listen on "everything", then it will only really be everything for just IPv4: + +```powershell +Add-PodeEndpoint -Address * -Port 8080 -Protocol Http +``` + +However, you can pass the `-DualMode` switch on [`Add-PodeEndpoint`](../../../Functions/Core/Add-PodeEndpoint) and this will tell Pode to listen on both IPv4 and IPv6 instead: + +```powershell +Add-PodeEndpoint -Address * -Port 8080 -Protocol Http -DualMode +``` + +This will work for any IPv4 address, including localhost, if the underlying OS supports IPv6. For IPv6 addresses, only those that can be converted back to an equivalent IPv4 address will work - it will still listen on the supplied IPv6 address, there just won't be an IPv4 that Pode could also listen on. + ## Hostnames You can specify a `-Hostname` for an endpoint, in doing so you can only access routes via the specified hostname. Using a hostname will allow you to have multiple endpoints all using the same IP/Port, but with different hostnames. @@ -32,7 +66,7 @@ To bind a hostname to a specific IP you can use `-Address`: Add-PodeEndpoint -Address 127.0.0.2 -Hostname example.pode.com -Port 8080 -Protocol Http ``` -or, lookup the hostnames IP from host file or DNS: +or, lookup the hostname's IP from the host file or DNS: ```powershell Add-PodeEndpoint -Hostname example.pode.com -Port 8080 -Protocol Http -LookupHostname @@ -49,16 +83,16 @@ Add-PodeEndpoint -Address 127.0.0.3 -Hostname two.pode.com -Port 8080 -Protocol If you add an HTTPS or WSS endpoint, then you'll be required to also supply certificate details. To configure a certificate you can use one of the following parameters: -| Name | Description | -| ---- | ----------- | -| Certificate | The path to a `.pfx` or `.cer` certificate | -| CertificatePassword | The password for the above `.pfx` certificate | -| CertificateThumbprint | The thumbprint of a certificate to find (Windows only) | -| CertificateName | The subject name of a certificate to find (Windows only) | -| CertificateStoreName | The name of the certificate store (Default: My) (Windows only) | -| CertificateStoreLocation | The location of the certificate store (Default: CurrentUser) (Windows only) | -| X509Certificate | A raw X509Certificate object | -| SelfSigned | If supplied, Pode will automatically generate a self-signed certificate as an X509Certificate object | +| Name | Description | +| ------------------------ | ---------------------------------------------------------------------------------------------------- | +| Certificate | The path to a `.pfx` or `.cer` certificate | +| CertificatePassword | The password for the above `.pfx` certificate | +| CertificateThumbprint | The thumbprint of a certificate to find (Windows only) | +| CertificateName | The subject name of a certificate to find (Windows only) | +| CertificateStoreName | The name of the certificate store (Default: My) (Windows only) | +| CertificateStoreLocation | The location of the certificate store (Default: CurrentUser) (Windows only) | +| X509Certificate | A raw X509Certificate object | +| SelfSigned | If supplied, Pode will automatically generate a self-signed certificate as an X509Certificate object | The below example will create an endpoint using a `.pfx` certificate: @@ -66,7 +100,7 @@ The below example will create an endpoint using a `.pfx` certificate: Add-PodeEndpoint -Address * -Port 8443 -Protocol Https -Certificate './certs/example.pfx' -CertificatePassword 'hunter2' ``` -Whereas the following will instead create an X509Certificate, and pass that to the endpoint instead: +However, the following will instead create an X509Certificate, and pass that to the endpoint instead: ```powershell $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new('./certs/example.cer') @@ -81,10 +115,10 @@ Add-PodeEndpoint -Address * -Port 8443 -Protocol Https -SelfSigned ### SSL Protocols -By default Pode will use the SSL3 or TLS12 protocols - or just TLS12 if on MacOS. You can override this default in one of two ways: +By default, Pode will use the SSL3 or TLS12 protocols - or just TLS12 if on MacOS. You can override this default in one of two ways: 1. Update the global default in Pode's configuration file, as [described here](../../Certificates#ssl-protocols). -2. Specify specific SSL Protocols to use per Endpoints using the `-SslProtocol` parameter on [`Add-PodeEndpoint`](../../../Functions/Core/Add-PodeEndpoint). +2. Specify specific SSL Protocols to use per Endpoint using the `-SslProtocol` parameter on [`Add-PodeEndpoint`](../../../Functions/Core/Add-PodeEndpoint). ## Endpoint Names @@ -124,19 +158,19 @@ Get-PodeEndpoint -Name Admin, User The following is the structure of the Endpoint object internally, as well as the object that is returned from [`Get-PodeEndpoint`](../../../Functions/Core/Get-PodeEndpoint): -| Name | Type | Description | -| ---- | ---- | ----------- | -| Name | string | The name of the Endpoint, if a name was supplied | -| Description | string | A description of the Endpoint, usually used for OpenAPI | -| Address | IPAddress | The IP address that will be used for the Endpoint | -| RawAddress | string | The address/host and port of the Endpoint | -| Port | int | The port the Endpoint will use | -| IsIPAddress | bool | Whether or not the listener will bind using Hostname or IP address | -| Hostname | string | The hostname of the Endpoint | -| FriendlyName | string | A user friendly hostname to use when generating internal URLs | -| Url | string | The full base URL of the Endpoint | -| Ssl.Enabled | bool | Whether or not this Endpoint uses SSL | +| Name | Type | Description | +| ------------- | ------------ | ------------------------------------------------------------------------------- | +| Name | string | The name of the Endpoint, if a name was supplied | +| Description | string | A description of the Endpoint, usually used for OpenAPI | +| Address | IPAddress | The IP address that will be used for the Endpoint | +| RawAddress | string | The address/host and port of the Endpoint | +| Port | int | The port the Endpoint will use | +| IsIPAddress | bool | Whether or not the listener will bind using Hostname or IP address | +| Hostname | string | The hostname of the Endpoint | +| FriendlyName | string | A user friendly hostname to use when generating internal URLs | +| Url | string | The full base URL of the Endpoint | +| Ssl.Enabled | bool | Whether or not this Endpoint uses SSL | | Ssl.Protocols | SslProtocols | An aggregated integer which specifies the SSL protocols this endpoints supports | -| Protocol | string | The protocol of the Endpoint. Such as: HTTP, HTTPS, WS, etc. | -| Type | string | The type of the Endpoint. Such as: HTTP, WS, SMTP, TCP | -| Certificate | hashtable | Details about the certificate that will be used for SSL Endpoints | +| Protocol | string | The protocol of the Endpoint. Such as: HTTP, HTTPS, WS, etc. | +| Type | string | The type of the Endpoint. Such as: HTTP, WS, SMTP, TCP | +| Certificate | hashtable | Details about the certificate that will be used for SSL Endpoints | diff --git a/docs/Tutorials/Middleware/Overview.md b/docs/Tutorials/Middleware/Overview.md index 555a59177..8a75a600f 100644 --- a/docs/Tutorials/Middleware/Overview.md +++ b/docs/Tutorials/Middleware/Overview.md @@ -2,13 +2,13 @@ Middleware in Pode allows you to observe and edit the request/response objects for a current [web event](../../WebEvent) - you can alter the response, add custom objects to the [web event](../../WebEvent) for later use, or terminate the response without processing the main Route logic. -Middleware is supported in both a global scope, using [`Add-PodeMiddleware`](../../../Functions/Middleware/Add-PodeMiddleware), as well as at the Route level using the `-Middleware` parameter on [`Add-PodeMiddleware`](../../../Functions/Middleware/Add-PodeMiddleware), +Middleware is supported in both a global scope, using [`Add-PodeMiddleware`](../../../Functions/Middleware/Add-PodeMiddleware), as well as at the Route level using the `-Middleware` parameter on [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute). Pode itself has some inbuilt Middleware, which is overridable, so you can use your own custom middleware. For example, Pode has inbuilt Middleware for rate limiting, but you can override this with [`Add-PodeMiddleware`](../../../Functions/Middleware/Add-PodeMiddleware) and the Name `__pode_mw_rate_limit__` (more on the [Access Rules](../Types/AccessRules) and [Rate Limiting](../Types/RateLimiting) page). ## Global Middleware -To setup and use middleware in Pode you use the Middleware function: [`Add-PodeMiddleware`](../../../Functions/Middleware/Add-PodeMiddleware). This will setup global middleware that will run, in the order created, on every request prior to any Route logic being invoked. +To set up and use middleware in Pode you use the Middleware function: [`Add-PodeMiddleware`](../../../Functions/Middleware/Add-PodeMiddleware). This will set up global middleware that will run, in the order created, on every request before any Route logic is invoked. The function takes a ScriptBlock, which has access to the current [web event](../../WebEvent) variable: `$WebEvent`. The event object contains the current `Request` and `Response` objects - you can also add more custom objects to it, as the event is just a `hashtable`. @@ -37,7 +37,7 @@ Start-PodeServer { } ``` -Where as the following example is Middleware that will only be run on requests against the `/api` route. Here, we're just going to do something simple, which is to write a message to the console for all `/api` requests: +However, the following example is Middleware that will only be run on requests against the `/api` route. Here, we're just going to do something simple, which is to write a message to the console for all `/api` requests: ```powershell Start-PodeServer { @@ -50,7 +50,7 @@ Start-PodeServer { ## Route Middleware -Custom middleware on a Route is basically the same as above however, you don't use the main Middleware functions and instead insert it straight on the Route. To do this, you can use the `-Middleware` parameter on the [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute) function. +Custom middleware on a Route is the same as above however, you don't use the main Middleware functions and instead insert it straight on the Route. To do this, you can use the `-Middleware` parameter on the [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute) function. The middleware on a route can either be a single `scriptblock` or an an array of `scriptblocks`. Middleware defined on routes will be run before the route itself, but after any global middleware that may have been configured. @@ -86,23 +86,23 @@ Start-PodeServer { Although you can define your own custom middleware, Pode does have some inbuilt middleware with a predefined run order. This order of running is as follows: -| Order | Middleware | Description | -| ----- | ---------- | ----------- | -| 1 | **Security Headers** | Add any defined security headers onto the response | -| 2 | **Access Rules** | Allowing/Denying IP addresses (if access rules have been defined) | -| 3 | **Rate Limiting** | Limiting access to IP addresses (if rate limiting rules have been defined) | -| 4 | **Static Content** | Static Content, such as images/css/js/html, in the `/public` directory | -| 5 | **Body Parsing** | Parsing request payload as JSON, XML, or other types | -| 6 | **Query String** | Getting any query string parameters currently on the request URL | -| 7 | **Cookie Parsing** | Parse the cookies from the request's header (this only applies to serverless) | -| 8 | **Custom Middleware** | Runs any defined user defined global Middleware in the order it was created | -| 9 | **Route Middleware** | Runs any Route level Middleware for the current Route being processed | -| 10 | **Route** | Then, the route itself is processed | -| 11 | **Endware** | Finally, any Endware configured is run | +| Order | Middleware | Description | +| ----- | --------------------- | ----------------------------------------------------------------------------- | +| 1 | **Security Headers** | Add any defined security headers onto the response | +| 2 | **Access Rules** | Allowing/Denying IP addresses (if access rules have been defined) | +| 3 | **Rate Limiting** | Limiting access to IP addresses (if rate limiting rules have been defined) | +| 4 | **Static Content** | Static Content, such as images/css/js/html, in the `/public` directory | +| 5 | **Body Parsing** | Parsing request payload as JSON, XML, or other types | +| 6 | **Query String** | Getting any query string parameters currently on the request URL | +| 7 | **Cookie Parsing** | Parse the cookies from the request's header (this only applies to serverless) | +| 8 | **Custom Middleware** | Runs any defined user defined global Middleware in the order it was created | +| 9 | **Route Middleware** | Runs any Route level Middleware for the current Route being processed | +| 10 | **Route** | Then, the route itself is processed | +| 11 | **Endware** | Finally, any Endware configured is run | ## Overriding Inbuilt -Pode has inbuilt Middleware as defined in the order of running above. Sometimes you probably don't want to use the inbuilt rate limiting, and use a custom rate limiting library that utilises REDIS instead. Each of the inbuilt Middleware have a defined name, that you can pass to the [`Add-PodeMiddleware`](../../../Functions/Middleware/Add-PodeMiddleware) function via the `-Name` parameter: +Pode has inbuilt Middleware as defined in the order of running above. Sometimes you probably don't want to use the inbuilt rate-limiting, and use a custom rate-limiting library that utilises REDIS instead. Each of the inbuilt Middleware has a defined name, that you can pass to the [`Add-PodeMiddleware`](../../../Functions/Middleware/Add-PodeMiddleware) function via the `-Name` parameter: * Access Control - `__pode_mw_access__` * Rate Limiting - `__pode_mw_rate_limit__` @@ -112,7 +112,7 @@ Pode has inbuilt Middleware as defined in the order of running above. Sometimes * Cookie Parsing - `__pode_mw_cookie_parsing__` * Security Headers - `__pode_mw_security__` -The following example uses rate limiting, and defines Middleware that will override the inbuilt rate limiting logic: +The following example uses rate limiting, and defines Middleware that will override the inbuilt rate-limiting logic: ```powershell Start-PodeServer { diff --git a/docs/Tutorials/Middleware/Types/Sessions.md b/docs/Tutorials/Middleware/Types/Sessions.md index fc1c04e5d..ba622c0e2 100644 --- a/docs/Tutorials/Middleware/Types/Sessions.md +++ b/docs/Tutorials/Middleware/Types/Sessions.md @@ -2,23 +2,23 @@ Session Middleware is supported on web requests and responses in the form of signed a cookie/header and server-side data storage. When configured the middleware will check for a session cookie/header (usually called `pode.sid`) on the request; if a cookie/header is not found on the request, or the session is not in storage, then a new session is created and attached to the response. If there is a session, then the appropriate data for that session is loaded from storage. -The duration of the session cookie/header can be specified, as well as whether to extend the duration each time on each request. A secret-key to sign sessions can be supplied (default is a random GUID), as well as the ability to specify custom data stores - the default is in-memory, but custom storage could be anything like Redis/MongoDB/etc. +The duration of the session cookie/header can be specified, as well as whether to extend the duration each time on each request. A secret key to sign sessions can be supplied (default is a random GUID), as well as the ability to specify custom data stores - the default is in-memory, but custom storage could be anything like Redis/MongoDB/etc. !!! note Using sessions via headers is best used with REST APIs and the CLI. It's not advised to use them for normal websites, as browsers don't send back response headers in new requests - unlike cookies. !!! tip - Sessions are typically used in conjunction with Authentication, but can you use them standalone as well! + Sessions are typically used in conjunction with Authentication, but you can use them standalone as well! ## Usage -To initialise sessions in Pode you'll need to call [`Enable-PodeSessionMiddleware`](../../../../Functions/Sessions/Enable-PodeSessionMiddleware). This function will configure and automatically create the Middleware needed to enable sessions. By default sessions are set to use cookies, but support is also available for headers. +To initialise sessions in Pode you'll need to call [`Enable-PodeSessionMiddleware`](../../../../Functions/Sessions/Enable-PodeSessionMiddleware). This function will configure and automatically create the Middleware needed to enable sessions. By default, sessions are set to use cookies, but support is also available for headers. Sessions are automatically signed using a random GUID. For Pode running on a single server using the default in-memory storage this is OK, however if you're running Pode on multiple servers, or if you're defining a custom storage then a `-Secret` is required - this is so that sessions from different servers, or after a server restart, don't become corrupt and unusable. ### Cookies -The following is an example of how to setup session middleware using cookies. The duration of each session is defined as a total number of seconds via the `-Duration` parameter; here we set the duration to 120, so each session created will expire after 2mins, but the expiry time will be extended each time the session is used: +The following is an example of how to set up session middleware using cookies. The duration of each session is defined as a total number of seconds via the `-Duration` parameter; here we set the duration to 120, so each session created will expire after 2mins, but the expiry time will be extended each time the session is used: ```powershell Start-PodeServer { @@ -30,7 +30,7 @@ The default name of the session cookie is `pode.sid`, but this can be customised ### Headers -Sessions are also supported using headers - useful for CLI requests. The following example will enable sessions use headers instead of cookies, and will also set each session created to have a `-Duration` of 120 seconds: +Sessions are also supported using headers - useful for CLI requests. The following example will enable sessions to use headers instead of cookies, and will also set each session created to have a `-Duration` of 120 seconds: ```powershell Start-PodeServer { @@ -40,13 +40,54 @@ Start-PodeServer { When using headers, the default name of the session header in the request/response is `pode.sid` - this can be customised using the `-Name` parameter. When you make an initial request to authenticate some user, the `pode.sid` header will be returned in the response. You can then use the value of this header in subsequent requests for the authenticated user, and then make a call using the session one last time against some route to expire the session - or just let it automatically expire. +## Scope + +Sessions have two different Scopes: Browser and Tab. You can specify the scope using the `-Scope` parameter on [`Enable-PodeSessionMiddleware`](../../../../Functions/Sessions/Enable-PodeSessionMiddleware). + +!!! important + Using the Tabs scope requires additional frontend logic, and doesn't work out-of-the-box like the Browser scope. See more [below](#tabs). + +The default Scope is Browser, where any authentication and general session data is shared across all tabs in a browser. If you have a site with a view counter and you log in to your site on one tab, and then open another tab and navigate to your site, you'll be automatically logged in and see the same view counter results in both tabs. + +The Tabs scope still shares authentication data, so if you log in to your site in one tab and open it again in a different tab, you'll still be logged in. However, general data is separated; taking the view counter example above, both tabs will show different results for the view counter. + +### Tabs + +Unlike the Browser scope which works out-of-the-box when enabled, the Tabs scope requires additional frontend logic. + +For session data to be split across different tabs, you need to inform Pode about what the "TabId" is for each tab. This is done by supplying an `X-PODE-SESSION-TAB-ID` HTTP header in the request. From a browser on a normal page request, there's no way to supply this header, and the normal base session will be supplied instead - hence why authentication data remains shared across tabs. However, if you load the content of your site asynchronously, or via any other means, you can supply this header and it will let you split general session data across tabs. + +In websites, the TabId is typically generated via JavaScript, and stored in `window.sessionStorage`. However, you have to be careful with this approach, as it does make tab sessions susceptible to XSS attacks. The following is a similar approach as used by Pode.Web: + +```javascript +// set TabId +if (window.sessionStorage.TabId) { + window.TabId = window.sessionStorage.TabId; + window.sessionStorage.removeItem("TabId"); +} +else { + window.TabId = Math.floor(Math.random() * 1000000); +} + +// binding to persist TabId on refresh +window.addEventListener("beforeunload", function(e) { + window.sessionStorage.TabId = window.TabId; + return null; +}); +``` + +The TabId could then be sent as an HTTP header using AJAX. There are other approaches available online as well. + ## SessionIds -The inbuilt SessionId generator used for sessions is a GUID, but you can supply a custom generator using the `-Generator` parameter. +The built-in SessionId generator used for sessions is a GUID, but you can supply a custom generator using the `-Generator` parameter. If supplied, the `-Generator` is a scriptblock that must return a valid string. The string itself should be a random unique value, that can be used as a unique session identifier. -Within a route, or middleware, you can get the currently authenticated session'd ID using [`Get-PodeSessionId`](../../../../Functions/Sessions/Get-PodeSessionId). If there is no session, or the session is not authenticated, then `$null` is returned. This function can also returned the fully signed sessionId as well. If you want the sessionId even if it's not authenticated, then you can supply `-Force` to get the current SessionId back. +Within a route, or middleware, you can get the currently authenticated session's ID using [`Get-PodeSessionId`](../../../../Functions/Sessions/Get-PodeSessionId). If there is no session, or the session is not authenticated, then `$null` is returned. This function can also return the fully signed sessionId as well. If you want the sessionId even if it's not authenticated, then you can supply `-Force` to get the current SessionId back. + +!!! note + If you're using the Tab `-Scope`, then the SessionId will include the TabId as well, if one was supplied. ### Strict @@ -66,7 +107,7 @@ You can define a custom storage by supplying a `psobject` to the `-Storage` para [void] Delete([string] $sessionId) ``` -For example, the following is a mock up of a Storage for Redis (note that the functions are fake): +For example, the following is a mock up of a Storage for Redis. Note that the functions are fake and also that the returned User property in the hashtable MUST be an object (such as via PSCO cast): ```powershell # create the object @@ -76,7 +117,12 @@ $store = New-Object -TypeName psobject $store | Add-Member -MemberType NoteProperty -Name Get -Value { param($sessionId) $data = Get-RedisKey -Key $sessionId - return ($data | ConvertFrom-Json -AsHashtable) + $session = $data | ConvertFrom-Json -AsHashtable + try { + $session.Data.Auth.User = [PSCustomObject]$session.Data.Auth.User + } + catch {} + return $session } # add a Set property to save a session's data @@ -97,7 +143,7 @@ Enable-PodeSessionMiddleware -Duration 120 -Storage $store -Secret 'schwifty' ## Session Data -To add data to a session you can utilise the `.Session.Data` property within the [web event](../../../WebEvent) object accessible in a Route - or other Middleware. The data will be saved to some storage at the end of the route automatically using Endware. When a request is made using the same SessionId, the data is loaded from the store. For example, incrementing some view counter: +To add data to a session you can use the `.Session.Data` property within the [web event](../../../WebEvent) object, which is accessible in a Route or other Middleware. The data will be saved to some storage at the end of the request automatically using Endware. When a request is made using the same SessionId, the data is loaded from the store. For example, incrementing some view counter: ```powershell Add-PodeRoute -Method Get -Path '/' -ScriptBlock { @@ -105,7 +151,7 @@ Add-PodeRoute -Method Get -Path '/' -ScriptBlock { } ``` -You can also use the `$session:` variable scope, which will get/set data on the current session for the name supplied. You can use `$session:` anywhere a `$WebEvent` is available - such as Routes, Middleware, Authentication and Endware. The same view counter example above would now be as follows: +You can also use the `$session:` variable scope, which will get/set data on the current session for the name supplied. You can use `$session:` anywhere a `$WebEvent` is available - such as Routes, Middleware, Authentication, and Endware. The same view counter example above would now be as follows: ```powershell Add-PodeRoute -Method Get -Path '/' -ScriptBlock { @@ -116,11 +162,14 @@ Add-PodeRoute -Method Get -Path '/' -ScriptBlock { A session's data will be automatically saved by Pode at the end of each request, but you can force the data of the current session to be saved by using [`Save-PodeSession`](../../../../Functions/Sessions/Save-PodeSession). !!! important - `$session:` can only be used in the main scriptblocks of Routes, etc. If you attempt to use it in a function of a custom module, it will fail; even if you're using the function in a route. Pode remaps `$session:` on server start, and can only do this to the main scriptblocks supplied to functions such as `Add-PodeRoute`. In these scenarios you will have to use `$WebEvent.Session.Data`. + `$session:` can only be used in the main scriptblocks of Routes, etc. If you attempt to use it in a function of a custom module, it will fail; even if you're using the function in a route. Pode remaps `$session:` on server start, and can only do this to the main scriptblocks supplied to functions such as `Add-PodeRoute`. In these scenarios, you will have to use `$WebEvent.Session.Data`. + +!!! note + If using the Tab `-Scope`, any session data will be stored separately from other tabs. This allows you to have multiple tabs open for the same site/page but all with separate session data. Any authentication data will still be shared. ## Expiry -When you enable Sessions using [`Enable-PodeSessionMiddleware`](../../../../Functions/Sessions/Enable-PodeSessionMiddleware) you can define the duration of each session created, in seconds, using the `-Duration` parameter. When a session is created its expiry is set to `DateTime.UtcNow + Duration`, and by default a session will automatically expire when the calculated DateTime is reached: +When you enable Sessions using [`Enable-PodeSessionMiddleware`](../../../../Functions/Sessions/Enable-PodeSessionMiddleware) you can define the duration of each session created, in seconds, using the `-Duration` parameter. When a session is created its expiry is set to `DateTime.UtcNow + Duration`, and by default, a session will automatically expire when the calculated DateTime is reached: ```powershell Start-PodeServer { @@ -128,7 +177,7 @@ Start-PodeServer { } ``` -You can tell Pode to reset/extend each session's expiry on each request sent, that uses that SessionId, by passing the `-Extend` switch. When a session's expiry is reset/extended, the DateTime/Duration calculation is re-calculated: +You can tell Pode to reset/extend each session's expiry on each request sent, that uses that SessionId, by supplying the `-Extend` switch. When a session's expiry is reset/extended, the DateTime/Duration calculation is re-calculated: ```powershell Start-PodeServer { @@ -138,7 +187,7 @@ Start-PodeServer { ### Retrieve -You can retrieve the expiry for the current session by using [`Get-PodeSessionExpiry`](../../../../Functions/Sessions/Get-PodeSessionExpiry). If you use this function without `-Extend` specified originally then this will return the explicit DateTime the current session will expire. However, if you did setup sessions to extend the this function will return the recalculated expiry for the current session on each call: +You can retrieve the expiry for the current session by using [`Get-PodeSessionExpiry`](../../../../Functions/Sessions/Get-PodeSessionExpiry). If you use this function without `-Extend` specified originally then this will return the explicit DateTime the current session will expire. However, if you did set up sessions to extend then this function will return the recalculated expiry for the current session on each call: ```powershell Start-PodeServer { @@ -168,7 +217,7 @@ Start-PodeServer { ### Reset -For any session created when `-Extend` wasn't supplied to [`Enable-PodeSessionMiddleware`](../../../../Functions/Sessions/Enable-PodeSessionMiddleware) will always have a explicit DateTime set for expiring. However, you can reset this expiry date using [`Reset-PodeSessionExpiry`](../../../../Functions/Sessions/Reset-PodeSessionExpiry), and the current session's expiry will be recalculated from now plus the specifed `-Duration`: +For any session created when `-Extend` wasn't supplied to [`Enable-PodeSessionMiddleware`](../../../../Functions/Sessions/Enable-PodeSessionMiddleware) will always have an explicit DateTime set for expiring. However, you can reset this expiry date using [`Reset-PodeSessionExpiry`](../../../../Functions/Sessions/Reset-PodeSessionExpiry), and the current session's expiry will be recalculated from now plus the specified `-Duration`: ```powershell Start-PodeServer { diff --git a/docs/Tutorials/OpenAPI.md b/docs/Tutorials/OpenAPI.md deleted file mode 100644 index 52ba4a447..000000000 --- a/docs/Tutorials/OpenAPI.md +++ /dev/null @@ -1,505 +0,0 @@ -# OpenAPI - -Pode has inbuilt support for converting your routes into OpenAPI 3.0 definitions. There is also support for a enabling simple Swagger and/or ReDoc viewers. - -You can simply enable OpenAPI in Pode, and a very simple definition will be generated. However, to get a more complex definition with request bodies, parameters and response payloads, you'll need to use the relevant OpenAPI functions detailed below. - -## Enabling OpenAPI - -To enable support for generating OpenAPI definitions you'll need to use the [`Enable-PodeOpenApi`](../../Functions/OpenApi/Enable-PodeOpenApi) function. This will allow you to set a title and version for your API. You can also set a default route to retrieve the OpenAPI definition for tools like Swagger or ReDoc, the default is at `/openapi`. - -You can also set a route filter (such as `/api/*`, the default is `/*` for everything), so only those routes are included in the definition. - -An example of enabling OpenAPI is a follows: - -```powershell -Enable-PodeOpenApi -Title 'My Awesome API' -Version 9.0.0.1 -``` - -An example of setting the OpenAPI route is a follows. This will create a route accessible at `/docs/openapi`: - -```powershell -Enable-PodeOpenApi -Path '/docs/openapi' -Title 'My Awesome API' -Version 9.0.0.1 -``` - -### Default Setup - -In the very simplest of scenarios, just enabling OpenAPI will generate a minimal definition. It can be viewed in Swagger/ReDoc etc, but won't be usable for trying calls. - -When you enable OpenAPI, and don't set any other OpenAPI data, the following is the minimal data that is included: - -* Every route will have a 200 and Default response -* Although routes will be included, no request bodies, parameters or response payloads will be defined -* If you have multiple endpoints, then the servers section will be included -* Any authentication will be included - -### Get Definition - -Instead of defining a route to return the definition, you can write the definition to the response whenever you want, and in any route, using the [`Get-PodeOpenApiDefinition`](../../Functions/OpenApi/Get-PodeOpenApiDefinition) function. This could be useful in certain scenarios like in Azure Functions, where you can enable OpenAPI, and then write the definition to the response of a GET request if some query parameter is set; eg: `?openapi=1`. - -For example: - -```powershell -Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - if ($WebEvent.Query.openapi -eq 1) { - Get-PodeOpenApiDefinition | Write-PodeJsonResponse - } -} -``` - -## Authentication - -Any authentication defined, either by [`Add-PodeAuthMiddleware`](../../Functions/Authentication/Add-PodeAuthMiddleware), or using the `-Authentication` parameter on Routes, will be automatically added to the `security` section of the OpenAPI definition. - -## Routes - -To extend the definition of a route, you can use the `-PassThru` switch on the [`Add-PodeRoute`](../../Functions/Routes/Add-PodeRoute) function. This will cause the route that was created to be returned, so you can pass it down the pipe into more OpenAPI functions. - -To add metadata to a route's definition you can use the [`Set-PodeOARouteInfo`](../../Functions/OpenApi/Set-PodeOARouteInfo) function. This will allow you to define a summary/description for the route, as well as tags for grouping: - -```powershell -Add-PodeRoute -Method Get -Path "/api/resources" -ScriptBlock { - Set-PodeResponseStatus -Code 200 -} -PassThru | - Set-PodeOARouteInfo -Summary 'Retrieve some resources' -Tags 'Resources' -``` - -Each of the following OpenAPI functions have a `-PassThru` switch, allowing you to chain many of them together. - -### Responses - -You can define multiple responses for a route, but only one of each status code, using the [`Add-PodeOAResponse`](../../Functions/OpenApi/Add-PodeOAResponse) function. You can either just define the response and status code, with a custom description, or with a schema defining the payload of the response. - -The following is an example of defining simple 200 and 404 responses on a route: - -```powershell -Add-PodeRoute -Method Get -Path "/api/user/:userId" -ScriptBlock { - # logic -} -PassThru | - Add-PodeOAResponse -StatusCode 200 -PassThru | - Add-PodeOAResponse -StatusCode 404 -Description 'User not found' -``` - -Whereas the following is a more complex definition, which also defines the responses JSON payload. This payload is defined as an object with a string Name, and integer UserId: - -```powershell -Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - Write-PodeJsonResponse -Value @{ - Name = 'Rick' - UserId = $WebEvent.Parameters['userId'] - } -} -PassThru | - Add-PodeOAResponse -StatusCode 200 -Description 'A user object' -ContentSchemas @{ - 'application/json' = (New-PodeOAObjectProperty -Properties @( - (New-PodeOAStringProperty -Name 'Name'), - (New-PodeOAIntProperty -Name 'UserId') - )) - } -``` - -the JSON response payload defined is as follows: - -```json -{ - "Name": [string], - "UserId": [integer] -} -``` - -Internally, each route is created with an empty default 200 and 500 response. You can remove these, or other added responses, by using [`Remove-PodeOAResponse`](../../Functions/OpenApi/Add-PodeOAResponse): - -```powershell -Add-PodeRoute -Method Get -Path "/api/user/:userId" -ScriptBlock { - # logic -} -PassThru | - Remove-PodeOAResponse -StatusCode 200 -``` - -### Requests - -#### Parameters - -You can set route parameter definitions, such as parameters passed in the path/query, by using the [`Set-PodeOARequest`](../../Functions/OpenApi/Set-PodeOARequest) function with the `-Parameters` parameter. The parameter takes an array of properties converted into parameters, using the [`ConvertTo-PodeOAParameter`](../../Functions/OpenApi/ConvertTo-PodeOAParameter) function. - -For example, to create some integer `userId` parameter that is supplied in the path of the request, the following will work: - -```powershell -Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - Write-PodeJsonResponse -Value @{ - Name = 'Rick' - UserId = $WebEvent.Parameters['userId'] - } -} -PassThru | - Set-PodeOARequest -Parameters @( - (New-PodeOAIntProperty -Name 'userId' -Required | ConvertTo-PodeOAParameter -In Path) - ) -``` - -Whereas you could use the next example to define 2 query parameters, both strings: - -```powershell -Add-PodeRoute -Method Get -Path '/api/users' -ScriptBlock { - Write-PodeJsonResponse -Value @{ - Name = 'Rick' - UserId = $WebEvent.Query['name'] - } -} -PassThru | - Set-PodeOARequest -Parameters @( - (New-PodeOAStringProperty -Name 'name' -Required | ConvertTo-PodeOAParameter -In Query), - (New-PodeOAStringProperty -Name 'city' -Required | ConvertTo-PodeOAParameter -In Query) - ) -``` - -#### Payload - -You can set request payload schemas by using the [`Set-PodeOARequest`](../../Functions/OpenApi/Set-PodeOARequest) function, with the `-RequestBody` parameter. The request body can be defined using the [`New-PodeOARequestBody`](../../Functions/OpenApi/New-PodeOARequestBody) function, and supplying schema definitions for content types - this works in very much a similar way to defining responses above. - -For example, to define a request JSON payload of some `userId` and `name` you could use the following: - -```powershell -Add-PodeRoute -Method Patch -Path '/api/users' -ScriptBlock { - Write-PodeJsonResponse -Value @{ - Name = $WebEvent.Data.name - UserId = $WebEvent.Data.userId - } -} -PassThru | - Set-PodeOARequest -RequestBody ( - New-PodeOARequestBody -Required -ContentSchemas @{ - 'application/json' = (New-PodeOAObjectProperty -Properties @( - (New-PodeOAStringProperty -Name 'name'), - (New-PodeOAIntProperty -Name 'userId') - )) - } - ) -``` - -The expected payload would look as follows: - -```json -{ - "name": [string], - "userId": [integer] -} -``` - -## Components - -You can define reusable OpenAPI components in Pode. Currently supported are Schemas, Parameters, Request Bodies, and Responses. - -### Schemas - -To define a reusable schema that can be used in request bodies, and responses, you can use the [`Add-PodeOAComponentSchema`](../../Functions/OpenApi/Add-PodeOAComponentSchema) function. You'll need to supply a Name, and a Schema that can be reused. - -The following is an example of defining a schema which is a object of Name, UserId, and Age: - -```powershell -# define a reusable schema user object -Add-PodeOAComponentSchema -Name 'UserSchema' -Schema ( - New-PodeOAObjectProperty -Properties @( - (New-PodeOAStringProperty -Name 'Name'), - (New-PodeOAIntProperty -Name 'UserId'), - (New-PodeOAIntProperty -Name 'Age') - ) -) - -# reuse the above schema in a response -Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - Write-PodeJsonResponse -Value @{ - Name = 'Rick' - UserId = $WebEvent.Parameters['userId'] - Age = 42 - } -} -PassThru | - Add-PodeOAResponse -StatusCode 200 -Description 'A list of users' -ContentSchemas @{ - 'application/json' = 'UserSchema' - } -``` - -### Request Bodies - -To define a reusable request bodies you can use the [`Add-PodeOAComponentRequestBody`](../../Functions/OpenApi/Add-PodeOAComponentRequestBody) function. You'll need to supply a Name, as well as the needed schemas for each content type. - -The following is an example of defining a JSON object that a Name, UserId, and an Enable flag: - -```powershell -# define a reusable request body -Add-PodeOAComponentRequestBody -Name 'UserBody' -Required -ContentSchemas @{ - 'application/json' = (New-PodeOAObjectProperty -Properties @( - (New-PodeOAStringProperty -Name 'Name'), - (New-PodeOAIntProperty -Name 'UserId'), - (New-PodeOABoolProperty -Name 'Enabled') - )) -} - -# use the request body in a route -Add-PodeRoute -Method Patch -Path '/api/users' -ScriptBlock { - Set-PodeResponseStatus -StatusCode 200 -} -PassThru | - Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Reference 'UserBody') -``` - -The JSON payload expected is of the format: - -```json -{ - "Name": [string], - "UserId": [integer], - "Enabled": [boolean] -} -``` - -### Parameters - -To define reusable parameters that are used on requests, you can use the [`Add-PodeOAComponentParameter`](../../Functions/OpenApi/Add-PodeOAComponentParameter) function. You'll need to supply a Name and the Parameter definition. - -The following is an example of defining an integer path parameter for a `userId`, and then using that parameter on a route. - -```powershell -# define a reusable {userid} path parameter -New-PodeOAIntProperty -Name 'userId' -Required | ConvertTo-PodeOAParameter -In Path |Add-PodeOAComponentParameter -Name 'UserId' - -# use this parameter in a route -Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - Write-PodeJsonResponse -Value @{ - Name = 'Rick' - UserId = $WebEvent.Parameters['userId'] - } -} -PassThru | - Set-PodeOARequest -Parameters @(ConvertTo-PodeOAParameter -Reference 'UserId') -``` - -### Responses - -To define a reusable response definition you can use the [`Add-PodeOAComponentResponse`](../../Functions/OpenApi/Add-PodeOAComponentResponse) function. You'll need to supply a Name, and optionally any Content/Header schemas that define the responses payload. - -The following is an example of defining a 200 response, that has a JSON payload of an array of objects for Name/UserId. This can then be used by name on a route: - -```powershell -# defines a response with a json payload -Add-PodeOAComponentResponse -Name 'OK' -Description 'A user object' -ContentSchemas @{ - 'application/json' = (New-PodeOAObjectProperty -Array -Properties @( - (New-PodeOAStringProperty -Name 'Name'), - (New-PodeOAIntProperty -Name 'UserId') - )) -} - -# reuses the above response on a route using its "OK" name -Add-PodeRoute -Method Get -Path "/api/users" -ScriptBlock { - Write-PodeJsonResponse -Value @( - @{ Name = 'Rick'; UserId = 123 }, - @{ Name = 'Geralt'; UserId = 124 } - ) -} -PassThru | - Add-PodeOAResponse -StatusCode 200 -Reference 'OK' -``` - -the JSON response payload defined is as follows: - -```json -[ - { - "Name": [string], - "UserId": [integer] - } -] -``` - -## Properties - -Properties are used to create all Parameters and Schemas in OpenAPI. You can use the simple types on their own, or you can combine multiple of them together to form complex objects. - -### Simple Types - -There are 5 simple property types: Integers, Numbers, Strings, Booleans, and Schemas. Each of which can be created using the following functions: - -* [`New-PodeOAIntProperty`](../../Functions/OpenApi/New-PodeOAIntProperty) -* [`New-PodeOANumberProperty`](../../Functions/OpenApi/New-PodeOANumberProperty) -* [`New-PodeOAStringProperty`](../../Functions/OpenApi/New-PodeOAStringProperty) -* [`New-PodeOABoolProperty`](../../Functions/OpenApi/New-PodeOABoolProperty) -* [`New-PodeOASchemaProperty`](../../Functions/OpenApi/New-PodeOASchemaProperty) - -These properties can be created with a Name, and other flags such as Required and/or a Description: - -```powershell -# simple integer -New-PodeOAIntProperty -Name 'userId' - -# a float number with a max value of 100 -New-PodeOANumberProperty -Name 'ratio' -Format Float -Maximum 100 - -# a string with a default value, and enum of options -New-PodeOAStringProperty -Name 'type' -Default 'admin' -Enum @('admin', 'user') - -# a boolean that's required -New-PodeOABoolProperty -Name 'enabled' -Required - -# a schema property that references another component schema -New-PodeOASchemaProperty -Name 'Config' -Reference 'ConfigSchema' -``` - -On their own, like above, the simple properties don't really do much. However, you can combine that together to make complex objects/arrays as defined below. - -### Arrays - -There isn't a dedicated function to create an array property, instead there is an `-Array` switch on each of the property functions - both Object and the above simple properties. - -If you supply the `-Array` switch to any of the above simple properties, this will define an array of that type - the `-Name` parameter can also be omitted if only a simple array if required. - -For example, the below will define an integer array: - -```powershell -New-PodeOAIntProperty -Array -``` - -When used in a Response, this could return the following JSON example: - -```json -[ - 0, - 1, - 2 -] -``` - -### Objects - -An object property is a combination of multiple other properties - both simple, array of more objects. - -There are two ways to define objects: - -1. Similar to arrays, you can use the `-Object` switch on the simple properties. -2. You can use the [`New-PodeOAObjectProperty`](../../Functions/OpenApi/New-PodeOAObjectProperty) function to combine multiple properties. - -#### Simple - -If you use the `-Object` switch on the simple property function, this will automatically wrap the property as an object. The Name for this is required. - -For example, the below will define a simple `userId` integer object: - -```powershell -New-PodeOAIntProperty -Name 'userId' -Object -``` - -In a response as JSON, this could look as follows: - -```json -{ - "userId": 0 -} -``` - -Furthermore, you can also supply both `-Array` and `-Object` switches: - -```powershell -New-PodeOAIntProperty -Name 'userId' -Object -Array -``` - -This wil result in something like the following JSON: - -```json -{ - "userId": [ 0, 1, 2 ] -} -``` - -#### Complex - -Unlike the `-Object` switch that simply converts a single property into an object, the [`New-PodeOAObjectProperty`](../../Functions/OpenApi/New-PodeOAObjectProperty) function can combine and convert multiple properties. - -For example, the following will create an object using an Integer, String, and a Boolean: - -```powershell -New-PodeOAObjectProperty -Properties @( - (New-PodeOAIntProperty -Name 'userId'), - (New-PodeOAStringProperty -Name 'name'), - (New-PodeOABoolProperty -Name 'enabled') -) -``` - -As JSON, this could look as follows: - -```json -{ - "userId": 0, - "name": "Gary Goodspeed", - "enabled": true -} -``` - -You can also supply the `-Array` switch to the [`New-PodeOAObjectProperty`](../../Functions/OpenApi/New-PodeOAObjectProperty) function. This will result in an array of objects. For example, if we took the above: - -```powershell -New-PodeOAObjectProperty -Array -Properties @( - (New-PodeOAIntProperty -Name 'userId'), - (New-PodeOAStringProperty -Name 'name'), - (New-PodeOABoolProperty -Name 'enabled') -) -``` - -As JSON, this could look as follows: - -```json -[ - { - "userId": 0, - "name": "Gary Goodspeed", - "enabled": true - }, - { - "userId": 1, - "name": "Kevin", - "enabled": false - } -] -``` - -You can also combine objects into other objects: - -```powershell -$usersArray = New-PodeOAObjectProperty -Name 'users' -Array -Properties @( - (New-PodeOAIntProperty -Name 'userId'), - (New-PodeOAStringProperty -Name 'name'), - (New-PodeOABoolProperty -Name 'enabled') -) - -New-PodeOAObjectProperty -Properties @( - (New-PodeOAIntProperty -Name 'found'), - $usersArray -) -``` - -As JSON, this could look as follows: - -```json -{ - "found": 2, - "users": [ - { - "userId": 0, - "name": "Gary Goodspeed", - "enabled": true - }, - { - "userId": 1, - "name": "Kevin", - "enabled": false - } - ] -} -``` - -## Swagger and ReDoc - -If you're not using a custom OpenAPI viewer, then you can use one of the inbuilt ones with Pode - either Swagger and ReDoc, or both! - -For both you can customise the path to access the page on, but by default Swagger is at `/swagger` and ReDoc is at `/redoc`. If you've written your own custom OpenAPI definition then you can also set a custom path to fetch the definition. - -To enable either you can use the [`Enable-PodeOpenApiViewer`](../../Functions/OpenApi/Enable-PodeOpenApiViewer) function: - -```powershell -# for swagger at "/docs/swagger" -Enable-PodeOpenApiViewer -Type Swagger -Path '/docs/swagger' -DarkMode - -# or ReDoc at the default "/redoc" -Enable-PodeOpenApiViewer -Type ReDoc -``` diff --git a/docs/Tutorials/OpenAPI/Overview.md b/docs/Tutorials/OpenAPI/Overview.md new file mode 100644 index 000000000..66098b2e5 --- /dev/null +++ b/docs/Tutorials/OpenAPI/Overview.md @@ -0,0 +1,1043 @@ +# Overview + +Pode has built-in support for converting your routes into OpenAPI 3.0 definitions. There is also support for enabling simple Swagger and/or ReDoc viewers and others. + +The OpenApi module has been extended with many more functions, and some old ones have been improved. + +For more detailed information regarding OpenAPI and Pode, please refer to [OpenAPI Specification and Pode](../Specification/v3_0_3.md) + +You can enable OpenAPI in Pode, and a straightforward definition will be generated. However, to get a more complex definition with request bodies, parameters, and response payloads, you'll need to use the relevant OpenAPI functions detailed below. + +## Enabling OpenAPI + +To enable support for generating OpenAPI definitions you'll need to use the [`Enable-PodeOpenApi`](../../../Functions/OpenApi/Enable-PodeOpenApi) function. This will allow you to set a title and version for your API. You can also set a default route to retrieve the OpenAPI definition for tools like Swagger or ReDoc, the default is at `/openapi`. + +You can also set a route filter (such as `/api/*`, the default is `/*` for everything), so only those routes are included in the definition. + +An example of enabling OpenAPI is a follows: + +```powershell +Enable-PodeOpenApi -Title 'My Awesome API' -Version 9.0.0.1 +``` + +An example of setting the OpenAPI route is a follows. This will create a route accessible at `/docs/openapi`: + +```powershell +Enable-PodeOpenApi -Path '/docs/openapi' -Title 'My Awesome API' -Version 9.0.0.1 +``` + +### Default Setup + +In the very simplest of scenarios, just enabling OpenAPI will generate a minimal definition. It can be viewed in Swagger/ReDoc etc, but won't be usable for trying calls. + +When you enable OpenAPI, and don't set any other OpenAPI data, the following is the minimal data that is included: + +* Every route will have a 200 and Default response +* Although routes will be included, no request bodies, parameters or response payloads will be defined +* If you have multiple endpoints, then the servers section will be included +* Any authentication will be included + +This can be changed with [`Enable-PodeOpenApi`](../../../Functions/OpenApi/Enable-PodeOpenApi) + +For example to change the default response 404 and 500 + +```powershell +Enable-PodeOpenApi -Path '/docs/openapi' -OpenApiVersion '3.0.3' -DefaultResponses ( + New-PodeOAResponse -StatusCode 404 -Description 'User not found' | Add-PodeOAResponse -StatusCode 500 + ) +``` + +For disabling the Default Response use: + +```powershell +Enable-PodeOpenApi -Path '/docs/openapi' -OpenApiVersion '3.0.3' -NoDefaultResponses +``` + +For disabling the Minimal Definitions feature use: + +```powershell +Enable-PodeOpenApi -Path '/docs/openapi' -OpenApiVersion '3.0.3' -DisableMinimalDefinitions +``` + +### Get Definition + +Instead of defining a route to return the definition, you can write the definition to the response whenever you want, and in any route, using the [`Get-PodeOADefinition`](../../../Functions/OpenApi/Get-PodeOADefinition) function. This could be useful in certain scenarios like in Azure Functions, where you can enable OpenAPI, and then write the definition to the response of a GET request if some query parameter is set; eg: `?openapi=1`. + +For example: + +```powershell +Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + if ($WebEvent.Query.openapi -eq 1) { + Get-PodeOpenApiDefinition | Write-PodeJsonResponse + } +} +``` + +## OpenAPI Info object + +In previous releases some of the Info object properties like Version and Title were defined by [`Enable-PodeOpenApi`](../../../Functions/OpenApi/Enable-PodeOpenApi). +Starting from version 2.10 a new [`Add-PodeOAInfo`](../../../Functions/OpenApi/Add-PodeOAInfo) function has been added to create a full OpenAPI Info spec. + +```powershell +Add-PodeOAInfo -Title 'Swagger Petstore - OpenAPI 3.0' ` + -Version 1.0.17 ` + -Description $InfoDescription ` + -TermsOfService 'http://swagger.io/terms/' ` + -LicenseName 'Apache 2.0' ` + -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' ` + -ContactName 'API Support' ` + -ContactEmail 'apiteam@swagger.io' +``` + +## OpenAPI configuration Best Practice + +Pode is rich of functions to create and configure an complete OpenApi spec. Here is a typical code you should use to initiate an OpenApi spec + +```powershell +#Initialize OpenApi +Enable-PodeOpenApi -Path '/docs/openapi' -Title 'Swagger Petstore - OpenAPI 3.0' ` + -OpenApiVersion 3.1 -DisableMinimalDefinitions -NoDefaultResponses + +# OpenApi Info +Add-PodeOAInfo -Title 'Swagger Petstore - OpenAPI 3.0' ` + -Version 1.0.17 ` + -Description 'This is a sample Pet Store Server based on the OpenAPI 3.0 specification. ...' ` + -TermsOfService 'http://swagger.io/terms/' ` + -LicenseName 'Apache 2.0' ` + -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' ` + -ContactName 'API Support' ` + -ContactEmail 'apiteam@swagger.io' ` + -ContactUrl 'http://example.com/support' + +# Endpoint for the API + Add-PodeOAServerEndpoint -url '/api/v3.1' -Description 'default endpoint' + + # OpenApi external documentation links + $extDoc = New-PodeOAExternalDoc -Name 'SwaggerDocs' -Description 'Find out more about Swagger' -Url 'http://swagger.io' + $extDoc | Add-PodeOAExternalDoc + + # OpenApi documentation viewer + Enable-PodeOAViewer -Type Swagger -Path '/docs/swagger' + Enable-PodeOAViewer -Type ReDoc -Path '/docs/redoc' + Enable-PodeOAViewer -Type RapiDoc -Path '/docs/rapidoc' + Enable-PodeOAViewer -Type StopLight -Path '/docs/stoplight' + Enable-PodeOAViewer -Type Explorer -Path '/docs/explorer' + Enable-PodeOAViewer -Bookmarks -Path '/docs' +``` + +## Authentication + +Any authentication defined, either by [`Add-PodeAuthMiddleware`](../../../Functions/Authentication/Add-PodeAuthMiddleware), or using the `-Authentication` parameter on Routes, will be automatically added to the `security` section of the OpenAPI definition. + + +## Tags + +In OpenAPI, a "tag" is used to group related operations. Tags are often used to organize and categorize endpoints in an API specification, making it easier to understand and navigate the API documentation. Each tag can be associated with one or more API operations, and these tags are then used in tools like Swagger UI to group and display operations in a more organized way. + +Here's an example of how to define and use tags: + +```powershell +# create an External Doc reference +$swaggerDocs = New-PodeOAExternalDoc -Description 'Find out more about Swagger' -Url 'http://swagger.io' + +# create a Tag +Add-PodeOATag -Name 'pet' -Description 'Everything about your Pets' -ExternalDoc $swaggerDocs + +Add-PodeRoute -PassThru -Method get -Path '/pet/findByStatus' -Authentication 'Login-OAuth2' -Scope 'read' -AllowAnon -ScriptBlock { + #route code +} | Set-PodeOARouteInfo -Summary 'Finds Pets by status' -Description 'Multiple status values can be provided with comma-separated strings' ` + -Tags 'pet' -OperationId 'findPetsByStatus' +``` + +## Routes + +To extend the definition of a route, you can use the `-PassThru` switch on the [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute) function. This will cause the route that was created to be returned, so you can pass it down the pipe into more OpenAPI functions. + +To add metadata to a route's definition you can use the [`Set-PodeOARouteInfo`](../../../Functions/OpenApi/Set-PodeOARouteInfo) function. This will allow you to define a summary/description for the route, as well as tags for grouping: + +```powershell +Add-PodeRoute -Method Get -Path "/api/resources" -ScriptBlock { + Set-PodeResponseStatus -Code 200 +} -PassThru | + Set-PodeOARouteInfo -Summary 'Retrieve some resources' -Tags 'Resources' +``` + +Each of the following OpenAPI functions have a `-PassThru` switch, allowing you to chain many of them together. + +### Responses + +You can define multiple responses for a route, but only one of each status code, using the [`Add-PodeOAResponse`](../../../Functions/OpenApi/Add-PodeOAResponse) function. You can either just define the response and status code, with a custom description, or with a schema defining the payload of the response. + +The following is an example of defining simple 200 and 404 responses on a route: + +```powershell +Add-PodeRoute -Method Get -Path "/api/user/:userId" -ScriptBlock { + # logic +} -PassThru | + Add-PodeOAResponse -StatusCode 200 -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' +``` + +Whereas the following is a more complex definition, which also defines the responses JSON payload. This payload is defined as an object with a string Name, and integer UserId: + +```powershell +Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { + Write-PodeJsonResponse -Value @{ + Name = 'Rick' + UserId = $WebEvent.Parameters['userId'] + } +} -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'A user object' --Content @{ + 'application/json' = (New-PodeOAStringProperty -Name 'Name'| + New-PodeOAIntProperty -Name 'UserId'| New-PodeOAObjectProperty) + } +``` + +the JSON response payload defined is as follows: + +```json +{ + "Name": [string], + "UserId": [integer] +} +``` + +In case the response JSON payload is an array + +```powershell +Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { + Write-PodeJsonResponse -Value @{ + Name = 'Rick' + UserId = $WebEvent.Parameters['userId'] + } + } -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'A user object' -Content ( + New-PodeOAContentMediaType -ContentMediaType 'application/json' -Array -Content ( + New-PodeOAStringProperty -Name 'Name' | + New-PodeOAIntProperty -Name 'UserId' | + New-PodeOAObjectProperty + ) + ) +``` + +```json +[ + { + "Name": [string], + "UserId": [integer] + } +] +``` + +Internally, each route is created with an empty default 200 and 500 response. You can remove these, or other added responses, by using [`Remove-PodeOAResponse`](../../../Functions/OpenApi/Remove-PodeOAResponse): + +```powershell +Add-PodeRoute -Method Get -Path "/api/user/:userId" -ScriptBlock { + # route logic +} -PassThru | + Remove-PodeOAResponse -StatusCode 200 +``` + +### Requests + +#### Parameters + +You can set route parameter definitions, such as parameters passed in the path/query, by using the [`Set-PodeOARequest`](../../../Functions/OpenApi/Set-PodeOARequest) function with the `-Parameters` parameter. The parameter takes an array of properties converted into parameters, using the [`ConvertTo-PodeOAParameter`](../../../Functions/OpenApi/ConvertTo-PodeOAParameter) function. + +For example, to create some integer `userId` parameter that is supplied in the path of the request, the following will work: + +```powershell +Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { + Write-PodeJsonResponse -Value @{ + Name = 'Rick' + UserId = $WebEvent.Parameters['userId'] + } +} -PassThru | + Set-PodeOARequest -Parameters @( + (New-PodeOAIntProperty -Name 'userId' -Required | ConvertTo-PodeOAParameter -In Path) + ) +``` + +Whereas you could use the next example to define 2 query parameters, both strings: + +```powershell +Add-PodeRoute -Method Get -Path '/api/users' -ScriptBlock { + Write-PodeJsonResponse -Value @{ + Name = 'Rick' + UserId = $WebEvent.Query['name'] + } +} -PassThru | + Set-PodeOARequest -Parameters ( + (New-PodeOAStringProperty -Name 'name' -Required | ConvertTo-PodeOAParameter -In Query), + (New-PodeOAStringProperty -Name 'city' -Required | ConvertTo-PodeOAParameter -In Query) + ) +``` + +#### Payload + +You can set request payload schemas by using the [`Set-PodeOARequest`](../../../Functions/OpenApi/Set-PodeOARequest)function, with the `-RequestBody` parameter. The request body can be defined using the [`New-PodeOARequestBody`](../../../Functions/OpenApi/New-PodeOARequestBody) function, and supplying schema definitions for content types - this works in very much a similar way to defining responses above. + +For example, to define a request JSON payload of some `userId` and `name` you could use the following: + +```powershell +Add-PodeRoute -Method Patch -Path '/api/users' -ScriptBlock { + Write-PodeJsonResponse -Value @{ + Name = $WebEvent.Data.name + UserId = $WebEvent.Data.userId + } +} -PassThru | + Set-PodeOARequest -RequestBody ( + New-PodeOARequestBody -Required -Content ( + New-PodeOAContentMediaType -ContentMediaType 'application/json','application/xml' -Content ( New-PodeOAStringProperty -Name 'Name'| New-PodeOAIntProperty -Name 'UserId'| New-PodeOAObjectProperty ) ) + + ) +``` + +The expected payload would look as follows: + +```json +{ + "name": [string], + "userId": [integer] +} +``` + +```xml + + + + + +``` + +## Components + +You can define reusable OpenAPI components in Pode. Currently supported are Schemas, Parameters, Request Bodies, and Responses. + +### Schemas + +To define a reusable schema that can be used in request bodies, and responses, you can use the [`Add-PodeOAComponentSchema`](../../../Functions/OAComponents/Add-PodeOAComponentSchema) function. You'll need to supply a Name, and a Schema that can be reused. + +The following is an example of defining a schema which is a object of Name, UserId, and Age: + +```powershell +# define a reusable schema user object +New-PodeOAStringProperty -Name 'Name' | + New-PodeOAIntProperty -Name 'UserId' | + New-PodeOAIntProperty -Name 'Age' | + New-PodeOAObjectProperty | + Add-PodeOAComponentSchema -Name 'UserSchema' + +# reuse the above schema in a response +Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { + Write-PodeJsonResponse -Value @{ + Name = 'Rick' + UserId = $WebEvent.Parameters['userId'] + Age = 42 + } +} -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'A list of users' -Content @{ + 'application/json' = 'UserSchema' + } +``` + +### Request Bodies + +To define a reusable request bodies you can use the [`Add-PodeOAComponentRequestBody`](../../../Functions/OAComponents/Add-PodeOAComponentRequestBody) function. You'll need to supply a Name, as well as the needed schemas for each content type. + +The following is an example of defining a JSON object that a Name, UserId, and an Enable flag: + +```powershell +# define a reusable request body +New-PodeOAContentMediaType -ContentMediaType 'application/json', 'application/x-www-form-urlencoded' -Content ( + New-PodeOAStringProperty -Name 'Name' | + New-PodeOAIntProperty -Name 'UserId' | + New-PodeOABoolProperty -Name 'Enabled' | + New-PodeOAObjectProperty + ) | Add-PodeOAComponentRequestBody -Name 'UserBody' -Required + +# use the request body in a route +Add-PodeRoute -Method Patch -Path '/api/users' -ScriptBlock { + Set-PodeResponseStatus -StatusCode 200 +} -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Reference 'UserBody') +``` + +The JSON payload expected is of the format: + +```json +{ + "Name": [string], + "UserId": [integer], + "Enabled": [boolean] +} +``` + +### Parameters + +To define reusable parameters that are used on requests, you can use the [`Add-PodeOAComponentParameter`](../../../Functions/OAComponents/Add-PodeOAComponentParameter) function. You'll need to supply a Name and the Parameter definition. + +The following is an example of defining an integer path parameter for a `userId`, and then using that parameter on a route. + +```powershell +# define a reusable {userid} path parameter +New-PodeOAIntProperty -Name 'userId' -Required | ConvertTo-PodeOAParameter -In Path |Add-PodeOAComponentParameter -Name 'UserId' + +# use this parameter in a route +Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { + Write-PodeJsonResponse -Value @{ + Name = 'Rick' + UserId = $WebEvent.Parameters['userId'] + } +} -PassThru | + Set-PodeOARequest -Parameters @(ConvertTo-PodeOAParameter -Reference 'UserId') +``` + +### Responses + +To define a reusable response definition you can use the [`Add-PodeOAComponentResponse`](../../../Functions/OAComponents/Add-PodeOAComponentResponse) function. You'll need to supply a Name, and optionally any Content/Header schemas that define the responses payload. + +The following is an example of defining a 200 response with a JSON payload of an array of objects for Name/UserId. The Response component can be used by a route referencing the name: + +```powershell +# defines a response with a json payload using New-PodeOAContentMediaType +Add-PodeOAComponentResponse -Name 'OK' -Description 'A user object' -Content ( + New-PodeOAContentMediaType -MediaType 'application/json' -Array -Content ( + New-PodeOAStringProperty -Name 'Name' | + New-PodeOAIntProperty -Name 'UserId' | + New-PodeOAObjectProperty + ) + ) + +# reuses the above response on a route using its "OK" name +Add-PodeRoute -Method Get -Path "/api/users" -ScriptBlock { + Write-PodeJsonResponse -Value @( + @{ Name = 'Rick'; UserId = 123 }, + @{ Name = 'Geralt'; UserId = 124 } + ) +} -PassThru | + Add-PodeOAResponse -StatusCode 200 -Reference 'OK' +``` + +the JSON response payload defined is as follows: + +```json +[ + { + "Name": [string], + "UserId": [integer] + } +] +``` + + +### Examples + +To define a reusable example definition you can use the [`Add-PodeOAComponentExample`](../../../Functions/OAComponents/Add-PodeOAComponentExample) function. You'll need to supply a Name, a Summary and a list of value representing the object. + +The following is an example that defines three Pet examples request bodies, and how they're used in a Route's OpenAPI definition: + +```powershell + # defines the frog example +Add-PodeOAComponentExample -name 'frog-example' -Summary "An example of a frog with a cat's name" -Value @{ + name = 'Jaguar'; petType = 'Panthera'; color = 'Lion'; gender = 'Male'; breed = 'Mantella Baroni' +} +# defines the cat example +Add-PodeOAComponentExample -Name 'cat-example' -Summary 'An example of a cat' -Value @{ + name = 'Fluffy'; petType = 'Cat'; color = 'White'; gender = 'male'; breed = 'Persian' +} +# defines the dog example +Add-PodeOAComponentExample -Name 'dog-example' -Summary "An example of a dog with a cat's name" -Value @{ + name = 'Puma'; petType = 'Dog'; color = 'Black'; gender = 'Female'; breed = 'Mixed' +} + +# reuses the examples +Add-PodeRoute -PassThru -Method Put -Path '/pet/:petId' -ScriptBlock { + # route code +} | Set-PodeOARouteInfo -Summary 'Updates a pet in the store with form data' -Tags 'pet' ` + -OperationId 'updatepet' -PassThru | + Set-PodeOARequest -Parameters @( + (New-PodeOAStringProperty -Name 'petId' -Description 'ID of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Path -Required) + ) -RequestBody ( + New-PodeOARequestBody -Description 'user to add to the system' -Content @{ 'application/json' = 'Pet' } -Examples ( + New-PodeOAExample -ContentMediaType 'application/json', 'application/xml' -Reference 'cat-example' | + New-PodeOAExample -ContentMediaType 'application/json', 'application/xml' -Reference 'dog-example' | + New-PodeOAExample -ContentMediaType 'application/json', 'application/xml' -Reference 'frog-example' + ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Pet updated.' +``` + +### Headers + +To define a reusable header definition you can use the [`Add-PodeOAComponentHeader`](../../../Functions/OAComponents/Add-PodeOAComponentHeader) function. You'll need to supply a Name, and optionally any Content/Header schemas that define the responses payload. + +```powershell + # define Headers +New-PodeOAIntProperty -Format Int32 -Description 'calls per hour allowed by the user' | + Add-PodeOAComponentHeader -Name 'X-Rate-Limit' +New-PodeOAStringProperty -Format Date-Time -Description 'date in UTC when token expires' | + Add-PodeOAComponentHeader -Name 'X-Expires-After' + +Add-PodeRoute -PassThru -Method Get -Path '/user/login' -ScriptBlock { + # route code +} | Set-PodeOARouteInfo -Summary 'Logs user into the system.' -Description 'Logs user into the system.' ` + -Tags 'user' -OperationId 'loginUser' -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' ` + -Header @('X-Rate-Limit', 'X-Expires-After') -Content ( + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'string' + ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username/password supplied' +``` + + +### CallBacks + +To define a reusable callback definition you can use the [`Add-PodeOAComponentCallBack`](../../../Functions/OAComponents/Add-PodeOAComponentCallBack) function. You'll need to supply a Name, and optionally any Content/Header schemas that define the responses payload. + +```powershell +Add-PodeRoute -PassThru -Method Post -Path '/petcallbackReference' -Authentication 'Login-OAuth2' ` + -Scope 'write' -ScriptBlock { + #route code +} | Set-PodeOARouteInfo -Summary 'Add a new pet to the store' -Description 'Add a new pet to the store' ` + -Tags 'pet' -OperationId 'petcallbackReference' -PassThru | + Set-PodeOARequest -RequestBody ( New-PodeOARequestBody -Reference 'PetBodySchema' ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content ( + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' + ) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Validation exception' -Content @{ + 'application / json' = ( New-PodeOAStringProperty -Name 'result' | + New-PodeOAStringProperty -Name 'message' | + New-PodeOAObjectProperty ) + } -PassThru | + Add-PodeOACallBack -Name 'test1' -Reference 'test' +``` + +### Response Links + +To define a reusable response link definition you can use the [`Add-PodeOAComponentResponseLink`](../../../Functions/OAComponents/Add-PodeOAComponentResponseLink) function. You'll need to supply a Name, and optionally any Content/Header schemas that define the responses payload. + +```powershell +#Add link reference +Add-PodeOAComponentResponseLink -Name 'address' -OperationId 'getUserByName' -Parameters @{ + 'username' = '$request.path.username' +} + +#use link reference +Add-PodeRoute -PassThru -Method Put -Path '/userLinkByRef/:username' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 +} | Set-PodeOARouteInfo -Summary 'Update user' -Description 'This can only be done by the logged in user.' ` + -Tags 'user' -OperationId 'updateUserLinkByRef' -PassThru | + Set-PodeOARequest -Parameters ( + ( New-PodeOAStringProperty -Name 'username' -Description ' name that need to be updated.' -Required | ConvertTo-PodeOAParameter -In Path ) + ) -RequestBody ( + New-PodeOARequestBody -Required -Content ( + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Content @{'application/json' = 'User' } -PassThru -Links ( + New-PodeOAResponseLink -Name 'address2' -Reference 'address' + ) | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' +``` + +## Properties + +Properties are used to create all Parameters and Schemas in OpenAPI. You can use the simple types on their own, or you can combine multiple of them together to form complex objects. + +### Simple Types + +There are 5 simple property types: Integers, Numbers, Strings, Booleans, and Schemas. Each of which can be created using the following functions: + +* [`New-PodeOAIntProperty`](../../../Functions/OAProperties/New-PodeOAIntProperty) +* [`New-PodeOANumberProperty`](../../../Functions/OAProperties/New-PodeOANumberProperty) +* [`New-PodeOAStringProperty`](../../../Functions/OAProperties/New-PodeOAStringProperty) +* [`New-PodeOABoolProperty`](../../../Functions/OAProperties/New-PodeOABoolProperty) +* [`New-PodeOASchemaProperty`](../../../Functions//New-PodeOASchemaProperty) +* [`New-PodeOAMultiTypeProperty`](../../../Functions/OAProperties/New-PodeOAMultiTypeProperty) (Note: OpenAPI 3.1 only) + +These properties can be created with a Name, and other flags such as Required and/or a Description: + +```powershell +# simple integer +New-PodeOAIntProperty -Name 'userId' + +# a float number with a max value of 100 +New-PodeOANumberProperty -Name 'ratio' -Format Float -Maximum 100 + +# a string with a default value, and enum of options +New-PodeOAStringProperty -Name 'type' -Default 'admin' -Enum @('admin', 'user') + +# a boolean that's required +New-PodeOABoolProperty -Name 'enabled' -Required + +# a schema property that references another component schema +New-PodeOASchemaProperty -Name 'Config' -Reference 'ConfigSchema' + +# a string or an integer or a null value (only available with OpenAPI 3.1) +New-PodeOAMultiTypeProperty -Name 'multi' -Type integer,string -Nullable +``` + +On their own, like above, the simple properties don't really do much. However, you can combine that together to make complex objects/arrays as defined below. + +### Arrays + +There isn't a dedicated function to create an array property, instead there is an `-Array` switch on each of the property functions - both Object and the above simple properties. + +If you supply the `-Array` switch to any of the above simple properties, this will define an array of that type - the `-Name` parameter can also be omitted if only a simple array if required. + +For example, the below will define an integer array: + +```powershell +New-PodeOAIntProperty -Array +``` + +When used in a Response, this could return the following JSON example: + +```json +[ + 0, + 1, + 2 +] +``` + +### Objects + +An object property is a combination of multiple other properties - both simple, array of more objects. + +There are two ways to define objects: + +1. Similar to arrays, you can use the `-Object` switch on the simple properties. +2. You can use the [`New-PodeOAObjectProperty`](../../../Functions/OAProperties/New-PodeOAObjectProperty) function to combine multiple properties. + +#### Simple + +If you use the `-Object` switch on the simple property function, this will automatically wrap the property as an object. The Name for this is required. + +For example, the below will define a simple `userId` integer object: + +```powershell +New-PodeOAIntProperty -Name 'userId' -Object +``` + +In a response as JSON, this could look as follows: + +```json +{ + "userId": 0 +} +``` + +Furthermore, you can also supply both `-Array` and `-Object` switches: + +```powershell +New-PodeOAIntProperty -Name 'userId' -Object -Array +``` + +This wil result in something like the following JSON: + +```json +{ + "userId": [ 0, 1, 2 ] +} +``` + +#### Complex + +Unlike the `-Object` switch that simply converts a single property into an object, the [`New-PodeOAObjectProperty`](../../../Functions/OAProperties/New-PodeOAObjectProperty) function can combine and convert multiple properties. + +For example, the following will create an object using an Integer, String, and a Boolean: + +Legacy Definition + +```powershell +New-PodeOAObjectProperty -Properties ( + (New-PodeOAIntProperty -Name 'userId'), + (New-PodeOAStringProperty -Name 'name'), + (New-PodeOABoolProperty -Name 'enabled') +) +``` + +Using piping (new in Pode 2.10) + +```powershell +New-PodeOAIntProperty -Name 'userId'| New-PodeOAStringProperty -Name 'name'| + New-PodeOABoolProperty -Name 'enabled' |New-PodeOAObjectProperty +``` + +As JSON, this could look as follows: + +```json +{ + "userId": 0, + "name": "Gary Goodspeed", + "enabled": true +} +``` + +You can also supply the `-Array` switch to the [`New-PodeOAObjectProperty`](../../../Functions/OAProperties/New-PodeOAObjectProperty) function. This will result in an array of objects. For example, if we took the above: + +```powershell +New-PodeOAIntProperty -Name 'userId'| New-PodeOAStringProperty -Name 'name'| + New-PodeOABoolProperty -Name 'enabled' |New-PodeOAObjectProperty -Array +``` + +As JSON, this could look as follows: + +```json +[ + { + "userId": 0, + "name": "Gary Goodspeed", + "enabled": true + }, + { + "userId": 1, + "name": "Kevin", + "enabled": false + } +] +``` + +You can also combine objects into other objects: + +```powershell +$usersArray = New-PodeOAIntProperty -Name 'userId'| New-PodeOAStringProperty -Name 'name'| + New-PodeOABoolProperty -Name 'enabled' |New-PodeOAObjectProperty -Array + +New-PodeOAObjectProperty -Properties @( + (New-PodeOAIntProperty -Name 'found'), + $usersArray +) +``` + +As JSON, this could look as follows: + +```json +{ + "found": 2, + "users": [ + { + "userId": 0, + "name": "Gary Goodspeed", + "enabled": true + }, + { + "userId": 1, + "name": "Kevin", + "enabled": false + } + ] +} +``` + +### oneOf, anyOf and allOf Keywords + +OpenAPI 3.x provides several keywords which you can use to combine schemas. You can use these keywords to create a complex schema or validate a value against multiple criteria. + +* oneOf - validates the value against exactly one of the sub-schemas +* allOf - validates the value against all the sub-schemas +* anyOf - validates the value against any (one or more) of the sub-schemas + +You can use the [`Merge-PodeOAProperty`](../../../Functions/OAProperties/Merge-PodeOAProperty) will instead define a relationship between the properties. + +Unlike [`New-PodeOAObjectProperty`](../../../Functions/OAProperties/New-PodeOAObjectProperty) which combines and converts multiple properties into an Object, [`Merge-PodeOAProperty`](../../../Functions/OAProperties/Merge-PodeOAProperty) will instead define a relationship between the properties. + +For example, the following will create an something like an C Union object using an Integer, String, and a Boolean: + +```powershell +Merge-PodeOAProperty -Type OneOf -ObjectDefinitions @( + (New-PodeOAIntProperty -Name 'userId' -Object), + (New-PodeOAStringProperty -Name 'name' -Object), + (New-PodeOABoolProperty -Name 'enabled' -Object) + ) +``` + +Or + +```powershell +New-PodeOAIntProperty -Name 'userId' -Object | + New-PodeOAStringProperty -Name 'name' -Object | + New-PodeOABoolProperty -Name 'enabled' -Object | + Merge-PodeOAProperty -Type OneOf +``` + +As JSON, this could look as follows: + +```json +{ + "oneOf": [ + { + "type": "object", + "properties": { + "userId": { + "type": "integer" + } + } + }, + { + "type": "object", + "properties": { + "name": { + "type": "string" + } + } + }, + { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "default": false + } + } + } + ] +} +``` + +You can also supply a Component Schema created using [`Add-PodeOAComponentSchema`](../../../Functions/OAComponents/Add-PodeOAComponentSchema). For example, if we took the above: + +```powershell + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 1 -ReadOnly | + New-PodeOAStringProperty -Name 'username' -Example 'theUser' -Required | + New-PodeOAStringProperty -Name 'firstName' -Example 'John' | + New-PodeOAStringProperty -Name 'lastName' -Example 'James' | + New-PodeOAStringProperty -Name 'email' -Format email -Example 'john@email.com' | + New-PodeOAStringProperty -Name 'lastName' -Example 'James' | + New-PodeOAStringProperty -Name 'password' -Format Password -Example '12345' -Required | + New-PodeOAStringProperty -Name 'phone' -Example '12345' | + New-PodeOAIntProperty -Name 'userStatus'-Format int32 -Description 'User Status' -Example 1| + New-PodeOAObjectProperty -Name 'User' -XmlName 'user' | + Add-PodeOAComponentSchema + + New-PodeOAStringProperty -Name 'street' -Example '437 Lytton' -Required | + New-PodeOAStringProperty -Name 'city' -Example 'Palo Alto' -Required | + New-PodeOAStringProperty -Name 'state' -Example 'CA' -Required | + New-PodeOAStringProperty -Name 'zip' -Example '94031' -Required | + New-PodeOAObjectProperty -Name 'Address' -XmlName 'address' -Description 'Shipping Address' | + Add-PodeOAComponentSchema + + Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'Address','User' + +``` + +As JSON, this could look as follows: + +```json +{ + "allOf": [ + { + "$ref": "#/components/schemas/Address" + }, + { + "$ref": "#/components/schemas/User" + } + ] +} +``` +## Implementing Parameter Validation + +Is possible to validate any parameter submitted by clients against an OpenAPI schema, ensuring adherence to defined standards. + + +First, schema validation has to be enabled using : + +```powershell +Enable-PodeOpenApi -EnableSchemaValidation #any other parameters needed +``` + +This command activates the OpenAPI feature with schema validation enabled, ensuring strict adherence to specified schemas. + +Next, is possible to validate any route using `PodeOAJsonSchemaCompliance`. +In this example, we'll create a route for updating a pet: + +```powershell +Add-PodeRoute -PassThru -Method Post -Path '/user' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + $responseMediaType = Get-PodeHeader -Name 'Accept' + switch ($contentType) { + 'application/xml' { + $user = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $user = ConvertTo-Json $WebEvent.data } + 'application/x-www-form-urlencoded' { $user = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + $Validate = Test-PodeOAJsonSchemaCompliance -Json $user -SchemaReference 'User' + if ($Validate.result) { + $newUser = Add-user -User (convertfrom-json -InputObject $user -AsHashtable) + Save-PodeState -Path $using:PetDataJson + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $newUser -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $newUser -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } +} | Set-PodeOARouteInfo -Summary 'Create user.' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'createUser' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' )) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' -PassThru | + Add-PodeOAResponse -Default -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'User' ) +``` +#### Explanation +- The route handles different content types (JSON/XML) and converts them to JSON for validation. +- It validates the received pet object against the 'User' schema using the 'Test-PodeOAJsonSchemaCompliance' function. +- Depending on the validation result, appropriate HTTP responses are returned. +- OpenAPI metadata such as summary, description, request body, and responses are also defined for documentation purposes. + + + +## OpenApi Documentation pages + +If you're not using a custom OpenAPI viewer, then you can use one or more of the inbuilt which Pode supports: ones with Pode: + +* Swagger +* ReDoc +* RapiDoc +* StopLight +* Explorer +* RapiPdf + +For each you can customise the Route path to access the page on, but by default Swagger is at `/swagger`, ReDoc is at `/redoc`, etc. If you've written your own custom OpenAPI definition then you can also set a custom Route path to fetch the definition on. + +To enable a viewer you can use the [`Enable-PodeOAViewer`](../../../Functions/OpenApi/Enable-PodeOAViewer) function: + +```powershell +# for swagger at "/docs/swagger" +Enable-PodeOpenApiViewer -Type Swagger -Path '/docs/swagger' -DarkMode + +# and ReDoc at the default "/redoc" +Enable-PodeOpenApiViewer -Type ReDoc + +# and RapiDoc at "/docs/rapidoc" +Enable-PodeOAViewer -Type RapiDoc -Path '/docs/rapidoc' -DarkMode + +# and StopLight at "/docs/stoplight" +Enable-PodeOAViewer -Type StopLight -Path '/docs/stoplight' + +# and Explorer at "/docs/explorer" +Enable-PodeOAViewer -Type Explorer -Path '/docs/explorer' + +# and RapiPdf at "/docs/rapipdf" +Enable-PodeOAViewer -Type RapiPdf -Path '/docs/rapipdf' + +# plus a bookmark page with the link to all documentation +Enable-PodeOAViewer -Bookmarks -Path '/docs' + +# there is also an OpenAPI editor (only for v3.0.x) +Enable-PodeOAViewer -Editor -Path '/docs/swagger-editor' +``` + +## Multiple OpenAPI definition + +It's possible to create multiple OpenAPI definitions inside the same Server instance. This feature could be useful in situations such as: + +* Multiple versions of the OpenAPI specification for different use cases +* The same OpenAPI definition, but one using OpenAPI v3.0.3 and another using v3.1.0 +* Different APIs based on the IP or URL + + +### How to use it +Any Pode function that interacts with OpenAPI has a `-DefinitionTag [string[]]` parameter available. This allows you to specify within which OpenAPI definition(s) the API's definition should be available. + +!!! note + These functions accept a simple string, and not an array + + * Get-PodeOADefinition + * Enable-PodeOpenApi + * Enable-PodeOAViewer + * Add-PodeOAInfo + * Test-PodeOAJsonSchemaCompliance + +A new OpenAPI definition has to be created using the `Enable-PodeOpenApi` function + +```powershell +Enable-PodeOpenApi -Path '/docs/openapi/v3.0' -OpenApiVersion '3.0.3' -DefinitionTag 'v3' +Enable-PodeOpenApi -Path '/docs/openapi/v3.1' -OpenApiVersion '3.1.0' -DefinitionTag 'v3.1' +Enable-PodeOpenApi -Path '/docs/openapi/admin' -OpenApiVersion '3.1.0' -DefinitionTag 'admin' +``` + +There is also [`Select-PodeOADefinition`](../../../Functions/OpenApi/Select-PodeOADefinition), which simplifies the selection of which OpenAPI definition to use as a wrapper around multiple OpenAPI functions, or Route functions. Meaning you don't have to specify `-DefinitionTag` on embedded OpenAPI/Route calls: + +```powershell +Select-PodeOADefinition -Tag 'v3', 'v3.1' -Scriptblock { + Add-PodeRouteGroup -Path '/api/v5' -Routes { + Add-PodeRoute -Method Get -Path '/petbyRef/:petId' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 2005 + } + } +} + +Select-PodeOADefinition -Tag 'admin' -ScriptBlock { + # your admin definition +} +``` + +The default `Definition Tag` is named "default". This can be changed using the `Server.psd1` file and the `Web.OpenApi.DefaultDefinitionTag` property + +```powershell +@{ + Web=@{ + OpenApi=@{ + DefaultDefinitionTag= 'NewDfault' + } + } +} +``` + +### OpenAPI example + +A simple OpenAPI definition + +```powershell +Add-PodeOAInfo -Title 'Swagger Petstore - OpenAPI 3.0' -Version 1.0.17 -Description $InfoDescription -TermsOfService 'http://swagger.io/terms/' -LicenseName 'Apache 2.0' ` + -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' -ContactName 'API Support' -ContactEmail 'apiteam@swagger.io' -DefinitionTag 'v3' + +Add-PodeOAInfo -Title 'Swagger Petstore - OpenAPI 3.1' -Version 1.0.17 -Description $InfoDescription -TermsOfService 'http://swagger.io/terms/' -LicenseName 'Apache 2.0' ` + -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' -ContactName 'API Support' -ContactEmail 'apiteam@swagger.io' -DefinitionTag 'v3.1' + +Add-PodeOAServerEndpoint -url '/api/v3' -Description 'default endpoint' -DefinitionTag 'v3', 'v3.1' + +#OpenAPI 3.0 +Enable-PodeOAViewer -Type Swagger -Path '/docs/swagger' -DefinitionTag 'v3' +Enable-PodeOAViewer -Type Bookmarks -Path '/docs' -DefinitionTag 'v3' + +#OpenAPI 3.1 +Enable-PodeOAViewer -Type Swagger -Path '/docs/v3.1/swagger' -DefinitionTag 'v3.1' +Enable-PodeOAViewer -Type ReDoc -Path '/docs/v3.1/redoc' -DarkMode -DefinitionTag 'v3.1' +Enable-PodeOAViewer -Type Bookmarks -Path '/docs/v3.1' -DefinitionTag 'v3.1' + +Select-PodeOADefinition -Tag 'v3', 'v3.1' -ScriptBlock { + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 10 -Required | + New-PodeOAStringProperty -Name 'name' -Example 'doggie' -Required | + New-PodeOASchemaProperty -Name 'category' -Reference 'Category' | + New-PodeOAStringProperty -Name 'photoUrls' -Array -XmlWrapped -XmlItemName 'photoUrl' -Required | + New-PodeOASchemaProperty -Name 'tags' -Reference 'Tag' -Array -XmlWrapped | + New-PodeOAStringProperty -Name 'status' -Description 'pet status in the store' -Enum @('available', 'pending', 'sold') | + New-PodeOAObjectProperty -XmlName 'pet' | + Add-PodeOAComponentSchema -Name 'Pet' + + + Add-PodeRouteGroup -Path '/api/v3' -Routes { + Add-PodeRoute -PassThru -Method Put -Path '/pet' -Authentication 'merged_auth_nokey' -Scope 'write:pets', 'read:pets' -ScriptBlock { + #code + } | Set-PodeOARouteInfo -Summary 'Update an existing pet' -Description 'Update an existing pet by Id' -Tags 'pet' -OperationId 'updatePet' -PassThru | + Set-PodeOARequest -RequestBody ( + New-PodeOARequestBody -Description 'Update an existent pet in the store' -Required -Content ( + New-PodeOAContentMediaType -ContentMediaType 'application/json', 'application/xml' -Content 'Pet' ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -ContentMediaType 'application/json', 'application/xml' -Content 'Pet' ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Pet not found' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Validation exception' + } +} +``` diff --git a/docs/Tutorials/OpenAPI/Specification/v3.0.3.md b/docs/Tutorials/OpenAPI/Specification/v3.0.3.md new file mode 100644 index 000000000..a296af9c2 --- /dev/null +++ b/docs/Tutorials/OpenAPI/Specification/v3.0.3.md @@ -0,0 +1,4264 @@ +# OpenAPI v.3.0.3 Specification and Pode + +#### OpenAPI Version 3.0.3 and Pode 2.10.0 + +The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [BCP 14](https://tools.ietf.org/html/bcp14) [RFC2119](https://tools.ietf.org/html/rfc2119) [RFC8174](https://tools.ietf.org/html/rfc8174) when, and only when, they appear in all capitals, as shown here. + +This document is licensed under [The Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0.html). + +## Introduction + +The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. + +An OpenAPI definition can then be used by documentation generation tools to display the API, code generation tools to generate servers and clients in various programming languages, testing tools, and many other use cases. + + +## Table of Contents + + +- [Definitions](#definitions) + - [OpenAPI Document](#oasDocument) + - [Path Templating](#pathTemplating) + - [Media Types](#mediaTypes) + - [HTTP Status Codes](#httpCodes) +- [Specification](#specification) + - [Versions](#versions) + - [Format](#format) + - [Document Structure](#documentStructure) + - [Data Types](#dataTypes) + - [Rich Text Formatting](#richText) + - [Relative References In URLs](#relativeReferences) + - [Schema](#schema) + - [OpenAPI Object](#oasObject) + - [Info Object](#infoObject) + - [Contact Object](#contactObject) + - [License Object](#licenseObject) + - [Server Object](#serverObject) + - [Server Variable Object](#serverVariableObject) + - [Components Object](#componentsObject) + - [Paths Object](#pathsObject) + - [Path Item Object](#pathItemObject) + - [Operation Object](#operationObject) + - [External Documentation Object](#externalDocumentationObject) + - [Parameter Object](#parameterObject) + - [Request Body Object](#requestBodyObject) + - [Media Type Object](#mediaTypeObject) + - [Encoding Object](#encodingObject) + - [Responses Object](#responsesObject) + - [Response Object](#responseObject) + - [Callback Object](#callbackObject) + - [Example Object](#exampleObject) + - [Link Object](#linkObject) + - [Header Object](#headerObject) + - [Tag Object](#tagObject) + - [Reference Object](#referenceObject) + - [Schema Object](#schemaObject) + - [Discriminator Object](#discriminatorObject) + - [XML Object](#xmlObject) + - [Security Scheme Object](#securitySchemeObject) + - [OAuth Flows Object](#oauthFlowsObject) + - [OAuth Flow Object](#oauthFlowObject) + - [Security Requirement Object](#securityRequirementObject) + - [Specification Extensions](#specificationExtensions) + - [Security Filtering](#securityFiltering) +- [Appendix A: Revision History](#revisionHistory) + + + + +## Definitions + +##### OpenAPI Document +A document (or set of documents) that defines or describes an API. An OpenAPI definition uses and conforms to the OpenAPI Specification. + +##### Path Templating +Path templating refers to the usage of template expressions, delimited by curly braces ({}), to mark a section of a URL path as replaceable using path parameters. + +Each template expression in the path MUST correspond to a path parameter that is included in the [Path Item](#path-item-object) itself and/or in each of the Path Item's [Operations](#operation-object). + +##### Media Types +Media type definitions are spread across several resources. +The media type definitions SHOULD be in compliance with [RFC6838](https://tools.ietf.org/html/rfc6838). + +Some examples of possible media type definitions: +``` + text/plain; charset=utf-8 + application/json + application/vnd.github+json + application/vnd.github.v3+json + application/vnd.github.v3.raw+json + application/vnd.github.v3.text+json + application/vnd.github.v3.html+json + application/vnd.github.v3.full+json + application/vnd.github.v3.diff + application/vnd.github.v3.patch +``` +##### HTTP Status Codes +The HTTP Status Codes are used to indicate the status of the executed operation. +The available status codes are defined by [RFC7231](https://tools.ietf.org/html/rfc7231#section-6) and registered status codes are listed in the [IANA Status Code Registry](https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml). + +## OpenAPI Features Unsupported by Pode + + - Relative Schema Document Example + +## Specification + +### Versions + +The OpenAPI Specification is versioned using [Semantic Versioning 2.0.0](https://semver.org/spec/v2.0.0.html) (semver) and follows the semver specification. + +The `major`.`minor` portion of the semver (for example `3.0`) SHALL designate the OAS feature set. Typically, *`.patch`* versions address errors in this document, not the feature set. Tooling which supports OAS 3.0 SHOULD be compatible with all OAS 3.0.\* versions. The patch version SHOULD NOT be considered by tooling, making no distinction between `3.0.0` and `3.0.1` for example. + +Each new minor version of the OpenAPI Specification SHALL allow any OpenAPI document that is valid against any previous minor version of the Specification, within the same major version, to be updated to the new Specification version with equivalent semantics. Such an update MUST only require changing the `openapi` property to the new minor version. + +For example, a valid OpenAPI 3.0.2 document, upon changing its `openapi` property to `3.1.0`, SHALL be a valid OpenAPI 3.1.0 document, semantically equivalent to the original OpenAPI 3.0.2 document. New minor versions of the OpenAPI Specification MUST be written to ensure this form of backward compatibility. + +An OpenAPI document compatible with OAS 3.\*.\* contains a required [`openapi`](#oasVersion) field which designates the semantic version of the OAS that it uses. (OAS 2.0 documents contain a top-level version field named [`swagger`](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swaggerObject) and value `"2.0"`.) + +### Format + +An OpenAPI document that conforms to the OpenAPI Specification is itself a JSON object, which may be represented either in JSON or YAML format. + +For example, if a field has an array value, the JSON array representation will be used: + +```json +{ + "field": [ 1, 2, 3 ] +} +``` +All field names in the specification are **case sensitive**. +This includes all fields that are used as keys in a map, except where explicitly noted that keys are **case insensitive**. + +The schema exposes two types of fields: Fixed fields, which have a declared name, and Patterned fields, which declare a regex pattern for the field name. + +Patterned fields MUST have unique names within the containing object. + +In order to preserve the ability to round-trip between YAML and JSON formats, YAML version [1.2](https://yaml.org/spec/1.2/spec.html) is RECOMMENDED along with some additional constraints: + +- Tags MUST be limited to those allowed by the [JSON Schema ruleset](https://yaml.org/spec/1.2/spec.html#id2803231). +- Keys used in YAML maps MUST be limited to a scalar string, as defined by the [YAML Failsafe schema ruleset](https://yaml.org/spec/1.2/spec.html#id2802346). + +**Note:** While APIs may be defined by OpenAPI documents in either YAML or JSON format, the API request and response bodies and other content are not required to be JSON or YAML. + +### Document Structure + +An OpenAPI document MAY be made up of a single document or be divided into multiple, connected parts at the discretion of the user. In the latter case, `$ref` fields MUST be used in the specification to reference those parts as follows from the [JSON Schema](https://json-schema.org) definitions. + +It is RECOMMENDED that the root OpenAPI document be named: `openapi.json` or `openapi.yaml`. + +### Data Types + +Primitive data types in the OAS are based on the types supported by the [JSON Schema Specification Wright Draft 00](https://tools.ietf.org/html/draft-wright-json-schema-00#section-4.2). +Note that `integer` as a type is also supported and is defined as a JSON number without a fraction or exponent part. +`null` is not supported as a type (see [`nullable`](#schemaNullable) for an alternative solution). +Models are defined using the [Schema Object](#schemaObject), which is an extended subset of JSON Schema Specification Wright Draft 00. + +Primitives have an optional modifier property: `format`. +OAS uses several known formats to define in fine detail the data type being used. +However, to support documentation needs, the `format` property is an open `string`-valued property, and can have any value. +Formats such as `"email"`, `"uuid"`, and so on, MAY be used even though undefined by this specification. +Types that are not accompanied by a `format` property follow the type definition in the JSON Schema. Tools that do not recognize a specific `format` MAY default back to the `type` alone, as if the `format` is not specified. + +The formats defined by the OAS are: + +| [`type`](#dataTypes) | [`format`](#dataTypeFormat) | [`Pode CmdLet`](https://badgerati.github.io/Pode/Tutorials/OpenAPI/) | Comments | +| -------------------- | --------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | +| `integer` | `int32` | [`New-PodeOAIntProperty -Name 'anInteger' -Format Int32`] | signed 32 bits | +| `integer` | `int64` | [`New-PodeOAIntProperty -Name 'aLong' -Format Int64`] | signed 64 bits (a.k.a long) | +| `number` | `float` | [`New-PodeOANumberProperty -Name 'aFloat' -Format Float`] | +| `number` | `double` | [`New-PodeOANumberProperty -Name 'aDouble' -Format Double`] | +| `string` | | [`New-PodeOAStringProperty -Name 'aString'`] | +| `string` | `byte` | [`New-PodeOAStringProperty -Name 'aString' -Format Byte`] | base64 encoded characters | +| `string` | `binary` | [`New-PodeOAStringProperty -Name 'aString' -Format Binary`] | any sequence of octets | +| `boolean` | | [`New-PodeOABoolProperty -Name 'aBoolean'`] | +| `string` | `date` | [`New-PodeOAStringProperty -Name 'aDate' -Format Date`] | As defined by `full-date` - [RFC3339](https://datatracker.ietf.org/doc/html/rfc3339#section-5.6) | +| `string` | `date-time` | [`New-PodeOAStringProperty -Name 'aDate' -Format Date-Time`] | As defined by `date-time` - [RFC3339](https://datatracker.ietf.org/doc/html/rfc3339#section-5.6) | +| `string` | `password` | [`New-PodeOAStringProperty -Name 'aDate' -Format Password`] | A hint to UIs to obscure input. | + + +### Rich Text Formatting +Throughout the specification `description` fields are noted as supporting CommonMark markdown formatting. +Where OpenAPI tooling renders rich text it MUST support, at a minimum, markdown syntax as described by [CommonMark 0.27](https://spec.commonmark.org/0.27/). Tooling MAY choose to ignore some CommonMark features to address security concerns. + +### Relative References in URLs + +Unless specified otherwise, all properties that are URLs MAY be relative references as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-4.2). +Relative references are resolved using the URLs defined in the [`Server Object`](#serverObject) as a Base URI. + +Relative references used in `$ref` are processed as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03), using the URL of the current document as the base URI. See also the [Reference Object](#referenceObject). + +### Schema + +In the following description, if a field is not explicitly **REQUIRED** or described with a MUST or SHALL, it can be considered OPTIONAL. + +#### OpenAPI Object + +This is the root document object of the [OpenAPI document](#oasDocument). + +##### Fixed Fields + +| Field Name | Type | Pode CmdLets | Description | +| ------------------------------------------ | :-----------------------------------------------------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| openapi | `string` | [`Enable-PodeOpenApi`](../../../../Functions/OpenApi/Enable-PodeOpenApi) | **REQUIRED**. This string MUST be the [semantic version number](https://semver.org/spec/v2.0.0.html) of the [OpenAPI Specification version](#versions) that the OpenAPI document uses. The `openapi` field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document. This is *not* related to the API [`info.version`](#infoVersion) string. | +| info | [Info Object](#infoObject) | [`Add-PodeOAInfo`](../../../../Functions/OpenApi/Add-PodeOAInfo) | **REQUIRED**. Provides metadata about the API. The metadata MAY be used by tooling as required. | +| servers | [[Server Object](#serverObject)] | [`Add-PodeOAServerEndpoint`](../../../../Functions/OpenApi/Add-PodeOAServerEndpoint) | An array of Server Objects, which provide connectivity information to a target server. If the `servers` property is not provided, or is an empty array, the default value would be a [Server Object](#serverObject) with a [url](#serverUrl) value of `/`. | +| paths | [Paths Object](#pathsObject) | [`Add-PodeRoute`](../../../../Functions/Routes/Add-PodeRoute)
[`Set-PodeOARouteInfo`](../../../../Functions/OpenApi/Set-PodeOARouteInfo) | **REQUIRED**. The available paths and operations for the API. | +| components | [Components Object](#componentsObject) | [`Add-PodeOAComponentHeader`](../../../../Functions/OAComponents/Add-PodeOAComponentHeader)
[`Add-PodeOAComponentResponse`](../../../../Functions/OAComponents/Add-PodeOAComponentResponse)
[`Add-PodeOAComponentRequestBody`](../../../../Functions/OAComponents/Add-PodeOAComponentRequestBody)
[`Add-PodeOAComponentParameter`](../../../../Functions/OAComponents/Add-PodeOAComponentParameter)
[`Add-PodeOAComponentSchema`](../../../../Functions/OAComponents/Add-PodeOAComponentSchema)
[`Add-PodeOAComponentResponseLink`](../../../../Functions/OAComponents/Add-PodeOAComponentResponseLink)
[`Add-PodeOAComponentCallBack`](../../../../Functions/OAComponents/Add-PodeOAComponentCallBack) | An element to hold various schemas for the specification. | +| security | [[Security Requirement Object](#securityRequirementObject)] | [`New-PodeAuthScheme`](../../../../Functions/Authentication/New-PodeAuthScheme)
[`Merge-PodeAuthScheme`](../../../../Functions//Merge-PodeAuthScheme)
[`Add-PodeRoute`](../../../../Functions/Routes/Add-PodeRoute)
| A declaration of which security mechanisms can be used across the API. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. Individual operations can override this definition. To make security optional, an empty security requirement (`{}`) can be included in the array. | +| tags | [[Tag Object](#tagObject)] | [`Add-PodeOATag`](../../../../Functions/OpenApi/Add-PodeOATag)
[`Set-PodeOARouteInfo`](../../../../Functions/OpenApi/Set-PodeOARouteInfo) | A list of tags used by the specification with additional metadata. The order of the tags can be used to reflect on their order by the parsing tools. Not all tags that are used by the [Operation Object](#operationObject) must be declared. The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique. | +| externalDocs | [External Documentation Object](#externalDocumentationObject) | [`Add-PodeOAExternalDoc`](../../../../Functions/OpenApi/Add-PodeOAExternalDoc)
[`New-PodeOAExternalDoc`](../../../../Functions/OpenApi/New-PodeOAExternalDoc) | Additional external documentation. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### Info Object + +The object provides metadata about the API. +The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. + +##### Fixed Fields + +| Field Name | Type | `Add-PodeOAInfo` | Description | +| ----------------------------------------------- | :------------------------------: | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| title | `string` | `-Title` | **REQUIRED**. The title of the API. | +| description | `string` | `-Description` | A short description of the API. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| termsOfService | `string` | `-TermOfService` | A URL to the Terms of Service for the API. MUST be in the format of a URL. | +| contact | [Contact Object](#contactObject) | `-ContactName` `-ContactEmail` `-ContactUrl` | The contact information for the exposed API. | +| license | [License Object](#licenseObject) | `-LicenseName` `-LicenseUrl` | The license information for the exposed API. | +| version | `string` | `-Version` | **REQUIRED**. The version of the OpenAPI document (which is distinct from the [OpenAPI Specification version](#oasVersion) or the API implementation version). | + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Info Object Example +```Powershell +Add-PodeOAInfo -Title 'Sample Pet Store App' -Version 1.0.1 -Description 'This is a sample server for a pet store.' ` + -TermsOfService 'http://example.com/terms/' -LicenseName 'Apache 2.0' ` + -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' -ContactName 'API Support' ` + -ContactEmail 'support@example.com' -ContactUrl 'http://example.com/support' +``` + +```json +{ + "title": "Sample Pet Store App", + "description": "This is a sample server for a pet store.", + "termsOfService": "http://example.com/terms/", + "contact": { + "name": "API Support", + "url": "http://www.example.com/support", + "email": "support@example.com" + }, + "license": { + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html" + }, + "version": "1.0.1" +} +``` + +```yaml +title: Sample Pet Store App +description: This is a sample server for a pet store. +termsOfService: http://example.com/terms/ +contact: + name: API Support + url: http://www.example.com/support + email: support@example.com +license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html +version: 1.0.1 +``` + + + +#### Contact Object + +Contact information for the exposed API. + +##### Fixed Fields + +| Field Name | Type | `Add-PodeOAInfo` | Description | +| -------------------------------- | :------: | ---------------- | ------------------------------------------------------------------------------------------------ | +| name | `string` | `-ContactName` | The identifying name of the contact person/organization. | +| url | `string` | `-ContactUrl` | The URL pointing to the contact information. MUST be in the format of a URL. | +| email | `string` | `-ContactEmail` | The email address of the contact person/organization. MUST be in the format of an email address. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Contact Object Example + +```Powershell +Add-PodeOAInfo -ContactName 'API Support' -ContactUrl 'http://example.com/support' -ContactEmail 'support@example.com' +``` + +```json +{ + "name": "API Support", + "url": "http://www.example.com/support", + "email": "support@example.com" +} +``` + +```yaml +name: API Support +url: http://www.example.com/support +email: support@example.com +``` + +#### License Object + +License information for the exposed API. + +##### Fixed Fields + +| Field Name | Type | `Add-PodeOAInfo` | Description | +| ------------------------------ | :------: | ---------------- | ---------------------------------------------------------------------- | +| name | `string` | `-LicenseName` | **REQUIRED**. The license name used for the API. | +| url | `string` | `-LicenseUrl` | A URL to the license used for the API. MUST be in the format of a URL. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### License Object Example +```Powershell +Add-PodeOAInfo -LicenseName 'Apache 2.0' -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' +``` + +```json +{ + "name": "Apache 2.0", + "url": "https://www.apache.org/licenses/LICENSE-2.0.html" +} +``` + +```yaml +name: Apache 2.0 +url: https://www.apache.org/licenses/LICENSE-2.0.html +``` + +#### Server Object + +An object representing a Server. + +##### Fixed Fields + +| Field Name | Type | `Add-PodeOAServerEndpoint` | Description | +| ------------------------------------------- | :------------------------------------------------------------: | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| url | `string` | `-Url` | **REQUIRED**. A URL to the target host. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in `{`brackets`}`. | +| description | `string` | `-Description` | An optional string describing the host designated by the URL. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| variables | Map[`string`, [Server Variable Object](#serverVariableObject)] | `-Variable` | A map between a variable name and its value. The value is used for substitution in the server's URL template. In Pode the OpenAPI Object's [`servers`](#oasServers) with variables can be defined using a `[ordered]@{}` [System.Collections.Specialized.OrderedDictionary](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary?view=net-7.0) | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Server Object Example + +A single server would be described as: + +```Powershell +Add-PodeOAServerEndpoint -Url 'https://development.gigantic-server.com/v1' -Description 'Development server' +``` + +```json +{ + "url": "https://development.gigantic-server.com/v1", + "description": "Development server" +} +``` + +```yaml +url: https://development.gigantic-server.com/v1 +description: Development server +``` + + + +The following shows how multiple servers can be described, for example, at the OpenAPI Object's [`servers`](#oasServers): +```Powershell +Add-PodeOAServerEndpoint -url 'https://development.gigantic-server.com/v1' -Description 'Development server' +Add-PodeOAServerEndpoint -url 'https://staging.gigantic-server.com/v1' -Description 'Staging server' +Add-PodeOAServerEndpoint -url 'https://api.gigantic-server.com/v1' -Description 'Production server' +``` +```json +{ + "servers": [ + { + "url": "https://development.gigantic-server.com/v1", + "description": "Development server" + }, + { + "url": "https://staging.gigantic-server.com/v1", + "description": "Staging server" + }, + { + "url": "https://api.gigantic-server.com/v1", + "description": "Production server" + } + ] +} +``` + +```yaml +servers: +- url: https://development.gigantic-server.com/v1 + description: Development server +- url: https://staging.gigantic-server.com/v1 + description: Staging server +- url: https://api.gigantic-server.com/v1 + description: Production server +``` + + + +The following shows how variables can be used for a server configuration: + +```Powershell +Add-PodeOAServerEndpoint -Url "https://{username}.gigantic-server.com:{port}/{basePath}" ` + -Description "The production API server" -Variable $( + [ordered]@{ + username = @{ + default = 'demo' + description = 'this value is assigned by the service provider, in this example gigantic-server.com' + } + port = @{ + enum = @( 8443, 443 ) + default = 8443 + } + basePath = @{ + default = 'v2' + } + }) +``` +```json +{ + "servers": [ + { + "url": "https://{username}.gigantic-server.com:{port}/{basePath}", + "description": "The production API server", + "variables": { + "username": { + "default": "demo", + "description": "this value is assigned by the service provider, in this example `gigantic-server.com`" + }, + "port": { + "enum": [ + "8443", + "443" + ], + "default": "8443" + }, + "basePath": { + "default": "v2" + } + } + } + ] +} +``` + +```yaml +servers: +- url: https://{username}.gigantic-server.com:{port}/{basePath} + description: The production API server + variables: + username: + # note! no enum here means it is an open value + default: demo + description: this value is assigned by the service provider, in this example `gigantic-server.com` + port: + enum: + - '8443' + - '443' + default: '8443' + basePath: + # open meaning there is the opportunity to use special base paths as assigned by the provider, default is `v2` + default: v2 +``` + + +#### Server Variable Object + +An object representing a Server Variable for server URL template substitution. + +##### Fixed Fields + +| Field Name | Type | Description | +| --------------------------------------------------- | :--------: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| enum | [`string`] | An enumeration of string values to be used if the substitution options are from a limited set. The array SHOULD NOT be empty. | +| default | `string` | **REQUIRED**. The default value to use for substitution, which SHALL be sent if an alternate value is _not_ supplied. Note this behavior is different than the [Schema Object's](#schemaObject) treatment of default values, because in those cases parameter values are optional. If the [`enum`](#serverVariableEnum) is defined, the value SHOULD exist in the enum's values. | +| description | `string` | An optional description for the server variable. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### Components Object + +Holds a set of reusable objects for different aspects of the OAS. +All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. + + +##### Fixed Fields + +| Field Name | Type | Pode | Description | +| -------------------------------------------------------- | :----------------------------------------------------------------------------------------------------- | ----------------------------------- | ---------------------------------------------------------------------------- | +| schemas | Map[`string`, [Schema Object](#schemaObject) \| [Reference Object](#referenceObject)] | [`Add-PodeOAComponentSchema`](../../../../Functions/OAComponents/Add-PodeOAComponentSchema) | An object to hold reusable [Schema Objects](#schemaObject). | +| responses | Map[`string`, [Response Object](#responseObject) \| [Reference Object](#referenceObject)] | [`Add-PodeOAComponentResponse`](../../../../Functions/OAComponents/Add-PodeOAComponentResponse) | An object to hold reusable [Response Objects](#responseObject). | +| parameters | Map[`string`, [Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | [`Add-PodeOAComponentParameter`](../../../../Functions/OAComponents/Add-PodeOAComponentParameter) | An object to hold reusable [Parameter Objects](#parameterObject). | PodeOAComponentExample | +| examples | Map[`string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | [`Add-PodeOAComponentExample`](../../../../Functions/OAComponents/Add-PodeOAComponentExample) | An object to hold reusable [Example Objects](#exampleObject). | +| requestBodies | Map[`string`, [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject)] | [`Add-PodeOAComponentRequestBody`](../../../../Functions/OAComponents/Add-PodeOAComponentRequestBody) | An object to hold reusable [Request Body Objects](#requestBodyObject). | +| headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | [`Add-PodeOAComponentHeader`](../../../../Functions/OAComponents/Add-PodeOAComponentHeader) | An object to hold reusable [Header Objects](#headerObject). | +| securitySchemes | Map[`string`, [Security Scheme Object](#securitySchemeObject) \| [Reference Object](#referenceObject)] | [`New-PodeAuthScheme`](../../../../Functions/Authentication/New-PodeAuthScheme) | An object to hold reusable [Security Scheme Objects](#securitySchemeObject). | +| links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | [`Add-PodeOAComponentResponseLink`](../../../../Functions/OAComponents/Add-PodeOAComponentResponseLink) | An object to hold reusable [Link Objects](#linkObject). | +| callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | [`Add-PodeOAComponentCallBack`](../../../../Functions/OAComponents/Add-PodeOAComponentCallBack) | An object to hold reusable [Callback Objects](#callbackObject). | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +All the fixed fields declared above are objects that MUST use keys that match the regular expression: `^[a-zA-Z0-9\.\-_]+$`. + +Field Name Examples: + +``` +User +User_1 +User_Name +user-name +my.org.User +``` + +##### Components Object Example +```powershell +New-PodeOAIntProperty -Name 'code' -Format Int32 | + New-PodeOAStringProperty -Name 'message' | + New-PodeOAObjectProperty | + Add-PodeOAComponentSchema -Name 'GeneralError' + +New-PodeOAStringProperty -Name 'name' | + New-PodeOAIntProperty -Name 'id' -Format Int64 | + New-PodeOAObjectProperty | + Add-PodeOAComponentSchema -Name 'Category' + +New-PodeOAStringProperty -Name 'name' | + New-PodeOAIntProperty -Name 'id' -Format Int64 | + New-PodeOAObjectProperty | + Add-PodeOAComponentSchema -Name 'Tag' + +Add-PodeOAComponentParameter -Name 'skipParam' -Parameter ( + New-PodeOAIntProperty -Name 'skip' -Format int32 -Description 'number of items to skip' -Required | + ConvertTo-PodeOAParameter -In Query +) + +Add-PodeOAComponentParameter -Name 'limitParam' -Parameter ( + New-PodeOAIntProperty -Name 'limit' -Format int32 -Description 'max records to return' -Required | + ConvertTo-PodeOAParameter -In Query +) + +Add-PodeOAComponentResponse -Name 'NotFound' -Description 'Entity not found.' +Add-PodeOAComponentResponse -Name 'IllegalInput' -Description 'Illegal input for operation.' +Add-PodeOAComponentResponse -Name 'GeneralError' -Description 'General Error' ` + -Content (@{'application/json' = 'GeneralError'}) + +New-PodeAuthScheme -ApiKey -Location Header | Add-PodeAuth -Name 'api_key' -Sessionless -ScriptBlock { + param($key) + #logic goes here +} + +New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'read:pets' -Description 'read your pets' +New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'write:pets' -Description 'modify pets in your account' + +New-PodeAuthScheme -OAuth2 -ClientId $ClientId -ClientSecret $ClientSecret -AuthoriseUrl "http://example.org/api/oauth/dialog" ` + -TokenUrl 'http://example.org/api/oauth/token' -Scope 'read:pets', 'write:pets' | + Add-PodeAuth -Name 'petstore_auth' -FailureUrl 'http://example.org/api/oauth/dialog' -SuccessUrl '/' -ScriptBlock { + param($user, $accessToken, $refreshToken) + return @{ User = $user } + } +``` +```json +"components": { + "schemas": { + "GeneralError": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + } + }, + "parameters": { + "skipParam": { + "name": "skip", + "in": "query", + "description": "number of items to skip", + "required": true, + "schema": { + "type": "integer", + "format": "int32" + } + }, + "limitParam": { + "name": "limit", + "in": "query", + "description": "max records to return", + "required": true, + "schema" : { + "type": "integer", + "format": "int32" + } + } + }, + "responses": { + "NotFound": { + "description": "Entity not found." + }, + "IllegalInput": { + "description": "Illegal input for operation." + }, + "GeneralError": { + "description": "General Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GeneralError" + } + } + } + } + }, + "securitySchemes": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "flows": { + "password": { + "authorizationUrl": "http://example.org/api/oauth/dialog", + "tokenUrl": "http://example.org/api/oauth/token", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } + } + } +} +``` + +```yaml +components: + schemas: + GeneralError: + type: object + properties: + code: + type: integer + format: int32 + message: + type: string + Category: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + parameters: + skipParam: + name: skip + in: query + description: number of items to skip + required: true + schema: + type: integer + format: int32 + limitParam: + name: limit + in: query + description: max records to return + required: true + schema: + type: integer + format: int32 + responses: + NotFound: + description: Entity not found. + IllegalInput: + description: Illegal input for operation. + GeneralError: + description: General Error + content: + application/json: + schema: + $ref: '#/components/schemas/GeneralError' + securitySchemes: + api_key: + type: apiKey + name: api_key + in: header + petstore_auth: + type: oauth2 + flows: + password: + authorizationUrl: http://example.org/api/oauth/dialog + tokenUrl: http://example.org/api/oauth/token + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + + +#### Paths Object + +Holds the relative paths to the individual endpoints and their operations. +The path is appended to the URL from the [`Server Object`](#serverObject) in order to construct the full URL. The Paths MAY be empty, due to [ACL constraints](#securityFiltering). + +##### Patterned Fields + +| Field Pattern | Type | Description | +| ------------------------------- | :---------------------------------: | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| /{path} | [Path Item Object](#pathItemObject) | A relative path to an individual endpoint. The field name MUST begin with a forward slash (`/`). The path is **appended** (no relative URL resolution) to the expanded URL from the [`Server Object`](#serverObject)'s `url` field in order to construct the full URL. [Path templating](#pathTemplating) is allowed. When matching URLs, concrete (non-templated) paths would be matched before their templated counterparts. Templated paths with the same hierarchy but different templated names MUST NOT exist as they are identical. In case of ambiguous matching, it's up to the tooling to decide which one to use. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Path Templating Matching + +Assuming the following paths, the concrete definition, `/pets/mine`, will be matched first if used: + +``` + /pets/{petId} + /pets/mine +``` + +The following paths are considered identical and invalid: + +``` + /pets/{petId} + /pets/{name} +``` + +The following may lead to ambiguous resolution: + +``` + /{entity}/me + /books/{id} +``` + +##### Paths Object Example + +```powershell + Add-PodeRoute -PassThru -Method Get -Path '/pets' -ScriptBlock { + Write-PodeJsonResponse -Value (Get-Pets -All) -StatusCode 200 + } | Set-PodeOARouteInfo -Description 'Returns all pets from the system that the user has access to' -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'A list of pets.' -Default -Content (@{ 'application/json' = New-PodeOASchemaProperty -Reference 'Pet' -array }) + +``` + +```json +{ + "/pets": { + "get": { + "description": "Returns all pets from the system that the user has access to", + "responses": { + "200": { + "description": "A list of pets.", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/pet" + } + } + } + } + } + } + } + } +} +``` + +```yaml +/pets: + get: + description: Returns all pets from the system that the user has access to + responses: + '200': + description: A list of pets. + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/pet' +``` + +#### Path Item Object + +Describes the operations available on a single path. +A Path Item MAY be empty, due to [ACL constraints](#securityFiltering). +The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. + +##### Fixed Fields + +| Field Name | Type | Description | +| --------------------------------------------- | :----------------------------------------------------------------------------: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| $ref | `string` | (Unsupported by Pode) Allows for an external definition of this path item. The referenced structure MUST be in the format of a [Path Item Object](#pathItemObject). In case a Path Item Object field appears both in the defined object and the referenced object, the behavior is undefined. | +| summary | `string` | An optional, string summary, intended to apply to all operations in this path. | +| description | `string` | An optional, string description, intended to apply to all operations in this path. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| get | [Operation Object](#operationObject) | A definition of a GET operation on this path. | +| put | [Operation Object](#operationObject) | A definition of a PUT operation on this path. | +| post | [Operation Object](#operationObject) | A definition of a POST operation on this path. | +| delete | [Operation Object](#operationObject) | A definition of a DELETE operation on this path. | +| options | [Operation Object](#operationObject) | A definition of a OPTIONS operation on this path. | +| head | [Operation Object](#operationObject) | A definition of a HEAD operation on this path. | +| patch | [Operation Object](#operationObject) | A definition of a PATCH operation on this path. | +| trace | [Operation Object](#operationObject) | A definition of a TRACE operation on this path. | +| servers | [[Server Object](#serverObject)] | An alternative `server` array to service all operations in this path. | +| parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). | + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Path Item Object Example +```powershell +Add-PodeRoute -PassThru -Method Get -Path '/peta/:id' -ScriptBlock { + Write-PodeJsonResponse -Value (Get-Pet -Id $WebEvent.Parameters['id']) -StatusCode 200 + } | + Set-PodeOARouteInfo -Summary 'Find pets by ID' -Description 'Returns pets based on ID' -OperationId 'getPetsById' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + (New-PodeOAStringProperty -Name 'id' -Description 'ID of pet to use' -array | ConvertTo-PodeOAParameter -In Path -Style Simple -Required )) | + Add-PodeOAResponse -StatusCode 200 -Description 'pet response' -Content (@{ '*/*' = New-PodeOASchemaProperty -Reference 'Pet' -array }) -PassThru | + Add-PodeOAResponse -Default -Description 'error payload' -Content (@{'text/html' = 'ErrorModel' }) -PassThru +``` +```json +{ + "get": { + "description": "Returns pets based on ID", + "summary": "Find pets by ID", + "operationId": "getPetsById", + "responses": { + "200": { + "description": "pet response", + "content": { + "*/*": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Pet" + } + } + } + } + }, + "default": { + "description": "error payload", + "content": { + "text/html": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } + } + }, + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to use", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "simple" + } + ] +} +``` + +```yaml +get: + description: Returns pets based on ID + summary: Find pets by ID + operationId: getPetsById + responses: + '200': + description: pet response + content: + '*/*' : + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + default: + description: error payload + content: + 'text/html': + schema: + $ref: '#/components/schemas/ErrorModel' +parameters: +- name: id + in: path + description: ID of pet to use + required: true + schema: + type: array + items: + type: string + style: simple +``` + +##### Path Item Object Example with External Servers + +```powershell +Add-PodeOAExternalRoute -PassThru -Method Get -Path '/peta/:id' -Servers ( + New-PodeOAServerEndpoint -Url 'http://ext.server.com/api/v12' -Description 'ext test server' | + New-PodeOAServerEndpoint -Url 'http://ext13.server.com/api/v12' -Description 'ext test server 13' + ) | + Set-PodeOARouteInfo -Summary 'Find pets by ID' -Description 'Returns pets based on ID' ` + -OperationId 'getPetsById' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + (New-PodeOAStringProperty -Name 'id' -Description 'ID of pet to use' -array | ConvertTo-PodeOAParameter -In Path -Style Simple -Required ) + ) | + Add-PodeOAResponse -StatusCode 200 -Description 'pet response' -Content ( + @{ '*/*' = New-PodeOASchemaProperty -Reference 'Pet' -array } + ) -PassThru | + Add-PodeOAResponse -Default -Description 'error payload' -Content ( + @{'text/html' = 'ErrorModel' } + ) +``` + +```json +{ + "get": { + "description": "Returns pets based on ID", + "summary": "Find pets by ID", + "operationId": "getPetsById", + "responses": { + "200": { + "description": "pet response", + "content": { + "*/*": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Pet" + } + } + } + } + }, + "default": { + "description": "error payload", + "content": { + "text/html": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } + } + }, + "servers": [ + { + "description": "ext test server", + "url": "http://ext.server.com/api/v12" + }, + { + "description": "ext test server 13", + "url": "http://ext13.server.com/api/v12" + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "description": "ID of pet to use", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "simple" + } + ] +} +``` + +```yaml +get: + description: Returns pets based on ID + summary: Find pets by ID + operationId: getPetsById + responses: + '200': + description: pet response + content: + '*/*' : + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + default: + description: error payload + content: + 'text/html': + schema: + $ref: '#/components/schemas/ErrorModel' + servers: + - description : ext test server + url : http://ext.server.com/api/v12 + - description : ext test server 13 + url : http://ext13.server.com/api/v12 +parameters: +- name: id + in: path + description: ID of pet to use + required: true + schema: + type: array + items: + type: string + style: simple +``` + +#### Operation Object + +Describes a single API operation on a path. + +##### Fixed Fields +```powershell +# Authentication Login-OAuth2 +New-PodeAuthScheme ` + -OAuth2 ` + -ClientId $ClientId ` + -ClientSecret $ClientSecret ` + -AuthoriseUrl 'http://example.org/api/oauth/dialog' ` + -TokenUrl 'http://example.org/api/oauth/token' ` + -Scope 'read', 'write' | Add-PodeAuth -Name 'Login-OAuth2' -FailureUrl '/LoginOAuth2' -SuccessUrl '/' -ScriptBlock { + param($user, $accessToken, $refreshToken) + return @{ User = $user } + } + +# Reference to external documentation +New-PodeOAExternalDoc -Name 'OpenApiDocs' -Description 'Find out more about OpenApi' ` + -Url 'https://www.openapis.org/' + +# The variable $Route used in this table is defined as: +$Route = Add-PodeRoute -PassThru -Method Get -Path '/pet/:petId' -ScriptBlock { + Write-PodeJsonResponse -Value (Get-Pet -Id $WebEvent.Parameters['id']) -StatusCode 200 + } +``` + +| Field Name | Type | `Set-PodeOARouteInfo` | Description | +| ------------------------------------------------ | :---------------------------------------------------------------------------------------: | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| tags | `string` | `-Tags` | A list of tags for API documentation control. Tags can be used for logical grouping of operations by resources or any other qualifier. | +| summary | `string` | `-Summary` | A short summary of what the operation does. | +| description | `string` | `-Description` | A verbose explanation of the operation behavior. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| externalDocs | [External Documentation Object](#externalDocumentationObject) | `-ExternalDocs` | Additional external documentation for this operation. | +| operationId | `string` | `-OperationId` | Unique string used to identify the operation. The id MUST be unique among all operations described in the API. The operationId value is **case-sensitive**. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. | +| callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | TBD | A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a [Callback Object](#callbackObject) that describes a request that may be initiated by the API provider and the expected responses. | +| deprecated | `boolean` | `-Deprecated` | Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation. Default value is `false`. | +| servers | [[Server Object](#serverObject)] | TBD | An alternative `server` array to service this operation. If an alternative `server` object is specified at the Path Item Object or Root level, it will be overridden by this value. | + +| Field Name | Type | `Set-PodeOARequest` | Description | +| ---------------------------------------------- | :-------------------------------------------------------------------------------: | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| parameters | [[Parameter Object](#parameterObject) \| [Reference Object](#referenceObject)] | `-Parameters` | A list of parameters that are applicable for this operation. If a parameter is already defined at the [Path Item](#pathItemParameters), the new definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). The list can use the [Reference Object](#referenceObject) to link to parameters that are defined at the [OpenAPI Object's components/parameters](#componentsParameters). | +| requestBody | [Request Body Object](#requestBodyObject) \| [Reference Object](#referenceObject) | `-RequestBody` | The request body applicable for this operation. The `requestBody` is only supported in HTTP methods where the HTTP 1.1 specification [RFC7231](https://tools.ietf.org/html/rfc7231#section-4.3.1) has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, `requestBody` SHALL be ignored by consumers. | + + + +| Field Name | Type | `Set-PodeOAResponse` | Description | +| ------------------------------------------ | :----------------------------------: | -------------------- | ------------------------------------------------------------------------------------------------ | +| responses | [Responses Object](#responsesObject) | | **REQUIRED**. The list of possible responses as they are returned from executing this operation. | + + + +| Field Name | Type | `Add-PodeRoute` | Description | +| ---------------------------------------- | :---------------------------------------------------------: | ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| security | [[Security Requirement Object](#securityRequirementObject)] | `-Authentication` `-Scope ` | A declaration of which security mechanisms can be used for this operation. The list of values includes alternative security requirement objects that can be used. Only one of the security requirement objects need to be satisfied to authorize a request. To make security optional, an empty security requirement (`{}`) can be included in the array. This definition overrides any declared top-level [`security`](#oasSecurity). To remove a top-level security declaration, an empty array can be used. | + + +| Field Name | Type | Unsupported | Description | +| ------------------------------------------ | :---------------------------------------------------------------------------------------: | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| callbacks | Map[`string`, [Callback Object](#callbackObject) \| [Reference Object](#referenceObject)] | | A map of possible out-of band callbacks related to the parent operation. The key is a unique identifier for the Callback Object. Each value in the map is a [Callback Object](#callbackObject) that describes a request that may be initiated by the API provider and the expected responses. | +| servers | [[Server Object](#serverObject)] | | An alternative `server` array to service this operation. If an alternative `server` object is specified at the Path Item Object or Root level, it will be overridden by this value. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Operation Object Example +```powershell +Add-PodeRoute -PassThru -Method Put -Path '/pet' -Authentication 'petstore_auth' ` + -Scope 'write:pets', 'read:pets' -ScriptBlock { + $JsonPet = ConvertTo-Json $WebEvent.data + if ( Update-Pet -Id $WebEvent.Parameters['id'] -Data $JsonPet) { + Write-PodeJsonResponse -Value @{} -StatusCode 200 + } else { + Write-PodeJsonResponse -Value @{} -StatusCode 405 + } +} | Set-PodeOARouteInfo -Summary 'Updates a pet in the store with form data' -Tags 'pet' ` + -OperationId 'updatePetWithForm' -PassThru | + Set-PodeOARequest -Parameters ( + (New-PodeOAStringProperty -Name 'petId' -Description 'ID of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Path -Required) + ) -RequestBody ( + New-PodeOARequestBody -Required -Content @{ + 'application/x-www-form-urlencoded' = New-PodeOAObjectProperty -Properties ( + (New-PodeOAStringProperty -Name 'name' -Description 'Updated name of the pet'), + (New-PodeOAStringProperty -Name 'status' -Description 'Updated status of the pet' -Required) + ) + } + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Pet updated.' -Content ( + @{ 'application/json' = '' ; 'application/xml' = '' } + ) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Method Not Allowed' -Content ( + @{ 'application/json' = '' ; 'application/xml' = '' } + ) +``` + +```json +{ + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "operationId": "updatePetWithForm", + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/x-www-form-urlencoded": { + "schema": { + "type": "object", + "properties": { + "name": { + "description": "Updated name of the pet", + "type": "string" + }, + "status": { + "description": "Updated status of the pet", + "type": "string" + } + }, + "required": ["status"] + } + } + } + }, + "responses": { + "200": { + "description": "Pet updated.", + "content": { + "application/json": {}, + "application/xml": {} + } + }, + "405": { + "description": "Method Not Allowed", + "content": { + "application/json": {}, + "application/xml": {} + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] +} +``` + +```yaml +tags: +- pet +summary: Updates a pet in the store with form data +operationId: updatePetWithForm +parameters: +- name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: string +requestBody: + content: + 'application/x-www-form-urlencoded': + schema: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + required: + - status +responses: + '200': + description: Pet updated. + content: + 'application/json': {} + 'application/xml': {} + '405': + description: Method Not Allowed + content: + 'application/json': {} + 'application/xml': {} +security: +- petstore_auth: + - write:pets + - read:pets +``` + +#### External Documentation Object + +Allows referencing an external resource for extended documentation. + +##### Fixed Fields + +| Field Name | Type | `New-PodeOAExternalDoc` | Description | +| ------------------------------------------------ | :------: | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | +| description | `string` | `-Description` | A short description of the target documentation. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| url | `string` | `-Url` | **REQUIRED**. The URL for the target documentation. Value MUST be in the format of a URL. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### External Documentation Object Example +```powershell +$ExampleDoc = New-PodeOAExternalDoc -Description 'Find more info here' -Url 'https://example.com' + +Add-PodeRoute -PassThru -Method Put -Path '/pet' -Authentication 'petstore_auth' -Scope 'write:pets', 'read:pets' -ScriptBlock { # code here + } | Set-PodeOARouteInfo -ExternalDoc 'ExampleDoc' -Summary 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatePetWithForm' -PassThru | # Continue ..... +``` + +```json +{ + "description": "Find more info here", + "url": "https://example.com" +} +``` + +```yaml +description: Find more info here +url: https://example.com +``` + +#### Parameter Object + +Describes a single operation parameter. + +A unique parameter is defined by a combination of a [name](#parameterName) and [location](#parameterIn). + +##### Parameter Locations +There are four possible parameter locations specified by the `in` field: +* path - Used together with [Path Templating](#pathTemplating), where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in `/items/{itemId}`, the path parameter is `itemId`. +* query - Parameters that are appended to the URL. For example, in `/items?id=###`, the query parameter is `id`. +* header - Custom headers that are expected as part of the request. Note that [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. +* cookie - Used to pass a specific cookie value to the API + +##### Fixed Fields + +| Field Name | Type | `ConvertTo-PodeOAParameter` | Description | +| ------------------------------------------------------- | :-------: | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| name | `string` | `-Name` | **REQUIRED**. The name of the parameter. Parameter names are *case sensitive*.
  • If [`in`](#parameterIn) is `"path"`, the `name` field MUST correspond to a template expression occurring within the [path](#pathsPath) field in the [Paths Object](#pathsObject). See [Path Templating](#pathTemplating) for further information.
  • If [`in`](#parameterIn) is `"header"` and the `name` field is `"Accept"`, `"Content-Type"` or `"Authorization"`, the parameter definition SHALL be ignored.
  • For all other cases, the `name` corresponds to the parameter name used by the [`in`](#parameterIn) property.
Note. In Pode if the -Name parameter is not used the name of the Property created by `New-PodeOAIntProperty`, `New-PodeOANumberProperty`, `New-PodeOABoolProperty `, `New-PodeOAStringProperty`, `New-PodeOAObjectProperty` is used. | +| in | `string` | `-In` | **REQUIRED**. The location of the parameter. Possible values are `"query"`, `"header"`, `"path"` or `"cookie"`. | +| description | `string` | `-Description` | A brief description of the parameter. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| required | `boolean` | `-Required` | Determines whether this parameter is mandatory. If the [parameter location](#parameterIn) is `"path"`, this property is **REQUIRED** and its value MUST be `true`. Otherwise, the property MAY be included and its default value is `false`. | +| deprecated | `boolean` | `-Deprecated` | Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. Default value is `false`. | +| allowEmptyValue | `boolean` | `-AllowEmptyValue` | Sets the ability to pass empty-valued parameters. This is valid only for `query` parameters and allows sending a parameter with an empty value. Default value is `false`. If [`style`](#parameterStyle) is used, and if behavior is `n/a` (cannot be serialized), the value of `allowEmptyValue` SHALL be ignored. Use of this property is NOT RECOMMENDED, as it is likely to be removed in a later revision. | + +The rules for serialization of the parameter are specified in one of two ways. +For simpler scenarios, a [`schema`](#parameterSchema) and [`style`](#parameterStyle) can describe the structure and syntax of the parameter. + +| Field Name | Type | `ConvertTo-PodeOAParameter` | Description | +| -------------------------------------------------- | :--------------------------------------------------------------------------------------: | --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| style | `string` | `-Style` | Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of `in`): for `query` - `form`; for `path` - `simple`; for `header` - `simple`; for `cookie` - `form`. | +| explode | `boolean` | `-Explode` | When this is true, parameter values of type `array` or `object` generate separate parameters for each value of the array or key-value pair of the map. For other types of parameters this property has no effect. When [`style`](#parameterStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. | +| allowReserved | `boolean` | `-AllowReserved` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. This property only applies to parameters with an `in` value of `query`. The default value is `false`. | +| schema | [Schema Object](#schemaObject) \| [Reference Object](#referenceObject) | `-Schema` | The schema defining the type used for the parameter. | +| example | Any | `-Example` | Example of the parameter's potential value. The example SHOULD match the specified schema and encoding properties if present. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` that contains an example, the `example` value SHALL _override_ the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary. | +| examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | `-Examples` | Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` that contains an example, the `examples` value SHALL _override_ the example provided by the schema. | + +For more complex scenarios, the [`content`](#parameterContent) property can define the media type and schema of the parameter. +A parameter MUST contain either a `schema` property, or a `content` property, but not both. +When `example` or `examples` are provided in conjunction with the `schema` object, the example MUST follow the prescribed serialization strategy for the parameter. + + +| Field Name | Type | `ConvertTo-PodeOAParameter` | Description | +| -------------------------------------- | :--------------------------------------------------: | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | +| content | Map[`string`, [Media Type Object](#mediaTypeObject)] | `-Content` | A map containing the representations for the parameter. The key is the media type and the value describes it. The map MUST only contain one entry. | + +##### Style Values + +In order to support common ways of serializing simple parameters, a set of `style` values are defined. + +| `style` | [`type`](#dataTypes) | `in` | Comments | +| -------------- | ------------------------------ | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| matrix | `primitive`, `array`, `object` | `path` | Path-style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.7) | +| label | `primitive`, `array`, `object` | `path` | Label style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.5) | +| form | `primitive`, `array`, `object` | `query`, `cookie` | Form style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.8). This option replaces `collectionFormat` with a `csv` (when `explode` is false) or `multi` (when `explode` is true) value from OpenAPI 2.0. | +| simple | `array` | `path`, `header` | Simple style parameters defined by [RFC6570](https://tools.ietf.org/html/rfc6570#section-3.2.2). This option replaces `collectionFormat` with a `csv` value from OpenAPI 2.0. | +| spaceDelimited | `array` | `query` | Space separated array values. This option replaces `collectionFormat` equal to `ssv` from OpenAPI 2.0. | +| pipeDelimited | `array` | `query` | Pipe separated array values. This option replaces `collectionFormat` equal to `pipes` from OpenAPI 2.0. | +| deepObject | `object` | `query` | Provides a simple way of rendering nested objects using form parameters. | + +##### Style Examples + +Assume a parameter named `color` has one of the following values: + +``` + string -> "blue" + array -> ["blue","black","brown"] + object -> { "R": 100, "G": 200, "B": 150 } +``` +The following table shows examples of rendering differences for each value. + +| [`style`](#dataTypeFormat) | `explode` | `empty` | `string` | `array` | `object` | +| -------------------------- | --------- | ------- | ----------- | ----------------------------------- | -------------------------------------- | +| matrix | false | ;color | ;color=blue | ;color=blue,black,brown | ;color=R,100,G,200,B,150 | +| matrix | true | ;color | ;color=blue | ;color=blue;color=black;color=brown | ;R=100;G=200;B=150 | +| label | false | . | .blue | .blue.black.brown | .R.100.G.200.B.150 | +| label | true | . | .blue | .blue.black.brown | .R=100.G=200.B=150 | +| form | false | color= | color=blue | color=blue,black,brown | color=R,100,G,200,B,150 | +| form | true | color= | color=blue | color=blue&color=black&color=brown | R=100&G=200&B=150 | +| simple | false | n/a | blue | blue,black,brown | R,100,G,200,B,150 | +| simple | true | n/a | blue | blue,black,brown | R=100,G=200,B=150 | +| spaceDelimited | false | n/a | n/a | blue%20black%20brown | R%20100%20G%20200%20B%20150 | +| pipeDelimited | false | n/a | n/a | blue\|black\|brown | R\|100\|G\|200\|B\|150 | +| deepObject | true | n/a | n/a | n/a | color[R]=100&color[G]=200&color[B]=150 | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Parameter Object Examples + +A header parameter with an array of 64 bit integer numbers: +```powershell +New-PodeOAIntProperty -Name 'token' -Description 'token to be passed as a header' -Array -Format Int64 | + ConvertTo-PodeOAParameter -In Header -Style Simple -Required +``` +```json +{ + "name": "token", + "in": "header", + "description": "token to be passed as a header", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "integer", + "format": "int64" + } + }, + "style": "simple" +} +``` + +```yaml +name: token +in: header +description: token to be passed as a header +required: true +schema: + type: array + items: + type: integer + format: int64 +style: simple +``` + +A path parameter of a string value: +```powershell +New-PodeOAStringProperty -Name 'username' -Description 'username to fetch' | + ConvertTo-PodeOAParameter -In Path -Required +``` + +```json +{ + "name": "username", + "in": "path", + "description": "username to fetch", + "required": true, + "schema": { + "type": "string" + } +} +``` + +```yaml +name: username +in: path +description: username to fetch +required: true +schema: + type: string +``` + +An optional query parameter of a string value, allowing multiple values by repeating the query parameter: +```powershell +New-PodeOAStringProperty -Name 'id' -Description 'ID of the object to fetch' -Array | + ConvertTo-PodeOAParameter -In Query -Style Form +``` + +```json +{ + "name": "id", + "in": "query", + "description": "ID of the object to fetch", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "string" + } + }, + "style": "form", + "explode": true +} +``` + +```yaml +name: id +in: query +description: ID of the object to fetch +required: false +schema: + type: array + items: + type: string +style: form +explode: true +``` + +A free-form query parameter, allowing undefined parameters of a specific type: + +```powershell +New-PodeOAIntProperty -Name 'freeForm' -Object | + ConvertTo-PodeOAParameter -In Query -Style Form +``` + +```json +{ + "in": "query", + "name": "freeForm", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer" + }, + }, + "style": "form" +} +``` + +```yaml +in: query +name: freeForm +schema: + type: object + additionalProperties: + type: integer +style: form +``` + +A complex parameter using `content` to define serialization: + +```powershell + New-PodeOANumberProperty -Name 'lat' -Required | + New-PodeOANumberProperty -Name 'long' -Required | + New-PodeOAObjectProperty|ConvertTo-PodeOAParameter -In Query -ContentType 'application/json' +``` + +```json +{ + "in": "query", + "name": "coordinates", + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "lat", + "long" + ], + "properties": { + "lat": { + "type": "number" + }, + "long": { + "type": "number" + } + } + } + } + } +} +``` + +```yaml +in: query +name: coordinates +content: + application/json: + schema: + type: object + required: + - lat + - long + properties: + lat: + type: number + long: + type: number +``` + +#### Request Body Object + +Describes a single request body. + +##### Fixed Fields +| Field Name | Type | `New-PodeOARequestBody` | Description | +| ------------------------------------------------ | :--------------------------------------------------: | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| description | `string` | `-Description` | A brief description of the request body. This could contain examples of use. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| content | Map[`string`, [Media Type Object](#mediaTypeObject)] | `-Content` | **REQUIRED**. The content of the request body. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* | +| required | `boolean` | `-Required` | Determines if the request body is required in the request. Defaults to `false`. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Request Body Examples + +A request body with a referenced model definition. +```powershell +New-PodeOARequestBody -Description 'user to add to the system' -Content @{ 'application/json' = 'User'; 'application/xml' = 'User'} -Examples ( + New-PodeOAExample -MediaType 'application/json' -Name 'user' -Summary 'User Example' -ExternalValue 'http://foo.bar/examples/user-example.json' | + New-PodeOAExample -MediaType 'application/xml' -Name 'user' -Summary 'User Example in XML' -ExternalValue 'http://foo.bar/examples/user-example.xml' | + New-PodeOAExample -MediaType 'text/plain' -Name 'user' -Summary 'User Example in Plain text' -ExternalValue 'http://foo.bar/examples/user-example.txt' | + New-PodeOAExample -MediaType '*/*' -Name 'user' -Summary 'User example in other format' -ExternalValue 'http://foo.bar/examples/user-example.whatever' + ) +``` + +```json +{ + "description": "user to add to the system", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + }, + "examples": { + "user" : { + "summary": "User Example", + "externalValue": "http://foo.bar/examples/user-example.json" + } + } + }, + "application/xml": { + "schema": { + "$ref": "#/components/schemas/User" + }, + "examples": { + "user" : { + "summary": "User example in XML", + "externalValue": "http://foo.bar/examples/user-example.xml" + } + } + }, + "text/plain": { + "examples": { + "user" : { + "summary": "User example in Plain text", + "externalValue": "http://foo.bar/examples/user-example.txt" + } + } + }, + "*/*": { + "examples": { + "user" : { + "summary": "User example in other format", + "externalValue": "http://foo.bar/examples/user-example.whatever" + } + } + } + } +} +``` + +```yaml +description: user to add to the system +content: + 'application/json': + schema: + $ref: '#/components/schemas/User' + examples: + user: + summary: User Example + externalValue: 'http://foo.bar/examples/user-example.json' + 'application/xml': + schema: + $ref: '#/components/schemas/User' + examples: + user: + summary: User Example in XML + externalValue: 'http://foo.bar/examples/user-example.xml' + 'text/plain': + examples: + user: + summary: User example in text plain format + externalValue: 'http://foo.bar/examples/user-example.txt' + '*/*': + examples: + user: + summary: User example in other format + externalValue: 'http://foo.bar/examples/user-example.whatever' +``` + +A body parameter that is an array of string values: + +```powershell +New-PodeOARequestBody -Description 'user to add to the system' -Content @{ + 'text/plain' = New-PodeOAStringProperty -Name 'breed' -array +} +``` + +```json +{ + "description": "user to add to the system", + "content": { + "text/plain": { + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + } + } +} +``` + +```yaml +description: user to add to the system +required: true +content: + text/plain: + schema: + type: array + items: + type: string +``` + +#### Media Type Object +Each Media Type Object provides schema and examples for the media type identified by its key. + +##### Fixed Fields +| Field Name | Type | `New-PodeOARequestBody` | Description | +| ---------------------------------------- | :--------------------------------------------------------------------------------------: | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| schema | [Schema Object](#schemaObject) \| [Reference Object](#referenceObject) | `-Schema` | The schema defining the content of the request, response, or parameter. | +| example | Any | `Not Supported` | Example of the media type. The example object SHOULD be in the correct format as specified by the media type. The `example` field is mutually exclusive of the `examples` field. Furthermore, if referencing a `schema` which contains an example, the `example` value SHALL _override_ the example provided by the schema. | +| examples | Map[ `string`, [Example Object](#exampleObject) \| [Reference Object](#referenceObject)] | `-Examples` | Examples of the media type. Each example object SHOULD match the media type and specified schema if present. The `examples` field is mutually exclusive of the `example` field. Furthermore, if referencing a `schema` which contains an example, the `examples` value SHALL _override_ the example provided by the schema. | +| encoding | Map[`string`, [Encoding Object](#encodingObject)] | `Not Supported` | A map between a property name and its encoding information. The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to `requestBody` objects when the media type is `multipart` or `application/x-www-form-urlencoded`. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Media Type Examples + +```powershell +New-PodeOARequestBody -Content @{ 'application/json' = 'Pet' } -Examples ( + New-PodeOAExample -MediaType 'application/json' -Name 'cat' -Summary 'An example of a cat' -Value @{name = 'Fluffy'; petType = 'Cat'; color = 'White'; gender = 'male'; breed = 'Persian' } | + New-PodeOAExample -MediaType 'application/json' -Name 'dog' -Summary "An example of a dog with a cat's name" -Value @{name = 'Puma'; petType = 'Dog'; color = 'Black'; gender = 'Female'; breed = 'Mixed' }| + New-PodeOAExample -MediaType 'application/json' -Reference 'frog-example' + ) +``` + +```json +{ + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pet" + }, + "examples": { + "cat" : { + "summary": "An example of a cat", + "value": + { + "name": "Fluffy", + "petType": "Cat", + "color": "White", + "gender": "male", + "breed": "Persian" + } + }, + "dog": { + "summary": "An example of a dog with a cat's name", + "value" : { + "name": "Puma", + "petType": "Dog", + "color": "Black", + "gender": "Female", + "breed": "Mixed" + }, + "frog": { + "$ref": "#/components/examples/frog-example" + } + } + } + } +} +``` + +```yaml +application/json: + schema: + $ref: "#/components/schemas/Pet" + examples: + cat: + summary: An example of a cat + value: + name: Fluffy + petType: Cat + color: White + gender: male + breed: Persian + dog: + summary: An example of a dog with a cat's name + value: + name: Puma + petType: Dog + color: Black + gender: Female + breed: Mixed + frog: + $ref: "#/components/examples/frog-example" +``` + +##### Considerations for File Uploads + +In contrast with the 2.0 specification, `file` input/output content in OpenAPI is described with the same semantics as any other schema type. Specifically: + +```yaml +# content transferred with base64 encoding +schema: + type: string + format: base64 +``` + +```yaml +# content transferred in binary (octet-stream): +schema: + type: string + format: binary +``` + +These examples apply to either input payloads of file uploads or response payloads. + +A `requestBody` for submitting a file in a `POST` operation may look like the following example: + +```powershell + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Content @{'application/octet-stream' = (New-PodeOAStringProperty -Format binary)}) +``` + +```yaml +requestBody: + content: + application/octet-stream: + schema: + # a binary file of any type + type: string + format: binary +``` + +In addition, specific media types MAY be specified: +```powershell + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Content @{ + 'image/jpeg' = (New-PodeOAStringProperty -Format binary) + 'image/png' = (New-PodeOAStringProperty -Format binary) + }) +``` +or + +```powershell +New-PodeOAContentMediaType -MediaType 'image/jpeg','image/png' -Content (New-PodeOAStringProperty -Format binary) +``` + +```yaml +# multiple, specific media types may be specified: +requestBody: + content: + # a binary file of type png or jpeg + 'image/jpeg': + schema: + type: string + format: binary + 'image/png': + schema: + type: string + format: binary +``` + +To upload multiple files, a `multipart` media type MUST be used: +```powershell + Set-PodeOARequest -Properties -RequestBody (New-PodeOARequestBody -Content @{ + 'multipart/form-data' = (New-PodeOAStringProperty -Name 'file' -Format binary -Array) + }) +``` + +```yaml +requestBody: + content: + multipart/form-data: + schema: + properties: + # The property name 'file' will be used for all files. + file: + type: array + items: + type: string + format: binary +``` + +Note the use of the `-Properties` Parameter without that the result is + +```yaml +requestBody: + content: + multipart/form-data: + schema: + type: array + items: + type: string + format: binary +``` + +##### Support for x-www-form-urlencoded Request Bodies + +To submit content using form url encoding via [RFC1866](https://tools.ietf.org/html/rfc1866), the following +definition may be used: +```powershell + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Content @{ + 'application/x-www-form-urlencoded' = (New-PodeOAObjectProperty -Properties @( + (New-PodeOAStringProperty -name 'id' -format 'uuid'), (New-PodeOAObjectProperty -name 'address' -NoProperties))) +}) +``` + +```yaml +requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + # complex types are stringified to support RFC 1866 + type: object + properties: {} +``` + +In this example, the contents in the `requestBody` MUST be stringified per [RFC1866](https://tools.ietf.org/html/rfc1866/) when passed to the server. In addition, the `address` field complex object will be stringified. + +When passing complex objects in the `application/x-www-form-urlencoded` content type, the default serialization strategy of such properties is described in the [`Encoding Object`](#encodingObject)'s [`style`](#encodingStyle) property as `form`. + +##### Special Considerations for `multipart` Content + +It is common to use `multipart/form-data` as a `Content-Type` when transferring request bodies to operations. In contrast to 2.0, a `schema` is REQUIRED to define the input parameters to the operation when using `multipart` content. This supports complex structures as well as supporting mechanisms for multiple file uploads. + +When passing in `multipart` types, boundaries MAY be used to separate sections of the content being transferred ? thus, the following default `Content-Type`s are defined for `multipart`: + +* If the property is a primitive, or an array of primitive values, the default Content-Type is `text/plain` +* If the property is complex, or an array of complex values, the default Content-Type is `application/json` +* If the property is a `type: string` with `format: binary` or `format: base64` (aka a file object), the default Content-Type is `application/octet-stream` + + +Examples: + +```powershell + Set-PodeOARequest -RequestBody ( + New-PodeOARequestBody -Content ( + New-PodeOAContentMediaType -MediaType 'multipart/form-data' -Content ( + New-PodeOAStringProperty -name 'id' -format 'uuid' | + New-PodeOAObjectProperty -name 'address' -NoProperties | + New-PodeOAStringProperty -name 'children' -array | + New-PodeOASchemaProperty -Name 'addresses' -Reference 'Address' -Array | + New-PodeOAObjectProperty + ) + ) + ) +``` + +```yaml +requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + id: + type: string + format: uuid + address: + # default Content-Type for objects is `application/json` + type: object + properties: {} + profileImage: + # default Content-Type for string/binary is `application/octet-stream` + type: string + format: binary + children: + # default Content-Type for arrays is based on the `inner` type (text/plain here) + type: array + items: + type: string + addresses: + # default Content-Type for arrays is based on the `inner` type (object shown, so `application/json` in this example) + type: array + items: + type: '#/components/schemas/Address' +``` + +An `encoding` attribute is introduced to give you control over the serialization of parts of `multipart` request bodies. This attribute is _only_ applicable to `multipart` and `application/x-www-form-urlencoded` request bodies. + +#### Encoding Object + +A single encoding definition applied to a single schema property. + +##### Fixed Fields +| Field Name | Type | `New-PodeOAEncodingObject` | Description | +| ------------------------------------------------- | :-----------------------------------------------------------------------------------: | -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| contentType | `string` | `-ContentType` | The Content-Type for encoding a specific property. Default value depends on the property type: for `string` with `format` being `binary` ? `application/octet-stream`; for other primitive types ? `text/plain`; for `object` - `application/json`; for `array` ? the default is defined based on the inner type. The value can be a specific media type (e.g. `application/json`), a wildcard media type (e.g. `image/*`), or a comma-separated list of the two types. | +| headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | `-Headers` | A map allowing additional information to be provided as headers, for example `Content-Disposition`. `Content-Type` is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a `multipart`. | +| style | `string` | `-Style` | Describes how a specific property value will be serialized depending on its type. See [Parameter Object](#parameterObject) for details on the [`style`](#parameterStyle) property. The behavior follows the same values as `query` parameters, including default values. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. | +| explode | `boolean` | `-Explode` | When this is true, property values of type `array` or `object` generate separate parameters for each value of the array, or key-value-pair of the map. For other types of properties this property has no effect. When [`style`](#encodingStyle) is `form`, the default value is `true`. For all other styles, the default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. | +| allowReserved | `boolean` | `-AllowReserved` | Determines whether the parameter value SHOULD allow reserved characters, as defined by [RFC3986](https://tools.ietf.org/html/rfc3986#section-2.2) `:/?#[]@!$&'()*+,;=` to be included without percent-encoding. The default value is `false`. This property SHALL be ignored if the request body media type is not `application/x-www-form-urlencoded`. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Encoding Object Example + +```powershell +New-PodeOARequestBody -Content (New-PodeOAContentMediaType -MediaType 'multipart/mixed' -Content ( + New-PodeOAStringProperty -name 'id' -format 'uuid' | + New-PodeOAObjectProperty -name 'address' -NoProperties | + New-PodeOAObjectProperty -name 'historyMetadata' -Description 'metadata in XML format' -NoProperties | + New-PodeOAStringProperty -name 'profileImage' -Format Binary | + New-PodeOAObjectProperty + )) -Encoding ( + New-PodeOAEncodingObject -Name 'historyMetadata' -ContentType 'application/xml; charset=utf-8' | + New-PodeOAEncodingObject -Name 'profileImage' -ContentType 'image/png, image/jpeg' -Headers ( + New-PodeOAIntProperty -name 'X-Rate-Limit-Limit' ` + -Description 'The number of allowed requests in the current period' + ) +) +``` + +```yaml +requestBody: + content: + multipart/mixed: + schema: + type: object + properties: + id: + # default is text/plain + type: string + format: uuid + address: + # default is application/json + type: object + properties: {} + historyMetadata: + # need to declare XML format! + description: metadata in XML format + type: object + properties: {} + profileImage: + # default is application/octet-stream, need to declare an image type only! + type: string + format: binary + encoding: + historyMetadata: + # require XML Content-Type in utf-8 encoding + contentType: application/xml; charset=utf-8 + profileImage: + # only accept png/jpeg + contentType: image/png, image/jpeg + headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer +``` + +#### Responses Object + +A container for the expected responses of an operation. +The container maps a HTTP response code to the expected response. + +The documentation is not necessarily expected to cover all possible HTTP response codes because they may not be known in advance. +However, documentation is expected to cover a successful operation response and any known errors. + +The `default` MAY be used as a default response object for all HTTP codes +that are not covered individually by the specification. + +The `Responses Object` MUST contain at least one response code, and it +SHOULD be the response for a successful operation call. + +##### Fixed Fields +| Field Name | Type | `Add-PodeOAResponse` | Description | +| -------------------------------------- | :------------------------------------------------------------------------: | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| default | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | `-Default` | The documentation of responses other than the ones declared for specific HTTP response codes. Use this field to cover undeclared responses. A [Reference Object](#referenceObject) can link to a response that the [OpenAPI Object's components/responses](#componentsResponses) section defines. | + +##### Patterned Fields +| Field Pattern | Type | `Add-PodeOAResponse` | Description | +| ---------------------------------------------------------- | :------------------------------------------------------------------------: | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [HTTP Status Code](#httpCodes) | [Response Object](#responseObject) \| [Reference Object](#referenceObject) | `-StatusCode` | Any [HTTP status code](#httpCodes) can be used as the property name, but only one property per code, to describe the expected response for that HTTP status code. A [Reference Object](#referenceObject) can link to a response that is defined in the [OpenAPI Object's components/responses](#componentsResponses) section. This field MUST be enclosed in quotation marks (for example, "200") for compatibility between JSON and YAML. To define a range of response codes, this field MAY contain the uppercase wildcard character `X`. For example, `2XX` represents all response codes between `[200-299]`. Only the following range definitions are allowed: `1XX`, `2XX`, `3XX`, `4XX`, and `5XX`. If a response is defined using an explicit code, the explicit code definition takes precedence over the range definition for that code. | + + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Responses Object Example + +A 200 response for a successful operation and a default response for others (implying an error): + +```powershell +Add-PodeOAResponse -StatusCode 200 -Description 'a pet to be returned' -Content (@{'application/json' = 'Pet' }) -PassThru | +Add-PodeOAResponse -Default -Description 'Unexpected error' -Content (@{'application/json' = 'ErrorModel' }) +``` + +```json +{ + "200": { + "description": "a pet to be returned", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Pet" + } + } + } + }, + "default": { + "description": "Unexpected error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorModel" + } + } + } + } +} +``` + +```yaml +'200': + description: a pet to be returned + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' +default: + description: Unexpected error + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorModel' +``` + +#### Response Object +Describes a single response from an API Operation, including design-time, static +`links` to operations based on the response. + +##### Fixed Fields +| Field Name | Type | `Add-PodeOAResponse` | Description | +| --------------------------------------------- | :------------------------------------------------------------------------------------: | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| description | `string` | `-Description` | **REQUIRED**. A short description of the response. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| headers | Map[`string`, [Header Object](#headerObject) \| [Reference Object](#referenceObject)] | `-Headers` | Maps a header name to its definition. [RFC7230](https://tools.ietf.org/html/rfc7230#page-22) states header names are case insensitive. If a response header is defined with the name `"Content-Type"`, it SHALL be ignored. | +| content | Map[`string`, [Media Type Object](#mediaTypeObject)] | `-Content` | A map containing descriptions of potential response payloads. The key is a media type or [media type range](https://tools.ietf.org/html/rfc7231#appendix-D) and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* | +| links | Map[`string`, [Link Object](#linkObject) \| [Reference Object](#referenceObject)] | TBD | A map of operations links that can be followed from the response. The key of the map is a short name for the link, following the naming constraints of the names for [Component Objects](#componentsObject). | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Response Object Examples + +Response of an array of a complex type: + +```powershell +Add-PodeOAResponse -StatusCode 200 -Description 'A complex object array response' -Content ( + New-PodeOAMediaContentType -MediaType 'application/json' -Content 'VeryComplexType' -Array +) +``` + +```json +{ + "200": { + "description": "A complex object array response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VeryComplexType" + } + } + } + } + } +} +``` + +```yaml +'200': + description: A complex object array response + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/VeryComplexType' +``` + +Response with a string type: + +```powershell +Add-PodeOAResponse -StatusCode 200 -Description 'A simple string response' -Content (New-PodeOAMediaContentType -MediaType 'text/plain' -Content (New-PodeOAStringProperty) -Array) +``` + +or + +```powershell +Add-PodeOAResponse -StatusCode 200 -Description 'A simple string response' -Content (New-PodeOAMediaContentType -MediaType 'text/plain' -Content 'string' -Array) +``` + +```json +{ + "200": { + "description": "A simple string response", + "content": { + "text/plain": { + "schema": { + "type": "string" + } + } + } + + } +} +``` + +```yaml +'200': + description: A simple string response + content: + text/plain: + schema: + type: string +``` + +Plain text response with headers: + +```powershell + Add-PodeOAResponse -StatusCode 200 -Description 'A simple string response' -Content @{ + 'text/plain' = ( New-PodeOAStringProperty -Example 'whoa!') + } -Headers ( + New-PodeOAIntProperty -Name 'X-Rate-Limit-Limit' -Description 'The number of allowed requests in the current period' | + New-PodeOAIntProperty -Name 'X-Rate-Limit-Remaining' -Description 'The number of remaining requests in the current period' | + New-PodeOAIntProperty -Name 'X-Rate-Limit-Reset' -Description 'The number of seconds left in the current period' + ) +``` + +```json +{ + "200": { + "description": "A simple string response", + "content": { + "text/plain": { + "schema": { + "type": "string", + "example": "whoa!" + } + } + }, + "headers": { + "X-Rate-Limit-Limit": { + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Remaining": { + "description": "The number of remaining requests in the current period", + "schema": { + "type": "integer" + } + }, + "X-Rate-Limit-Reset": { + "description": "The number of seconds left in the current period", + "schema": { + "type": "integer" + } + } + } + } +} +``` + +```yaml +'200': + description: A simple string response + content: + text/plain: + schema: + type: string + example: 'whoa!' + headers: + X-Rate-Limit-Limit: + description: The number of allowed requests in the current period + schema: + type: integer + X-Rate-Limit-Remaining: + description: The number of remaining requests in the current period + schema: + type: integer + X-Rate-Limit-Reset: + description: The number of seconds left in the current period + schema: + type: integer +``` + +Response with no return value: +```powershell +Add-PodeOAResponse -StatusCode 200 -Description 'object created' +``` + +```json +{ + "200": { + "description": "object created" + } +} +``` + +```yaml +'200': + description: object created +``` + +#### Callback Object + +A map of possible out-of band callbacks related to the parent operation. +Each value in the map is a [Path Item Object](#pathItemObject) that describes a set of requests that may be initiated by the API provider and the expected responses. +The key value used to identify the path item object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. + +##### Patterned Fields +| Field Pattern | Type | Description | +| --------------------------------------------- | :---------------------------------: | -------------------------------------------------------------------------------------------------------------------------------------------------------- | +| {expression} | [Path Item Object](#pathItemObject) | A Path Item Object used to define a callback request and expected responses. A [complete example](../examples/v3.0/callback-example.yaml) is available. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Key Expression + +The key that identifies the [Path Item Object](#pathItemObject) is a [runtime expression](#runtimeExpression) that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. +A simple example might be `$request.body#/url`. +However, using a [runtime expression](#runtimeExpression) the complete HTTP message can be accessed. +This includes accessing any part of a body that a JSON Pointer [RFC6901](https://tools.ietf.org/html/rfc6901) can reference. + +For example, given the following HTTP request: + +```http +POST /subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning HTTP/1.1 +Host: example.org +Content-Type: application/json +Content-Length: 187 + +{ + "failedUrl" : "http://clientdomain.com/failed", + "successUrls" : [ + "http://clientdomain.com/fast", + "http://clientdomain.com/medium", + "http://clientdomain.com/slow" + ] +} + +201 Created +Location: http://example.org/subscription/1 +``` + +The following examples show how the various expressions evaluate, assuming the callback operation has a path parameter named `eventType` and a query parameter named `queryUrl`. + +| Expression | Value | +| ---------------------------- | :--------------------------------------------------------------------------------- | +| $url | http://example.org/subscribe/myevent?queryUrl=http://clientdomain.com/stillrunning | +| $method | POST | +| $request.path.eventType | myevent | +| $request.query.queryUrl | http://clientdomain.com/stillrunning | +| $request.header.content-Type | application/json | +| $request.body#/failedUrl | http://clientdomain.com/failed | +| $request.body#/successUrls/2 | http://clientdomain.com/medium | +| $response.header.Location | http://example.org/subscription/1 | + + +##### Callback Object Examples + +The following example uses the user provided `queryUrl` query string parameter to define the callback URL. This is an example of how to use a callback object to describe a WebHook callback that goes with the subscription operation to enable registering for the WebHook. + +```powershell +Add-PodeOACallBacks -Title 'test' -Path '{$request.query.queryUrl}' -Method Post ` + -RequestBody (New-PodeOARequestBody -Description 'Callback payload' ` + -Content @{'application/json' = 'SomePayload' } ) ` + -Response ( Add-PodeOACallBacksResponse -StatusCode 200 -Description 'callback successfully processed' ) +``` + +```yaml +myCallback: + '{$request.query.queryUrl}': + post: + requestBody: + description: Callback payload + content: + 'application/json': + schema: + $ref: '#/components/schemas/SomePayload' + responses: + '200': + description: callback successfully processed +``` + +The following example shows a callback where the server is hard-coded, but the query string parameters are populated from the `id` and `email` property in the request body. + +```yaml +transactionCallback: + 'http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}': + post: + requestBody: + description: Callback payload + content: + 'application/json': + schema: + $ref: '#/components/schemas/SomePayload' + responses: + '200': + description: callback successfully processed +``` + +#### Example Object + +##### Fixed Fields +| Field Name | Type | `New-PodeOAExample ` | Description | +| ------------------------------------------------ | :------: | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| summary | `string` | `-Summary` | Short description for the example. | +| description | `string` | `-Description` | Long description for the example. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| value | Any | `-Value` | Embedded literal example. The `value` field and `externalValue` field are mutually exclusive. To represent examples of media types that cannot naturally represented in JSON or YAML, use a string value to contain the example, escaping where necessary. | +| externalValue | `string` | `-ExternalValue` | A URL that points to the literal example. This provides the capability to reference examples that cannot easily be included in JSON or YAML documents. The `value` field and `externalValue` field are mutually exclusive. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +In all cases, the example value is expected to be compatible with the type schema +of its associated value. Tooling implementations MAY choose to +validate compatibility automatically, and reject the example value(s) if incompatible. + +##### Example Object Examples + +In a request body: + +```powershell +New-PodeOARequestBody -Content @{ 'application/json' = 'Address' } -Examples ( + New-PodeOAExample -MediaType 'application/json' -Name 'foo' -Summary 'A foo example' -Value @{foo = 'bar' } | + New-PodeOAExample -MediaType 'application/json' -Name 'bar' -Summary 'A bar example' -Value @{'bar' = 'baz' }| + New-PodeOAExample -MediaType 'application/xml' -Name 'xmlExample' -Summary 'This is an example in XML' -ExternalValue 'http://example.org/examples/address-example.xml' | + New-PodeOAExample -MediaType 'text/plain' -Name 'textExample' -Summary 'This is an example' -ExternalValue 'http://example.org/examples/address-example.txt' | + ) +``` + +```yaml +requestBody: + content: + 'application/json': + schema: + $ref: '#/components/schemas/Address' + examples: + foo: + summary: A foo example + value: {"foo": "bar"} + bar: + summary: A bar example + value: {"bar": "baz"} + 'application/xml': + examples: + xmlExample: + summary: This is an example in XML + externalValue: 'http://example.org/examples/address-example.xml' + 'text/plain': + examples: + textExample: + summary: This is a text example + externalValue: 'http://foo.bar/examples/address-example.txt' +``` + +In a parameter: + +```powershell +New-PodeOAStringProperty -Name 'zipCode' -format 'zip-code' | + ConvertTo-PodeOAParameter -In Query -Examples ( + New-PodeOAExample -Name 'zip-example' -Refence 'zip-example' + ) +``` + +```yaml +parameters: + - name: 'zipCode' + in: 'query' + schema: + type: 'string' + format: 'zip-code' + examples: + zip-example: + $ref: '#/components/examples/zip-example' +``` + +In a response: + +```yaml +responses: + '200': + description: your car appointment has been booked + content: + application/json: + schema: + $ref: '#/components/schemas/SuccessResponse' + examples: + confirmation-success: + $ref: '#/components/examples/confirmation-success' +``` + + +#### Link Object + +The `Link object` represents a possible design-time link for a response. +The presence of a link does not guarantee the caller's ability to successfully invoke it, rather it provides a known relationship and traversal mechanism between responses and other operations. + +Unlike _dynamic_ links (i.e. links provided **in** the response payload), the OAS linking mechanism does not require link information in the runtime response. + +For computing links, and providing instructions to execute them, a [runtime expression](#runtimeExpression) is used for accessing values in an operation and using them as parameters while invoking the linked operation. + +##### Fixed Fields + +| Field Name | Type | Description | +| ------------------------------------------- | :------------------------------------------------------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| operationRef | `string` | A relative or absolute URI reference to an OAS operation. This field is mutually exclusive of the `operationId` field, and MUST point to an [Operation Object](#operationObject). Relative `operationRef` values MAY be used to locate an existing [Operation Object](#operationObject) in the OpenAPI definition. | +| operationId | `string` | The name of an _existing_, resolvable OAS operation, as defined with a unique `operationId`. This field is mutually exclusive of the `operationRef` field. | +| parameters | Map[`string`, Any \| [{expression}](#runtimeExpression)] | A map representing parameters to pass to an operation as specified with `operationId` or identified via `operationRef`. The key is the parameter name to be used, whereas the value can be a constant or an expression to be evaluated and passed to the linked operation. The parameter name can be qualified using the [parameter location](#parameterIn) `[{in}.]{name}` for operations that use the same parameter name in different locations (e.g. path.id). | +| requestBody | Any \| [{expression}](#runtimeExpression) | A literal value or [{expression}](#runtimeExpression) to use as a request body when calling the target operation. | +| description | `string` | A description of the link. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| server | [Server Object](#serverObject) | A server object to be used by the target operation. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +A linked operation MUST be identified using either an `operationRef` or `operationId`. +In the case of an `operationId`, it MUST be unique and resolved in the scope of the OAS document. +Because of the potential for name clashes, the `operationRef` syntax is preferred +for specifications with external references. + +##### Examples + +Computing a link from a request operation where the `$request.path.id` is used to pass a request parameter to the linked operation. + +```yaml +paths: + /users/{id}: + parameters: + - name: id + in: path + required: true + description: the user identifier, as userId + schema: + type: string + get: + responses: + '200': + description: the user being returned + content: + application/json: + schema: + type: object + properties: + uuid: # the unique user id + type: string + format: uuid + links: + address: + # the target link operationId + operationId: getUserAddress + parameters: + # get the `id` field from the request path parameter named `id` + userId: $request.path.id + # the path item of the linked operation + /users/{userid}/address: + parameters: + - name: userid + in: path + required: true + description: the user identifier, as userId + schema: + type: string + # linked operation + get: + operationId: getUserAddress + responses: + '200': + description: the user's address +``` + +When a runtime expression fails to evaluate, no parameter value is passed to the target operation. + +Values from the response body can be used to drive a linked operation. + +```yaml +links: + address: + operationId: getUserAddressByUUID + parameters: + # get the `uuid` field from the `uuid` field in the response body + userUuid: $response.body#/uuid +``` + +Clients follow all links at their discretion. +Neither permissions, nor the capability to make a successful call to that link, is guaranteed +solely by the existence of a relationship. + + +##### OperationRef Examples + +As references to `operationId` MAY NOT be possible (the `operationId` is an optional +field in an [Operation Object](#operationObject)), references MAY also be made through a relative `operationRef`: + +```yaml +links: + UserRepositories: + # returns array of '#/components/schemas/repository' + operationRef: '#/paths/~12.0~1repositories~1{username}/get' + parameters: + username: $response.body#/username +``` + +or an absolute `operationRef`: + +```yaml +links: + UserRepositories: + # returns array of '#/components/schemas/repository' + operationRef: 'https://na2.gigantic-server.com/#/paths/~12.0~1repositories~1{username}/get' + parameters: + username: $response.body#/username +``` + +Note that in the use of `operationRef`, the _escaped forward-slash_ is necessary when +using JSON references. + + +##### Runtime Expressions + +Runtime expressions allow defining values based on information that will only be available within the HTTP message in an actual API call. +This mechanism is used by [Link Objects](#linkObject) and [Callback Objects](#callbackObject). + +The runtime expression is defined by the following [ABNF](https://tools.ietf.org/html/rfc5234) syntax + +```abnf + expression = ( "$url" / "$method" / "$statusCode" / "$request." source / "$response." source ) + source = ( header-reference / query-reference / path-reference / body-reference ) + header-reference = "header." token + query-reference = "query." name + path-reference = "path." name + body-reference = "body" ["#" json-pointer ] + json-pointer = *( "/" reference-token ) + reference-token = *( unescaped / escaped ) + unescaped = %x00-2E / %x30-7D / %x7F-10FFFF + ; %x2F ('/') and %x7E ('~') are excluded from 'unescaped' + escaped = "~" ( "0" / "1" ) + ; representing '~' and '/', respectively + name = *( CHAR ) + token = 1*tchar + tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / + "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA +``` + +Here, `json-pointer` is taken from [RFC 6901](https://tools.ietf.org/html/rfc6901), `char` from [RFC 7159](https://tools.ietf.org/html/rfc7159#section-7) and `token` from [RFC 7230](https://tools.ietf.org/html/rfc7230#section-3.2.6). + +The `name` identifier is case-sensitive, whereas `token` is not. + +The table below provides examples of runtime expressions and examples of their use in a value: + +##### Examples + +| Source Location | example expression | notes | +| --------------------- | :------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------- | +| HTTP Method | `$method` | The allowable values for the `$method` will be those for the HTTP operation. | +| Requested media type | `$request.header.accept` | +| Request parameter | `$request.path.id` | Request parameters MUST be declared in the `parameters` section of the parent operation or they cannot be evaluated. This includes request headers. | +| Request body property | `$request.body#/user/uuid` | In operations which accept payloads, references may be made to portions of the `requestBody` or the entire body. | +| Request URL | `$url` | +| Response value | `$response.body#/status` | In operations which return payloads, references may be made to portions of the response body or the entire body. | +| Response header | `$response.header.Server` | Single header values only are available | + +Runtime expressions preserve the type of the referenced value. +Expressions can be embedded into string values by surrounding the expression with `{}` curly braces. + +#### Header Object + +The Header Object follows the structure of the [Parameter Object](#parameterObject) with the following changes: + +1. `name` MUST NOT be specified, it is given in the corresponding `headers` map. +1. `in` MUST NOT be specified, it is implicitly in `header`. +1. All traits that are affected by the location MUST be applicable to a location of `header` (for example, [`style`](#parameterStyle)). + +##### Header Object Example + +A simple header of type `integer`: + +```json +{ + "description": "The number of allowed requests in the current period", + "schema": { + "type": "integer" + } +} +``` + +```yaml +description: The number of allowed requests in the current period +schema: + type: integer +``` + +#### Tag Object + +Adds metadata to a single tag that is used by the [Operation Object](#operationObject). +It is not mandatory to have a Tag Object per tag defined in the Operation Object instances. + +##### Fixed Fields +| Field Name | Type | `Add-PodeOATag` | Description | +| ------------------------------------------ | :-----------------------------------------------------------: | --------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| name | `string` | `-Name` | **REQUIRED**. The name of the tag. | +| description | `string` | `-Description` | A short description for the tag. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| externalDocs | [External Documentation Object](#externalDocumentationObject) | `-ExternalDocs` | Additional external documentation for this tag. In Pode is an ExternalDoc object created with `New-PodeOAExternalDoc` | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Tag Object Example +```powershell + Add-PodeOATag -Name 'pet' -Description 'Pets operations' +``` + +```json +{ + "name": "pet", + "description": "Pets operations" +} +``` + +```yaml +name: pet +description: Pets operations +``` + +#### Reference Object + +A simple object to allow referencing other components in the specification, internally and externally. + +The Reference Object is defined by [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03) and follows the same structure, behavior and rules. + +For this specification, reference resolution is accomplished as defined by the JSON Reference specification and not by the JSON Schema specification. + +##### Fixed Fields +| Field Name | Type | Description | +| ------------------------------- | :------: | ----------------------------------- | +| $ref | `string` | **REQUIRED**. The reference string. | + +This object cannot be extended with additional properties and any properties added SHALL be ignored. + +Multiple cmdlets support `$ref` : `Merge-PodeOAProperty`, `New-PodeOASchemaProperty`, `Add-PodeOAResponse`, `New-PodeOAResponse` `New-PodeOARequestBody` +##### Reference Object Example + +```powershell +New-PodeOASchemaProperty -Name 'something' -Reference 'Pet' +``` + +```powershell +Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'Pet','Animal' +``` + +```powershell +Add-PodeOAResponse -Default -Content (New-PodeOAMediaContentType -Content 'Pet') +``` + +```powershell +New-PodeOAResponse -Default -Content (New-PodeOAMediaContentType -Content 'Pet') +``` + +```powershell +New-PodeOAComponentResponse -Name 'Pet' -Default -Content (New-PodeOAMediaContentType -Content 'Pet') +``` + +```json +{ + "$ref": "#/components/schemas/Pet" +} +``` + +```yaml +$ref: '#/components/schemas/Pet' +``` + +##### Relative Schema Document Example +```json +{ + "$ref": "Pet.json" +} +``` + +```yaml +$ref: Pet.yaml +``` + +##### Relative Documents With Embedded Schema Example + +```json +{ + "$ref": "definitions.json#/Pet" +} +``` + +```yaml +$ref: definitions.yaml#/Pet +``` + +#### Schema Object + +The Schema Object allows the definition of input and output data types. +These types can be objects, but also primitives and arrays. +This object is an extended subset of the [JSON Schema Specification Wright Draft 00](https://json-schema.org/). + +For more information about the properties, see [JSON Schema Core](https://tools.ietf.org/html/draft-wright-json-schema-00) and [JSON Schema Validation](https://tools.ietf.org/html/draft-wright-json-schema-validation-00). +Unless stated otherwise, the property definitions follow the JSON Schema. + +##### Properties + +The following properties are taken directly from the JSON Schema definition and follow the same specifications: + +type - Value MUST be a string. Multiple types via an array are not supported. + +| type | cmdlet | +| ------ | -------------------------- | +| int | `New-PodeOAIntProperty` | +| string | `New-PodeOAStringProperty` | +| object | `New-PodeOAObjectProperty` | +| bool | `New-PodeOABoolProperty` | +| number | `New-PodeOANumberProperty` | +| | | + +| Field Name | `New-PodeOAIntProperty` \| `New-PodeOAStringProperty` \| `New-PodeOAObjectProperty` \| `New-PodeOABoolProperty` \| `New-PodeOANumberProperty` | Description | +| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| title | `-Name` or `-Title` | +| multipleOf | `-MultipleOf` | `New-PodeOANumberProperty` \| `New-PodeOAIntProperty` | +| maximum | `-Maximum` | `New-PodeOANumberProperty` \| `New-PodeOAIntProperty` | +| exclusiveMaximum | `-ExclusiveMaximum` | `New-PodeOANumberProperty` \| `New-PodeOAIntProperty` | +| minimum | `-Minimum` | `New-PodeOANumberProperty` \| `New-PodeOAIntProperty` | +| exclusiveMinimum | `-ExclusiveMinimum` | `New-PodeOANumberProperty` \| `New-PodeOAIntProperty` | +| maxLength | `-MaxLength` | `New-PodeOAStringProperty` | +| minLength | `-MinLength` | `New-PodeOAStringProperty` | +| pattern | `-Pattern` | `New-PodeOAStringProperty` - (This string SHOULD be a valid regular expression, according to the [Ecma-262 Edition 5.1 regular expression](https://www.ecma-international.org/ecma-262/5.1/#sec-15.10.1) dialect) | +| maxItems | `-MaxItems` | Used in combination with `-Array` with any New-PodeOAxxxProperty cmdlet | +| minItems | `-MinItems` | Used in combination with `-Array` with any New-PodeOAxxxProperty cmdlet | +| uniqueItems | `-UniqueItems` | Used in combination with `-Array` with any New-PodeOAxxxProperty cmdlet | +| maxProperties | `-MaxProperties` | `New-PodeOAObjectProperty` | +| minProperties | `-MinProperties` | `New-PodeOAObjectProperty` | +| required | `-Required` | `New-PodeOAIntProperty` \| `New-PodeOAStringProperty` \| `New-PodeOABoolProperty` \| `New-PodeOANumberProperty` \| `New-PodeOAObjectProperty` | +| enum | `-Enum` | `New-PodeOAIntProperty` \| `New-PodeOAStringProperty` \| `New-PodeOABoolProperty` \| `New-PodeOANumberProperty` \| `New-PodeOAObjectProperty` | +| items | `-Array` | `New-PodeOAIntProperty` \| `New-PodeOAStringProperty` \| `New-PodeOABoolProperty` \| `New-PodeOANumberProperty` \| `New-PodeOAObjectProperty` | +| description | `-Description` | [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| default | `-Default` | The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided. Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level. For example, if `type` is `string`, then `default` can be `"foo"` but cannot be `1`. | +| properties | `-properties` | `New-PodeOAObjectProperty` Property definitions MUST be a [Schema Object](#schemaObject) and not a standard JSON Schema (inline or referenced). | + +| type | `Merge-PodeOAProperty` | Note | +| ----------------------------------------------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| allOf | `-Type AllOf` | | +| oneOf | `-Type OneOf` | (Pode) Doesn't support schema validation | +| anyOf | `-Type AnyOf` | (Pode)Doesn't support schema validation | +| not | Not supported | Will be supported in a future release | +| discriminator | `-Discriminator` | [Discriminator Object](#discriminatorObject) - Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description. See [Composition and Inheritance](#schemaComposition) for more details. | + + + + + +- additionalProperties - Value can be boolean or object. Inline or referenced schema MUST be of a [Schema Object](#schemaObject) and not a standard JSON Schema. Consistent with JSON Schema, `additionalProperties` defaults to `true`. +- format - See [Data Type Formats](#dataTypeFormat) for further details. While relying on JSON Schema's defined formats, the OAS offers a few additional predefined formats. + + +Alternatively, any time a Schema Object can be used, a [Reference Object](#referenceObject) can be used in its place. This allows referencing definitions instead of defining them inline. + +Additional properties defined by the JSON Schema specification that are not mentioned here are strictly unsupported. + +Other than the JSON Schema subset fields, the following fields MAY be used for further schema documentation: + +##### Fixed Fields +| Field Name | Type | | Description | +| --------------------------------------------- | :-----------------------------------------------------------: | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| nullable | `boolean` | `-Nullable` | A `true` value adds `"null"` to the allowed type specified by the `type` keyword, only if `type` is explicitly defined within the same Schema Object. Other Schema Object constraints retain their defined behavior, and therefore may disallow the use of `null` as a value. A `false` value leaves the specified or default `type` unmodified. The default value is `false`. | +| readOnly | `boolean` | `-ReadOnly` | Relevant only for Schema `"properties"` definitions. Declares the property as "read only". This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request. If the property is marked as `readOnly` being `true` and is in the `required` list, the `required` will take effect on the response only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`. | +| writeOnly | `boolean` | `-WriteOnly` | Relevant only for Schema `"properties"` definitions. Declares the property as "write only". Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response. If the property is marked as `writeOnly` being `true` and is in the `required` list, the `required` will take effect on the request only. A property MUST NOT be marked as both `readOnly` and `writeOnly` being `true`. Default value is `false`. | +| xml | [XML Object](#xmlObject) | `-Xml` | This MAY be used only on properties schemas. It has no effect on root schemas. Adds additional metadata to describe the XML representation of this property. | +| externalDocs | [External Documentation Object](#externalDocumentationObject) | `-ExternalDocs` | Additional external documentation for this schema. | +| example | Any | `-Example` | A free-form property to include an example of an instance for this schema. To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary. | +| deprecated | `boolean` | `-Deprecated` | Specifies that a schema is deprecated and SHOULD be transitioned out of usage. Default value is `false`. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +###### Composition and Inheritance (Polymorphism) + +The OpenAPI Specification allows combining and extending model definitions using the `allOf` property of JSON Schema, in effect offering model composition. +`allOf` takes an array of object definitions that are validated *independently* but together compose a single object. + +While composition offers model extensibility, it does not imply a hierarchy between the models. +To support polymorphism, the OpenAPI Specification adds the `discriminator` field. +When used, the `discriminator` will be the name of the property that decides which schema definition validates the structure of the model. +As such, the `discriminator` field MUST be a required field. +There are two ways to define the value of a discriminator for an inheriting instance. +- Use the schema name. +- Override the schema name by overriding the property with a new value. If a new value exists, this takes precedence over the schema name. +As such, inline schema definitions, which do not have a given id, *cannot* be used in polymorphism. + +###### XML Modeling + +The [xml](#schemaXml) property allows extra definitions when translating the JSON definition to XML. +The [XML Object](#xmlObject) contains additional information about the available options. + +##### Schema Object Examples + +###### Primitive Sample + +```powershell +New-PodeOAStringProperty -Format 'email' +``` + +```json +{ + "type": "string", + "format": "email" +} +``` + +```yaml +type: string +format: email +``` + +###### Simple Model + +```powershell +New-PodeOAStringProperty -Name 'name'| New-PodeOASchemaProperty -Name 'Address' -Reference 'Address'| + New-PodeOAIntProperty -Name 'age' -Minimum 0 -Format Int32 | New-PodeOAObjectProperty +``` + +```json +{ + "type": "object", + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "address": { + "$ref": "#/components/schemas/Address" + }, + "age": { + "type": "integer", + "format": "int32", + "minimum": 0 + } + } +} +``` + +```yaml +type: object +required: +- name +properties: + name: + type: string + address: + $ref: '#/components/schemas/Address' + age: + type: integer + format: int32 + minimum: 0 +``` + +###### Model with Map/Dictionary Properties + +For a simple string to string mapping: + +```powershell +New-PodeOAObjectProperty -AdditionalProperties (New-PodeOAStringProperty ) +``` + +```json +{ + "type": "object", + "additionalProperties": { + "type": "string" + } +} +``` + +```yaml +type: object +additionalProperties: + type: string +``` + +For a string to model mapping: + + +```powershell +New-PodeOAObjectProperty -AdditionalProperties (New-PodeOASchemaProperty -Reference 'ComplexModel') +``` + +```json +{ + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/ComplexModel" + } +} +``` + +```yaml +type: object +additionalProperties: + $ref: '#/components/schemas/ComplexModel' +``` + +###### Model with Example + +```powershell +New-PodeOAIntProperty -Name 'id' -Format Int64 | New-PodeOAStringProperty -Name 'name' -Required | + New-PodeOAObjectProperty -Example @{"name"= "Puma"; "id"= 1} +``` + +```json +{ + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "required": [ + "name" + ], + "example": { + "name": "Puma", + "id": 1 + } +} +``` + +```yaml +type: object +properties: + id: + type: integer + format: int64 + name: + type: string +required: +- name +example: + name: Puma + id: 1 +``` + +###### Models with Composition + +```powershell +#Define ErrorModel schema +New-PodeOAStringProperty -Name 'message' | + New-PodeOAIntProperty -Name 'code' -Minimum 100 -Maximum 600 | + New-PodeOAObjectProperty | + Add-PodeOAComponentSchema -Name 'ErrorModel' + +#Define ExtendedErrorModel schema +Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'ErrorModel', (New-PodeOAStringProperty -Name 'rootCause' -required -object) | + Add-PodeOAComponentSchema -Name 'ExtendedErrorModel' +``` + +```json +{ + "components": { + "schemas": { + "ErrorModel": { + "type": "object", + "required": [ + "message", + "code" + ], + "properties": { + "message": { + "type": "string" + }, + "code": { + "type": "integer", + "minimum": 100, + "maximum": 600 + } + } + }, + "ExtendedErrorModel": { + "allOf": [ + { + "$ref": "#/components/schemas/ErrorModel" + }, + { + "type": "object", + "required": [ + "rootCause" + ], + "properties": { + "rootCause": { + "type": "string" + } + } + } + ] + } + } + } +} +``` + +```yaml +components: + schemas: + ErrorModel: + type: object + required: + - message + - code + properties: + message: + type: string + code: + type: integer + minimum: 100 + maximum: 600 + ExtendedErrorModel: + allOf: + - $ref: '#/components/schemas/ErrorModel' + - type: object + required: + - rootCause + properties: + rootCause: + type: string +``` + +###### Models with Polymorphism Support + +```powershell +#Define Pet schema +New-PodeOAStringProperty -Name 'name'| New-PodeOAStringProperty -Name 'petType' | + New-PodeOAObjectProperty -DiscriminatorProperty 'petType' | Add-PodeOAComponentSchema -Name 'Pet' + +#Define Cat schema +Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'Pet', +(New-PodeOAStringProperty -Name 'huntingSkill' -Description "The measured skill for hunting" -Default "lazy" -Enum "clueless", "lazy", "adventurous", "aggressive" -Required -Object ) | + Add-PodeOAComponentSchema -Name 'Cat' -Description "A representation of a cat. Note that `Cat` will be used as the discriminator value." + +#Define Dog schema +Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'Pet', +(New-PodeOAIntProperty -Name 'packSize' -Description "the size of the pack the dog is from" -Default 0 -Minimum 0 -Format Int32 -Required -Object ) | + Add-PodeOAComponentSchema -Name 'Dog' -Description "A representation of a dog. Note that `Dog` will be used as the discriminator value." +``` + +```json +{ + "components": { + "schemas": { + "Pet": { + "type": "object", + "discriminator": { + "propertyName": "petType" + }, + "properties": { + "name": { + "type": "string" + }, + "petType": { + "type": "string" + } + }, + "required": [ + "name", + "petType" + ] + }, + "Cat": { + "description": "A representation of a cat. Note that `Cat` will be used as the discriminator value.", + "allOf": [ + { + "$ref": "#/components/schemas/Pet" + }, + { + "type": "object", + "properties": { + "huntingSkill": { + "type": "string", + "description": "The measured skill for hunting", + "default": "lazy", + "enum": [ + "clueless", + "lazy", + "adventurous", + "aggressive" + ] + } + }, + "required": [ + "huntingSkill" + ] + } + ] + }, + "Dog": { + "description": "A representation of a dog. Note that `Dog` will be used as the discriminator value.", + "allOf": [ + { + "$ref": "#/components/schemas/Pet" + }, + { + "type": "object", + "properties": { + "packSize": { + "type": "integer", + "format": "int32", + "description": "the size of the pack the dog is from", + "default": 0, + "minimum": 0 + } + }, + "required": [ + "packSize" + ] + } + ] + } + } + } +} +``` + +```yaml +components: + schemas: + Pet: + type: object + discriminator: + propertyName: petType + properties: + name: + type: string + petType: + type: string + required: + - name + - petType + Cat: ## "Cat" will be used as the discriminator value + description: A representation of a cat + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + properties: + huntingSkill: + type: string + description: The measured skill for hunting + enum: + - clueless + - lazy + - adventurous + - aggressive + required: + - huntingSkill + Dog: ## "Dog" will be used as the discriminator value + description: A representation of a dog + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + properties: + packSize: + type: integer + format: int32 + description: the size of the pack the dog is from + default: 0 + minimum: 0 + required: + - packSize +``` + +#### Discriminator Object + +When request bodies or response payloads may be one of a number of different schemas, a `discriminator` object can be used to aid in serialization, deserialization, and validation. The discriminator is a specific object in a schema which is used to inform the consumer of the specification of an alternative schema based on the value associated with it. + +When using the discriminator, _inline_ schemas will not be considered. + +##### Fixed Fields +| Field Name | Type | `New-PodeOAObjectProperty` | Description | +| ------------------------------------------- | :---------------------: | -------------------------- | --------------------------------------------------------------------------------------------- | +| propertyName | `string` | `-DiscriminatorProperty` | **REQUIRED**. The name of the property in the payload that will hold the discriminator value. | +| mapping | Map[`string`, `string`] | `-DiscriminatorMapping` | An object to hold mappings between payload values and schema names or references. | + +The discriminator object is legal only when using one of the composite keywords `oneOf`, `anyOf`, `allOf`. + +In OAS 3.0, a response payload MAY be described to be exactly one of any number of types: + +```powershell +Merge-PodeOAProperty -Type OneOf -ObjectDefinitions 'Cat','Dog','Lizard' +``` + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' +``` + +which means the payload _MUST_, by validation, match exactly one of the schemas described by `Cat`, `Dog`, or `Lizard`. In this case, a discriminator MAY act as a "hint" to shortcut validation and selection of the matching schema which may be a costly operation, depending on the complexity of the schema. We can then describe exactly which field tells us which schema to use: + +```powershell +Merge-PodeOAProperty -Type OneOf -ObjectDefinitions 'Cat','Dog','Lizard' -DiscriminatorProperty 'petType' +``` + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' + discriminator: + propertyName: petType +``` + +The expectation now is that a property with name `petType` _MUST_ be present in the response payload, and the value will correspond to the name of a schema defined in the OAS document. Thus the response payload: + +```json +{ + "id": 12345, + "petType": "Cat" +} +``` + +Will indicate that the `Cat` schema be used in conjunction with this payload. + +In scenarios where the value of the discriminator field does not match the schema name or implicit mapping is not possible, an optional `mapping` definition MAY be used: + +```powershell +Merge-PodeOAProperty -Type OneOf -ObjectDefinitions 'Cat','Dog','Lizard' ` + -DiscriminatorProperty 'petType' -DiscriminatorMapping @{ + 'dog' = '#/components/schemas/Dog' + 'monster' = 'https://gigantic-server.com/schemas/Monster/schema.json' + } +``` + +```yaml +MyResponseType: + oneOf: + - $ref: '#/components/schemas/Cat' + - $ref: '#/components/schemas/Dog' + - $ref: '#/components/schemas/Lizard' + - $ref: 'https://gigantic-server.com/schemas/Monster/schema.json' + discriminator: + propertyName: petType + mapping: + dog: '#/components/schemas/Dog' + monster: 'https://gigantic-server.com/schemas/Monster/schema.json' +``` + +Here the discriminator _value_ of `dog` will map to the schema `#/components/schemas/Dog`, rather than the default (implicit) value of `Dog`. If the discriminator _value_ does not match an implicit or explicit mapping, no schema can be determined and validation SHOULD fail. Mapping keys MUST be string values, but tooling MAY convert response values to strings for comparison. + +When used in conjunction with the `anyOf` construct, the use of the discriminator can avoid ambiguity where multiple schemas may satisfy a single payload. + +In both the `oneOf` and `anyOf` use cases, all possible schemas MUST be listed explicitly. To avoid redundancy, the discriminator MAY be added to a parent schema definition, and all schemas comprising the parent schema in an `allOf` construct may be used as an alternate schema. + +For example: + +```powershell +New-PodeOAStringProperty -Name 'petType' -Required |New-PodeOAObjectProperty -DiscriminatorProperty 'petType' -DiscriminatorMapping @{ 'dog'='Dog'} | + Add-PodeOAComponentSchema -Name 'Pet' + +Merge-PodeOAProperty -Name -Type AllOf -ObjectDefinitions 'Pet', ( New-PodeOAStringProperty -Name 'name' -Object) | + Add-PodeOAComponentSchema -Name 'Cat' + +Merge-PodeOAProperty -Name -Type AllOf -ObjectDefinitions 'Pet', ( New-PodeOAStringProperty -Name 'bark' -Object) | + Add-PodeOAComponentSchema -Name 'Dog' + + Merge-PodeOAProperty -Name -Type AllOf -ObjectDefinitions 'Pet', ( New-PodeOABoolProperty -Name 'lovesRocks' -Object) | + Add-PodeOAComponentSchema -Name 'Lizard' +``` + +```yaml +components: + schemas: + Pet: + type: object + required: + - petType + properties: + petType: + type: string + discriminator: + propertyName: petType + mapping: + dog: Dog + Cat: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Cat` + properties: + name: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Dog` + properties: + bark: + type: string + Lizard: + allOf: + - $ref: '#/components/schemas/Pet' + - type: object + # all other properties specific to a `Lizard` + properties: + lovesRocks: + type: boolean +``` + +a payload like this: + +```json +{ + "petType": "Cat", + "name": "misty" +} +``` + +will indicate that the `Cat` schema be used. Likewise this schema: + +```json +{ + "petType": "dog", + "bark": "soft" +} +``` + +will map to `Dog` because of the definition in the `mappings` element. + + +#### XML Object + +A metadata object that allows for more fine-tuned XML model definitions. + +When using arrays, XML element names are *not* inferred (for singular/plural forms) and the `name` property SHOULD be used to add that information. +See examples for expected behavior. + +##### Fixed Fields +| Field Name | Type | `New-PodeOA(*)Property` | Description | +| ------------------------------------ | :-------: | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| name | `string` | `-XmlName` | Replaces the name of the element/attribute used for the described schema property. When defined within `items`, it will affect the name of the individual XML elements within the list. When defined alongside `type` being `array` (outside the `items`), it will affect the wrapping element and only if `wrapped` is `true`. If `wrapped` is `false`, it will be ignored. | +| namespace | `string` | `-XmlNameSpace` | The URI of the namespace definition. Value MUST be in the form of an absolute URI. | +| prefix | `string` | `-XmlPrefix` | The prefix to be used for the [name](#xmlName). | +| attribute | `boolean` | `-XmlAttribute` | Declares whether the property definition translates to an attribute instead of an element. Default value is `false`. | +| wrapped | `boolean` | `-XmlWrapped` | MAY be used only for an array definition. Signifies whether the array is wrapped (for example, ``) or unwrapped (``). Default value is `false`. The definition takes effect only when defined alongside `type` being `array` (outside the `items`). | + +(*) `New-PodeOAIntProperty` \| `New-PodeOAStringProperty` \| `New-PodeOABoolProperty` \| `New-PodeOANumberProperty` \| `New-PodeOAObjectProperty` \|`New-PodeOASchemaProperty` + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### XML Object Examples + +The examples of the XML object definitions are included inside a property definition of a [Schema Object](#schemaObject) with a sample of the XML representation of it. + +###### No XML Element + +Basic string property: + +```powershell +New-PodeOAStringProperty -Name 'animals' +``` + +```json +{ + "animals": { + "type": "string" + } +} +``` + +```yaml +animals: + type: string +``` + +```xml +... +``` + +Basic string array property ([`wrapped`](#xmlWrapped) is `false` by default): + +```powershell +New-PodeOAStringProperty -Name 'animals' -Array +``` + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string +``` + +```xml +... +... +... +``` + +###### XML Name Replacement + +```powershell +New-PodeOAStringProperty -Name 'animals' -XmlName 'animal' +``` + +```json +{ + "animals": { + "type": "string", + "xml": { + "name": "animal" + } + } +} +``` + +```yaml +animals: + type: string + xml: + name: animal +``` + +```xml +... +``` + + +###### XML Attribute, Prefix and Namespace + +In this example, a full model definition is shown. + +```powershell +New-PodeOAIntProperty -Name 'id' -Format Int32 -XmlAttribute | New-PodeOAStringProperty -Name 'name' -XmlPrefix 'sample' -XmlNamespace 'http://example.com/schema/sample' | + New-PodeOAObjectProperty | Add-PodeOAComponentSchema -Name 'Person' +``` + +```json +{ + "Person": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int32", + "xml": { + "attribute": true + } + }, + "name": { + "type": "string", + "xml": { + "namespace": "http://example.com/schema/sample", + "prefix": "sample" + } + } + } + } +} +``` + +```yaml +Person: + type: object + properties: + id: + type: integer + format: int32 + xml: + attribute: true + name: + type: string + xml: + namespace: http://example.com/schema/sample + prefix: sample +``` + +```xml + + example + +``` + +###### XML Arrays + +Changing the element names: + +```powershell +New-PodeOAStringProperty -Array -XmlItemName 'animal' | Add-PodeOAComponentSchema -Name 'animals' +``` + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal +``` + +```xml +value +value +``` + +The external `name` property has no effect on the XML: + +```powershell +New-PodeOAStringProperty -Array -XmlItemName 'animal' -XmlName 'aliens' | Add-PodeOAComponentSchema -Name 'animals' +``` + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens" + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens +``` + +```xml +value +value +``` + +Even when the array is wrapped, if a name is not explicitly defined, the same name will be used both internally and externally: + +```powershell +New-PodeOAStringProperty -Array -XmlWrapped | Add-PodeOAComponentSchema -Name 'animals' +``` + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + wrapped: true +``` + +```xml + + value + value + +``` + +To overcome the naming problem in the example above, the following definition can be used: + +```powershell +New-PodeOAStringProperty -Array -XmlWrapped -XmlItemName 'animal' | Add-PodeOAComponentSchema -Name 'animals' +``` + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + wrapped: true +``` + +```xml + + value + value + +``` + +Affecting both internal and external names: + +```powershell +New-PodeOAStringProperty -Array -XmlWrapped -XmlItemName 'animal' -XmlName 'aliens' | Add-PodeOAComponentSchema -Name 'animals' +``` + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string", + "xml": { + "name": "animal" + } + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: animal + xml: + name: aliens + wrapped: true +``` + +```xml + + value + value + +``` + +If we change the external element but not the internal ones: + +```json +{ + "animals": { + "type": "array", + "items": { + "type": "string" + }, + "xml": { + "name": "aliens", + "wrapped": true + } + } +} +``` + +```yaml +animals: + type: array + items: + type: string + xml: + name: aliens + wrapped: true +``` + +```xml + + value + value + +``` + +#### Security Scheme Object + +Defines a security scheme that can be used by the operations. +Supported schemes are HTTP authentication, an API key (either as a header, a cookie parameter or as a query parameter), OAuth2's common flows (implicit, password, client credentials and authorization code) as defined in [RFC6749](https://tools.ietf.org/html/rfc6749), and [OpenID Connect Discovery](https://tools.ietf.org/html/draft-ietf-oauth-discovery-06). + +##### Fixed Fields +| Field Name | Type | Applies To | Description | +| ------------------------------------------------------------- | :-------------------------------------: | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| type | `string` | Any | **REQUIRED**. The type of the security scheme. Valid values are `"apiKey"`, `"http"`, `"oauth2"`, `"openIdConnect"`. | +| description | `string` | Any | A short description for security scheme. [CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation. | +| name | `string` | `apiKey` | **REQUIRED**. The name of the header, query or cookie parameter to be used. | +| in | `string` | `apiKey` | **REQUIRED**. The location of the API key. Valid values are `"query"`, `"header"` or `"cookie"`. | +| scheme | `string` | `http` | **REQUIRED**. The name of the HTTP Authorization scheme to be used in the [Authorization header as defined in RFC7235](https://tools.ietf.org/html/rfc7235#section-5.1). The values used SHOULD be registered in the [IANA Authentication Scheme registry](https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml). | +| bearerFormat | `string` | `http` (`"bearer"`) | A hint to the client to identify how the bearer token is formatted. Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. | +| flows | [OAuth Flows Object](#oauthFlowsObject) | `oauth2` | **REQUIRED**. An object containing configuration information for the flow types supported. | +| openIdConnectUrl | `string` | `openIdConnect` | **REQUIRED**. OpenId Connect URL to discover OAuth2 configuration values. This MUST be in the form of a URL. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### Security Scheme Object Example + +###### Basic Authentication Sample + +```powershell +New-PodeAuthScheme -Basic | Add-PodeAuth -Name 'basic' -ScriptBlock { + param($username, $password) + # check if the user is valid + return @{ User = $user } +} +``` + +```json +{ + "type": "http", + "scheme": "basic" +} +``` + +```yaml +type: http +scheme: basic +``` + +###### API Key Sample + +```powershell + New-PodeAuthScheme -ApiKey -Location 'Header' | Add-PodeAuth -Name 'ApiKey' -ScriptBlock { + param($key) + # check if the key is valid, and get user + return @{ User = $user } + } +``` + +```json +{ + "type": "apiKey", + "name": "api_key", + "in": "header" +} +``` + +```yaml +type: apiKey +name: api_key +in: header +``` + +###### JWT Bearer Sample + +```powershell +New-PodeAuthScheme -Bearer -AsJWT | Add-PodeAuth -Name 'Example' -Sessionless -ScriptBlock { + param($payload) + # check if the key is valid, and get user + return @{ User = $user } +} +``` + +```json +{ + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT", +} +``` + +```yaml +type: http +scheme: bearer +bearerFormat: JWT +``` + +###### Implicit OAuth2 Sample +```powershell +New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'read:pets' -Description 'read your pets' +New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'write:pets' -Description 'modify pets in your account' + +New-PodeAuthScheme -OAuth2 -ClientId $ClientId -ClientSecret $ClientSecret -AuthoriseUrl "http://example.org/api/oauth/dialog" ` + -TokenUrl 'http://example.org/api/oauth/token' -Scope 'read:pets', 'write:pets' | + Add-PodeAuth -Name 'petstore_auth' -FailureUrl 'http://example.org/api/oauth/dialog' -SuccessUrl '/' -ScriptBlock { + param($user, $accessToken, $refreshToken) + return @{ User = $user } + } +``` + +```json +{ + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "tokenUrl": "http://example.org/api/oauth/token" + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } +} +``` + +```yaml +type: oauth2 +flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + tokenUrl: http://example.org/api/oauth/token + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### OAuth Flows Object + +Allows configuration of the supported OAuth Flows. + +##### Fixed Fields +| Field Name | Type | Description | +| ----------------------------------------------------------- | :-----------------------------------: | ----------------------------------------------------------------------------------------------------- | +| implicit | [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Implicit flow | +| password | [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Resource Owner Password flow | +| clientCredentials | [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Client Credentials flow. Previously called `application` in OpenAPI 2.0. | +| authorizationCode | [OAuth Flow Object](#oauthFlowObject) | Configuration for the OAuth Authorization Code flow. Previously called `accessCode` in OpenAPI 2.0. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +#### OAuth Flow Object + +Configuration details for a supported OAuth Flow + +##### Fixed Fields +| Field Name | Type | Applies To | Description | +| -------------------------------------------------------- | :---------------------: | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | +| authorizationUrl | `string` | `oauth2` (`"implicit"`, `"authorizationCode"`) | **REQUIRED**. The authorization URL to be used for this flow. This MUST be in the form of a URL. | +| tokenUrl | `string` | `oauth2` (`"password"`, `"clientCredentials"`, `"authorizationCode"`) | **REQUIRED**. The token URL to be used for this flow. This MUST be in the form of a URL. | +| refreshUrl | `string` | `oauth2` | The URL to be used for obtaining refresh tokens. This MUST be in the form of a URL. | +| scopes | Map[`string`, `string`] | `oauth2` | **REQUIRED**. The available scopes for the OAuth2 security scheme. A map between the scope name and a short description for it. The map MAY be empty. | + +This object MAY be extended with [Specification Extensions](#specificationExtensions). + +##### OAuth Flow Object Examples + +```json +{ + "type": "oauth2", + "flows": { + "implicit": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "authorizationCode": { + "authorizationUrl": "https://example.com/api/oauth/dialog", + "tokenUrl": "https://example.com/api/oauth/token", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + } +} +``` + +```yaml +type: oauth2 +flows: + implicit: + authorizationUrl: https://example.com/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + authorizationCode: + authorizationUrl: https://example.com/api/oauth/dialog + tokenUrl: https://example.com/api/oauth/token + scopes: + write:pets: modify pets in your account + read:pets: read your pets +``` + +#### Security Requirement Object + +Lists the required security schemes to execute this operation. +The name used for each property MUST correspond to a security scheme declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). + +Security Requirement Objects that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. +This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. + +When a list of Security Requirement Objects is defined on the [OpenAPI Object](#oasObject) or [Operation Object](#operationObject), only one of the Security Requirement Objects in the list needs to be satisfied to authorize the request. + +##### Patterned Fields + +| Field Pattern | Type | Description | +| --------------------------------------------- | :--------: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| {name} | [`string`] | Each name MUST correspond to a security scheme which is declared in the [Security Schemes](#componentsSecuritySchemes) under the [Components Object](#componentsObject). If the security scheme is of type `"oauth2"` or `"openIdConnect"`, then the value is a list of scope names required for the execution, and the list MAY be empty if authorization does not require a specified scope. For other security scheme types, the array MUST be empty. | + +##### Security Requirement Object Examples + +###### Non-OAuth2 Security Requirement + +```powershell +New-PodeAuthScheme -ApiKey | Add-PodeAuth -Name 'api_key' -Sessionless -ScriptBlock { + param($username, $password) + # check if the user is valid + return @{ User = $user } +} +Add-PodeRoute -PassThru -Method Get -Path '/pet/#id' -Authentication 'api_key' -ScriptBlock { + #code here +} +``` + +```json +{ + "/pet2/{petId}": { + "get": { + "petId": { + "schema": { + "type": "integer", + "format": "int64" + }, + "description": "ID of the pet", + "required": true, + "in": "path" + } + }, + "security": [ + { + "api_key": [] + } + ] + } +} +``` + +```yaml +/pet2/{petId} : + get : + petId : + schema : + type : integer + format : int64 + description : ID of the pet + required : true + in : path + security: + - api_key: [] +``` + +###### OAuth2 Security Requirement + +```powershell +New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'read:pets' -Description 'read your pets' +New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'write:pets' -Description 'modify pets in your account' + +New-PodeAuthScheme -OAuth2 -ClientId $ClientId -ClientSecret $ClientSecret -AuthoriseUrl 'http://example.org/api/oauth/dialog' ` + -TokenUrl 'http://example.org/api/oauth/token' -Scope 'read:pets', 'write:pets' | + Add-PodeAuth -Name 'petstore_auth' -FailureUrl 'http://example.org/api/oauth/dialog' -SuccessUrl '/' -ScriptBlock { + param($user, $accessToken, $refreshToken) + #Auth here + return @{ User = $user } + } + +Add-PodeRoute -PassThru -Method post -Path '/pet/#id' -Authentication 'petstore_auth' -Scope 'write:pets', +'read:pets' -ScriptBlock { + #code here +} +``` + +```json +{ + "/pet2/{petId}": { + "post": { + "petId": { + "schema": { + "type": "integer", + "format": "int64" + }, + "description": "ID of the pet", + "required": true, + "in": "path" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } +} +``` + +```yaml +/pet2/{petId} : + post : + petId : + schema : + type : integer + format : int64 + description : ID of the pet + required : true + in : path + security: + - petstore_auth: + - write:pets + - read:pets +``` + +###### Optional OAuth2 Security + +Optional OAuth2 security as would be defined in an OpenAPI Object or an Operation Object: + +```powershell +New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'read:pets' -Description 'read your pets' +New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'write:pets' -Description 'modify pets in your account' + +New-PodeAuthScheme -OAuth2 -ClientId $ClientId -ClientSecret $ClientSecret -AuthoriseUrl 'http://example.org/api/oauth/dialog' ` + -TokenUrl 'http://example.org/api/oauth/token' -Scope 'read:pets', 'write:pets' | + Add-PodeAuth -Name 'petstore_auth' -FailureUrl 'http://example.org/api/oauth/dialog' -SuccessUrl '/' -ScriptBlock { + param($user, $accessToken, $refreshToken) + #Auth here + return @{ User = $user } + } + +Add-PodeRoute -PassThru -Method put -Path '/pet/#id' -Authentication 'petstore_auth' -Scope 'write:pets', +'read:pets' -AllowAnon -ScriptBlock { + #code here +} +``` + +```json +{ + "/pet2/{petId}": { + "post": { + "petId": { + "schema": { + "type": "integer", + "format": "int64" + }, + "description": "ID of the pet", + "required": true, + "in": "path" + } + }, + "security": [ + {}, + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } +} +``` + +```yaml +/pet2/{petId} : + put : + petId : + schema : + type : integer + format : int64 + description : ID of the pet + required : true + in : path + security: + - petstore_auth: + - write:pets + - read:pets + - {} +``` + +### Specification Extensions + +While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points. + +The extensions properties are implemented as patterned fields that are always prefixed by `"x-"`. + +| Field Pattern | Type | Description | +| -------------------------------- | :---: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| ^x- | Any | Allows extensions to the OpenAPI Schema. The field name MUST begin with `x-`, for example, `x-internal-id`. The value can be `null`, a primitive, an array or an object. Can have any valid JSON format value. | + +The extensions may or may not be supported by the available tooling, but those may be extended as well to add requested support (if tools are internal or open-sourced). + +### Security Filtering + +Some objects in the OpenAPI Specification MAY be declared and remain empty, or be completely removed, even though they are inherently the core of the API documentation. + +The reasoning is to allow an additional layer of access control over the documentation. +While not part of the specification itself, certain libraries MAY choose to allow access to parts of the documentation based on some form of authentication/authorization. + +Two examples of this: + +1. The [Paths Object](#pathsObject) MAY be empty. It may be counterintuitive, but this may tell the viewer that they got to the right place, but can't access any documentation. They'd still have access to the [Info Object](#infoObject) which may contain additional information regarding authentication. +2. The [Path Item Object](#pathItemObject) MAY be empty. In this case, the viewer will be aware that the path exists, but will not be able to see any of its operations or parameters. This is different from hiding the path itself from the [Paths Object](#pathsObject), because the user will be aware of its existence. This allows the documentation provider to finely control what the viewer can see. + +## Appendix A: Revision History + +| Version | Date | Notes | +| ---------- | ---------- | ------------------------------------------------- | +| 3.0.3-Pode | 2023-11-20 | OpenAPI Specification 3.0.3 Pode Version | +| 3.0.3 | 2020-02-20 | Patch release of the OpenAPI Specification 3.0.3 | +| 3.0.2 | 2018-10-08 | Patch release of the OpenAPI Specification 3.0.2 | +| 3.0.1 | 2017-12-06 | Patch release of the OpenAPI Specification 3.0.1 | +| 3.0.0 | 2017-07-26 | Release of the OpenAPI Specification 3.0.0 | +| 3.0.0-rc2 | 2017-06-16 | rc2 of the 3.0 specification | +| 3.0.0-rc1 | 2017-04-27 | rc1 of the 3.0 specification | +| 3.0.0-rc0 | 2017-02-28 | Implementer's Draft of the 3.0 specification | +| 2.0 | 2015-12-31 | Donation of Swagger 2.0 to the OpenAPI Initiative | +| 2.0 | 2014-09-08 | Release of Swagger 2.0 | +| 1.2 | 2014-03-14 | Initial release of the formal document. | +| 1.1 | 2012-08-22 | Release of Swagger 1.1 | +| 1.0 | 2011-08-10 | First release of the Swagger Specification | diff --git a/docs/Tutorials/Routes/Utilities/SSE.md b/docs/Tutorials/Routes/Utilities/SSE.md new file mode 100644 index 000000000..94af90fe1 --- /dev/null +++ b/docs/Tutorials/Routes/Utilities/SSE.md @@ -0,0 +1,259 @@ +# SSE + +You can convert regular HTTP requests made to a Route into an SSE connection, allowing you to stream events from your server to one or more connected clients. Connections can be scoped to just the Route that converted the request and it will be closed at the end of the Route like a normal request flow (Local), or you can keep the connection open beyond the request flow and be used server-wide for sending events (Global). + +SSE connections are typically made from client browsers via JavaScript, using the [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) class. + +## Convert Request + +To convert a request into an SSE connection use [`ConvertTo-PodeSseConnection`](../../../../Functions/SSE/ConvertTo-PodeSseConnection). This will automatically send back the appropriate HTTP response headers to the client, converting it into an SSE connection; allowing the connection to be kept open, and for events to be streamed back to the client. A `-Name` must be supplied during the conversion, allowing for easier reference to all connections later on, and allowing for different connection groups (of which, you can also have `-Group` within a Name as well). + +!!! important + For a request to be convertible, it must have an `Accept` HTTP request header value of `text/event-stream`. + +Any requests to the following Route will be converted to a globally scoped SSE connection, and be available under the `Events` name: + +```powershell +Add-PodeRoute -Method Get -Path '/events' -ScriptBlock { + ConvertTo-PodeSseConnection -Name 'Events' +} +``` + +You could then use [`Send-PodeSseEvent`](../../../../Functions/SSE/Send-PodeSseEvent) in a Schedule (more info [below](#send-events)) to broadcast an event, every minute, to all connected clients within the `Events` name: + +```powershell +Add-PodeSchedule -Name 'Example' -Cron (New-PodeCron -Every Minute) -ScriptBlock { + Send-PodeSseEvent -Name 'Events' -Data "Hello there! The datetime is: $([datetime]::Now.TimeOfDay)" +} +``` + +Once [`ConvertTo-PodeSseConnection`](../../../../Functions/SSE/ConvertTo-PodeSseConnection) has been called, the `$WebEvent` object will be extended to include a new `SSE` property. This new property will have the following items: + +| Name | Description | +| ----------- | ------------------------------------------------------------------------------------------------------- | +| Name | The Name given to the connection | +| Group | An optional Group assigned to the connection within the Name | +| ClientId | The assigned ClientId for the connection - this will be different to a passed ClientId if using signing | +| LastEventId | The last EventId the client saw, if this is a reconnecting SSE request | +| IsLocal | Is the connection Local or Global | + +Therefore, after converting a request, you can get the client ID back via: + +```powershell +Add-PodeRoute -Method Get -Path '/events' -ScriptBlock { + ConvertTo-PodeSseConnection -Name 'Events' + $clientId = $WebEvent.Sse.ClientId +} +``` + +!!! tip + The Name, Group, and Client ID values are also sent back on the HTTP response during conversion as headers. These won't be available if you're using JavaScript's `EventSource` class, but could be if using other SSE libraries. The headers are: + + * `X-PODE-SSE-CLIENT-ID` + * `X-PODE-SSE-NAME` + * `X-PODE-SSE-GROUP` + +### ClientIds + +ClientIds created by [`ConvertTo-PodeSseConnection`](../../../../Functions/SSE/ConvertTo-PodeSseConnection) will be a GUID by default however, you can supply your own IDs via the `-ClientId` parameter: + +```powershell +Add-PodeRoute -Method Get -Path '/events' -ScriptBlock { + $clientId = Get-Random -Minimum 10000 -Maximum 999999 + ConvertTo-PodeSseConnection -Name 'Events' -ClientId $clientId +} +``` + +You can also [sign clientIds](#signing-clientids) as well. + +### Scopes + +The default scope for a new SSE connection is "Global", which means the connection will be stored internally and can be used outside of the converting Route to stream events back to the client. + +The default scope for new SSE connections can be altered by using [`Set-PodeSseDefaultScope`](../../../../Functions/SSE/Set-PodeSseDefaultScope). For example, if you wanted all new SSE connections to instead default to a Local scope: + +```powershell +Set-PodeSseDefaultScope -Scope Local +``` + +#### Global + +A Globally scoped SSE connection is the default (unless altered via [`Set-PodeSseDefaultScope`](../../../../Functions/SSE/Set-PodeSseDefaultScope)). A Global connection has the following features: + +* They are kept open, even after the Route that converted the request has finished. +* The connection is stored internally, so that events can be streamed to the clients from other Routes, Timers, etc. +* You can send events to a specific connection if you know the Name and ClientId for the connection. +* Global connections can be closed via [`Close-PodeSseConnection`](../../../../Functions/SSE/Close-PodeSseConnection). + +For example, the following will convert requests to `/events` into global SSE connections, and then a Schedule will send events to them every minute: + +```powershell +Start-PodeServer { + Add-PodeEndpoint -Address * -Port 8090 -Protocol Http + + Add-PodeRoute -Method Get -Path '/events' -ScriptBlock { + ConvertTo-PodeSseConnection -Name 'Events' + } + + Add-PodeSchedule -Name 'Example' -Cron (New-PodeCron -Every Minute) -ScriptBlock { + Send-PodeSseEvent -Name 'Events' -Data "Hello there! The datetime is: $([datetime]::Now.TimeOfDay)" + } +} +``` + +#### Local + +A Local connection has the following features: + +* When the Route that converted the request has finished, the connection will be closed - the same as HTTP requests. +* The connection is **not** stored internally, it is only available for the lifecycle of the HTTP request. +* You can send events back to the connection from within the converting Route's scriptblock, but not from Timers, etc. When sending events back for local connections you will need to use the `-FromEvent` switch on [`Send-PodeSseEvent`](../../../../Functions/SSE/Send-PodeSseEvent). + +For example, the following will convert requests to `/events` into local SSE connections, and two events will be sent back to the client before the connection is closed: + +```powershell +Start-PodeServer { + Add-PodeEndpoint -Address * -Port 8090 -Protocol Http + + Add-PodeRoute -Method Get -Path '/events' -ScriptBlock { + ConvertTo-PodeSseConnection -Name 'Events' -Scope Local + Send-PodeSseEvent -FromEvent -Data "Hello there! The datetime is: $([datetime]::Now.TimeOfDay)" + Start-Sleep -Seconds 10 + Send-PodeSseEvent -FromEvent -Data "Hello there! The datetime is: $([datetime]::Now.TimeOfDay)" + } +} +``` + +### Inbuilt Events + +Pode has two inbuilt events that it will send to your SSE connections. These events will be sent automatically when a connection is opened, and when it is closed. + +!!! important + It is recommended to listen for the close event from Pode, as this way you'll know when Pode has closed the connection and you can perform any required clean-up. + +#### Open + +When an SSE connection is opened, via [`ConvertTo-PodeSseConnection`](../../../../Functions/SSE/ConvertTo-PodeSseConnection), Pode will send a `pode.open` event to your client. This event will also contain the `clientId`, `group`, and `name` of the SSE connection. + +You can listen for this event in JavaScript if using `EventSource`, as follows: + +```javascript +const sse = new EventSource('/events'); + +sse.addEventListener('pode.open', (e) => { + var data = JSON.parse(e.data); + let clientId = data.clientId; + let group = data.group; + let name = data.name; +}); +``` + +#### Close + +When an SSE connection is closed, either via [`Close-PodeSseConnection`](../../../../Functions/SSE/Close-PodeSseConnection) or when the Pode server stops, Pode will send a `pode.close` event to your clients. This will be an empty event, purely for clean-up purposes. + +You can listen for this event in JavaScript if using `EventSource`, as follows: + +```javascript +const sse = new EventSource('/events'); + +sse.addEventListener('pode.close', (e) => { + sse.close(); +}); +``` + +## Send Events + +To send an event from the server to one or more connected clients, you can use [`Send-PodeSseEvent`](../../../../Functions/SSE/Send-PodeSseEvent). Using the `-Data` parameter, you can either send a raw string value, or a more complex hashtable/psobject which will be auto-converted into a JSON string. + +For example, to broadcast an event to all clients on an "Events" SSE connection: + +```powershell +# simple string +Send-PodeSseEvent -Name 'Events' -Data 'Hello there!' + +# complex object +Send-PodeSseEvent -Name 'Events' -Data @{ Value = 'Hello there!' } +``` + +Or to send an event to a specific client: + +```powershell +Send-PodeSseEvent -Name 'Events' -ClientId 'some-client-id' -Data 'Hello there!' +``` + +You can also specify an optional `-Id` and `-EventType` for the SSE event being sent. The `-EventType` can be used in JavaScript to register event listeners, and the `-Id` is used by the browser to keep track of events being sent in case the connection is dropped. + +```powershell +$id = [int][datetime]::Now.TimeOfDay.TotalSeconds +$data = @{ Date = [datetime]::Now.ToString() } + +Send-PodeSseEvent -Name 'Events' -Id $id -EventType 'Date' -Data $data +``` + +### Broadcast Levels + +By default, Pode will allow broadcasting of events to all clients for an SSE connection Name, Group, or a specific ClientId. + +You can supply a custom broadcasting level for specific SSE connection names (or all), limiting broadcasting to requiring a specific ClientId for example, by using [`Set-PodeSseBroadcastLevel`](../../../../Functions/SSE/Set-PodeSseBroadcastLevel). If a `-Name` is not supplied then the level type is applied to all SSE connections. + +For example, the following will only allow events to be broadcast to an SSE connection name if a ClientId is also specified on [`Send-PodeSseEvent`](../../../../Functions/SSE/Send-PodeSseEvent): + +```powershell +# apply to all SSE connections +Set-PodeSseBroadcastLevel -Type 'ClientId' + +# apply to just SSE connections with name = Events +Set-PodeSseBroadcastLevel -Name 'Events' -Type 'ClientId' +``` + +The following levels are available: + +| Level | Description | +| -------- | ------------------------------------------------------------------- | +| Name | A Name is required. Groups/ClientIds are optional. | +| Group | A Name is required. One of either a Group and ClientId is required. | +| ClientId | A Name and a ClientId are required. | + +## Signing ClientIds + +Similar to Sessions and Cookies, you can sign SSE connection ClientIds. This can be done by calling [`Enable-PodeSseSigning`](../../../../Functions/SSE/Enable-PodeSseSigning) and supplying a `-Secret` to sign the ClientIds. + +!!! tip + You can use the inbuilt [`Get-PodeServerDefaultSecret`](../../../../Functions/Core/Get-PodeServerDefaultSecret) function to retrieve an internal Pode server secret which can be used. However, be warned that this secret is regenerated to a random value on every server start/restart. + +```powershell +Enable-PodeSseSigning -Secret 'super-secret' +Enable-PodeSseSigning -Secret (Get-PodeServerDefaultSecret) +``` + +When signing is enabled, all clientIds will be signed regardless if they're an internally generated random GUID or supplied via `-ClientId` on [`ConvertTo-PodeSseConnection`](../../../../Functions/SSE/ConvertTo-PodeSseConnection). A signed clientId will look as follows, and have the structure `s:.`: + +```plain +s:5d12f974-7b1a-4524-ab93-6afbf42c4ffa.uvG49LcojTMuJ0l4yzBzr6jCqEV8gGC/0YgsYU1QEuQ= +``` + +You can also supply the `-Strict` switch to [`Enable-PodeSseSigning`](../../../../Functions/SSE/Enable-PodeSseSigning), which will extend the secret during signing with the client's IP Address and User Agent. + +## Request Headers + +If you have an SSE connection open for a client, and you want to have the client send AJAX requests to the server but have the responses streamed back over the SSE connection, then you can identify the SSE connection for the client using the following HTTP headers: + +* `X-PODE-SSE-CLIENT-ID` +* `X-PODE-SSE-NAME` +* `X-PODE-SSE-GROUP` + +At a minimum, you'll need the `X-PODE-SSE-CLIENT-ID` header. If supplied Pode will automatically verify the client ID for you, including if the signing of the client ID is valid - if you're using client ID signing. + +When these headers are supplied in a request, Pode will set up the `$WebEvent.Sse` property again - similar to the property set up from [conversion](#convert-request) above: + +| Name | Description | +| ----------- | ------------------------------------------------------------------ | +| Name | The Name for the connection from X-PODE-SSE-NAME | +| Group | The Group for the connection from X-PODE-SSE-GROUP | +| ClientId | The assigned ClientId for the connection from X-PODE-SSE-CLIENT-ID | +| LastEventId | `$null` | +| IsLocal | `$false` | + +!!! note + If you only supply the Name or Group headers, then the `$WebEvent.Sse` property will not be configured. The ClientId is required as a minimum. diff --git a/docs/Tutorials/Routes/Utilities/StaticContent.md b/docs/Tutorials/Routes/Utilities/StaticContent.md index 44da45d17..9a14ae8db 100644 --- a/docs/Tutorials/Routes/Utilities/StaticContent.md +++ b/docs/Tutorials/Routes/Utilities/StaticContent.md @@ -6,9 +6,10 @@ Caching is supported on static content. ## Public Directory -You can place static files within the `/public` directory, at the root of your server. If a request is made for a file, then Pode will automatically check the public directory first, and if found will return the back. +You can place static files within the `/public` directory at the root of your server, which serves as the default location for static content. When a request is made for a file, Pode will automatically check this designated static directory first, and if the file is found, it will be returned to the requester. -For example, if you have a `logic.js` at `/public/scripts/logic.js`. The the following request would return the file's content: + +For example, if you have a `logic.js` at `/public/scripts/logic.js`. The following request would return the file's content: ```plain Invoke-WebRequest -Uri http://localhost:8080/scripts/logic.js @@ -20,9 +21,40 @@ Or, you can reference the file in a view like: ``` +### Changing the Default Folders + +Usually, the Default Folders are located under the RootPath specified by `Start-PodeServer -RootPath `. +But if you need to relocate this directory, you can do so programmatically using the `Set-PodeStaticFolder` function within your server script or specify a different location in the `server.psd1` configuration file under the `Server.DefaultFolders` property. When a file request is made, Pode will automatically check this designated static directory first, and if the file is found, it will be returned to the requester. + +Here is an example: + +1. Using `Set-PodeStaticFolder` + +```powershell +Set-PodeDefaultFolder -Type 'Public' -Path 'c:\custom\public' +Set-PodeDefaultFolder -Type 'Views' -Path 'd:\shared\views' +Set-PodeDefaultFolder -Type 'Errors' -Path 'e:\logs\errors' +``` + +2. Using `server.psd1` configuration file + +```powershell +@{ + # For more information https://badgerati.github.io/Pode/Tutorials/Configuration/ + Server = @{ + # Any other properties you need in your application + DefaultFolders = @{ + Public = 'c:\custom\public' + Views = 'd:\shared\views' + Errors = 'e:\logs\errors' + } + } +} +``` + ## Static Routes -The following is an example of using the [`Add-PodeStaticRoute`](../../../../Functions/Routes/Add-PodeStaticRoute) function to define a route to some static content directory; this tells Pode where to get static files from for certain routes. This example will define a static route for `/assets`, and will point the route at the internal directory path of `./content/assets`: +The following is an example of using the [`Add-PodeStaticRoute`](../../../../Functions/Routes/Add-PodeStaticRoute) function to define a route to some static content directory; this tells Pode where to get static files for certain routes. This example will define a static route for `/assets`, and will point the route at the internal directory path of `./content/assets`: ```powershell Start-PodeServer { @@ -41,7 +73,7 @@ Invoke-WebRequest -Uri 'http://localhost:8080/assets/images/icon.png' -Method Ge Anything placed within your server's `/public` directory will always be public static content. However, if you define custom static routes via [`Add-PodeStaticRoute`](../../../../Functions/Routes/Add-PodeStaticRoute), then you can also supply middleware - including authentication. -Custom static routes follow a similar flow to normal routes, and any query string; payloads; cookies; etc, will all be parsed - allowing you to run any route specific middleware before the static content is actually returned. +Custom static routes follow a similar flow to normal routes, and any query string; payloads; cookies; etc, will all be parsed - allowing you to run any route-specific middleware before the static content is returned. Middleware works the same as on normal Routes, so there's nothing extra you need to do. Any global middleware that you've defined will also work on static routes as well. @@ -80,7 +112,7 @@ Add-PodeStaticRoute -Path '/assets' -Source './content/assets' -Defaults @('inde } ``` -The only difference being, if you have multiple static routes, setting any default pages in the `server.psd1` file will apply to *all* static routes. Any default pages set using the `-Default` parameter will have a higher precedence than the `server.psd1` file. +The only difference is, if you have multiple static routes, setting any default pages in the `server.psd1` file will apply to *all* static routes. Any default pages set using the `-Default` parameter will have a higher precedence than the `server.psd1` file. ## Caching @@ -138,7 +170,7 @@ Let's say you do want to exclude all `*.exe` files from being cached: } ``` -Or, you could setup some static routes called `/assets` and `/images`, and you want everything on `/images` to be cached, but only `*.js` files to be cached on `/assets`: +Or, you could set up some static routes called `/assets` and `/images`, and you want everything on `/images` to be cached, but only `*.js` files to be cached on `/assets`: ```powershell @{ @@ -168,3 +200,40 @@ Start-PodeServer { ``` When a static route is set as downloadable, then `-Defaults` and caching are not used. + +## File Browsing + +This feature allows the use of a static route as an HTML file browser. If you set the `-FileBrowser` switch on the [`Add-PodeStaticRoute`](../../../../Functions/Routes/Add-PodeStaticRoute) function, the route will show the folder content whenever it is invoked. + +```powershell +Start-PodeServer -ScriptBlock { + Add-PodeEndpoint -Address localhost -Port 8080 -Protocol Http + Add-PodeStaticRoute -Path '/' -Source './content/assets' -FileBrowser + Add-PodeStaticRoute -Path '/download' -Source './content/newassets' -DownloadOnly -FileBrowser +} +``` + +When used with `-DownloadOnly`, the browser downloads any file selected instead of rendering. The folders are rendered and not downloaded. + +## Static Routes order + +By default, Static routes are processed before any other route. There will be situations where you want normal routes to have priority over static ones. +For example, you have to hide or make some computation to a file or a folder before returning the result. + +```powershell +Start-PodeServer -ScriptBlock { + Add-PodeRoute -Method Get -Path '/LICENSE.txt' -ScriptBlock { + $value = @' +Don't kidding me. Nobody will believe that you want to read this legalise nonsense. +I want to be kind; this is a summary of the content: + +Nothing to report :D +'@ + Write-PodeTextResponse -Value $value + } + + Add-PodeStaticRoute -Path '/' -Source "./content" -FileBrowser +} +``` + +To change the default behaviour, you can use the `Web.Static.ValidateLast` property in the `server.psd1` configuration file, setting the value to `$True.` This will ensure that any static route is evaluated after any other route. diff --git a/docs/Tutorials/ScopedVariables.md b/docs/Tutorials/ScopedVariables.md new file mode 100644 index 000000000..06e7719b7 --- /dev/null +++ b/docs/Tutorials/ScopedVariables.md @@ -0,0 +1,99 @@ +# Scoped Variables + +You can create custom Scoped Variables within Pode, to allow for easier/quicker access to values without having to supply function calls every time within ScriptBlocks - such as those supplied to Routes, Middleware, etc. + +For example, the inbuilt `$state:` Scoped Variable is a quick way of calling `Get-PodeState` and `Set-PodeState`, but without having to write out those functions constantly! + +Pode has support for the following inbuilt Scoped Variables: + +* `$cache:` +* `$secret:` +* `$session:` +* `$state:` +* `$using:` + +The `$using:` Scoped Variable is a special case, as it only allows for the retrieval of a value, and not the setting of the value as well. + +## Creation + +To create a custom Scoped Variable you can use [`Add-PodeScopedVariable`](../../Functions/ScopedVariables/Add-PodeScopedVariable) with a unique Name. There are two ways to add a Scoped Variable: + +* A [simple](#simple-replace) Replacement conversion from `$var:` syntax to Get/Set function syntax. +* A more [advanced](#advanced) conversion strategy using a ScriptBlock. + +### Simple Replace + +The simple Replacement conversion using [`Add-PodeScopedVariable`](../../Functions/ScopedVariables/Add-PodeScopedVariable) requires you to supply a `-GetReplace` and an optional `-SetReplace` template strings. These template strings will be used appropriately replace `$var:` calls with the template Get/Set function calls. + +Within the template strings there is a special placeholder, `{{name}}`, which can be used. This placeholder is where the "name" from `$var:` will be used within the Get/Set replacement. + +Using the inbuilt `$state` Scoped Variable as an example, this conversion is done using the Get/Set replacement method. For this Scoped Variable we want: + +```powershell +$value = $state:Name +# to be replaced with +$value = (Get-PodeState -Name 'Name') + +$state:Name = 'Value' +# to be replace with +Set-PodeState -Name 'Name' -Value 'Value' +``` + +to achieve this, we can call [`Add-PodeScopedVariable`](../../Functions/ScopedVariables/Add-PodeScopedVariable) as follows: + +```powershell +Add-PodeScopedVariable -Name 'state' ` + -SetReplace "Set-PodeState -Name '{{name}}' -Value " ` + -GetReplace "Get-PodeState -Name '{{name}}'" +``` + +### Advanced + +A more advanced conversion can be achieved using [`Add-PodeScopedVariable`](../../Functions/ScopedVariables/Add-PodeScopedVariable) by supplying a `-ScriptBlock` instead of the Replace parameters. This ScriptBlock will be supplied with: + +* The ScriptBlock that needs converting. +* A SessionState object for when scoping is required for retrieving values (like `$using:`). +* A "Get" pattern which can be used for finding `$var:Name` syntaxes within the supplied ScriptBlock. +* A "Set" pattern which can be used for finding `$value = $var:Name` syntaxes within the supplied ScriptBlock. + +The ScriptBlock supplied to [`Add-PodeScopedVariable`](../../Functions/ScopedVariables/Add-PodeScopedVariable) should return a converted version of the ScriptBlock supplied to it. It should also return an optional array of values which need to be supplied to the converted ScriptBlock first. + +For example, if you wanted to add a custom `$config:` Scoped Variable, to simplify calling [`Get-PodeConfig`](../../Functions/Utilities/Get-PodeConfig), but you wanted to do this using [`Add-PodeScopedVariable`](../../Functions/ScopedVariables/Add-PodeScopedVariable)'s `-ScriptBlock` instead of the Replacement parameters, then you could do the following: + +```powershell +Add-PodeScopedVariable -Name 'config' -ScriptBlock { + param($ScriptBlock, $SessionState, $GetPattern, $SetPattern) + + # convert the scriptblock to a string, for searching + $strScriptBlock = "$($ScriptBlock)" + + # the "get" template to be used, to convert "$config:Name" syntax to "(Get-PodeConfig).Name" + $template = "(Get-PodeConfig).'{{name}}'" + + # loop through the scriptblock, replacing "$config:Name" syntax + while ($strScriptBlock -imatch $GetPattern) { + $getReplace = $template.Replace('{{name}}', $Matches['name']) + $strScriptBlock = $strScriptBlock.Replace($Matches['full'], "($($getReplace))") + } + + # convert string back to scriptblock, and return + return [scriptblock]::Create($strScriptBlock) +} +``` + +## Conversion + +If you have a ScriptBlock that you need to convert, in an ad-hoc manner, you can manually call [`Convert-PodeScopedVariables`](../../Functions/ScopedVariables/Convert-PodeScopedVariables) yourself. You should supply the `-ScriptBlock` to wish to convert, as well as an optional `-PSSession` SessionState from `$PSCmdlet.SessionState`, to this function: + +```powershell +# convert the scriptblock's scoped variables +$ScriptBlock, $usingVars = Convert-PodeScopedVariables -ScriptBlock $ScriptBlock -PSSession $PSCmdlet.SessionState + +# invoke the converted scriptblock, and supply any using variable values +$result = Invoke-PodeScriptBlock -ScriptBlock $ScriptBlock -UsingVariables $usingVars -Splat -Return +``` + +!!! note + If you don't supply a `-PSSession` then no `$using:` Scoped Variables will be converted. + +You can also supply one or more Scoped Variable Names to `-Exclude`, which will skip over converting these Scoped Variables in the supplied `-ScriptBlock`. diff --git a/docs/Tutorials/Scoping.md b/docs/Tutorials/Scoping.md index c11b7e44b..dfa1d3728 100644 --- a/docs/Tutorials/Scoping.md +++ b/docs/Tutorials/Scoping.md @@ -235,13 +235,20 @@ Prior to 2.0 if you wanted to use quick local variables in your Routes/etc, you The `$using:` syntax is supported in almost all `-ScriptBlock` parameters for the likes of: * Authentication +* Access +* Caching * Endware +* Events +* FileWatchers * Handlers * Logging * Middleware * Routes * Schedules +* Secrets * Timers +* Verbs +* WebSockets Below, the `$outer_msg` and `$inner_msg` variables can now be more simply referenced in a Route: @@ -259,6 +266,12 @@ Start-PodeServer -ScriptBlock { } ``` +!!! note + In some environments, or for some use cases like Pode.Web, the `$outer_msg` variables need to be created within the `Start-PodeServer` scriptblock due to scoping issues. + +!!! tip + You can create custom Scoped Variables like `$using:`, `$state:`, and `$session` using the documentation for [Scoped Variables](../ScopedVariables). + ## Secret Vaults This mostly only applies to vaults registered via the SecretManagement module, and its `Register-SecretVault` function. You can register vaults as the user that will run your Pode server, before you start the server using the normal `Register-SecretVault` function. On start, Pode will detect these vaults and will automatically register then within Pode for you - ready to be used for mounting secrets with [`Mount-PodeSecret`](../../Functions/Secrets/Mount-PodeSecret). diff --git a/docs/Tutorials/Tasks.md b/docs/Tutorials/Tasks.md index b7d44a02b..dc7cbf47c 100644 --- a/docs/Tutorials/Tasks.md +++ b/docs/Tutorials/Tasks.md @@ -2,7 +2,7 @@ A Task in Pode is a script that you can later invoke either asynchronously, or synchronously. They can be invoked many times, and they also support returning values from them for later use. -Similar to [Schedules](../Schedules), Tasks also run in their own separate runspaces; meaning you can have long or short running tasks. By default up to a maximum of 2 tasks can run concurrently, but this can be changed by using [`Set-PodeTaskConcurrency`](../../Functions/Tasks/Set-PodeTaskConcurrency). +Similar to [Schedules](../Schedules), Tasks also run in their own separate runspaces; meaning you can have long or short running tasks. By default up to a maximum of 2 tasks can run concurrently, but this can be changed by using [`Set-PodeTaskConcurrency`](../../Functions/Tasks/Set-PodeTaskConcurrency). When more tasks are invoked than can be run concurrently, tasks will be added to the task queue and will run once there is available resource in the thread pool. Behind the scenes there is a a Timer created that will automatically clean-up any completed tasks. Any task that has been completed for 1+ minutes will be disposed of to free up resources - there are functions which will let you clean-up tasks more quickly. @@ -43,7 +43,7 @@ Start-PodeServer -EnablePool Tasks { You can supply custom arguments to your tasks by using the `-ArgumentList` parameter. Similar to schedules, for tasks the `-ArgumentList` is a hashtable; this is done because parameters to the `-ScriptBlock` are splatted in, and the parameter names are literal. -For example, the first parameter to a task is always `$Event` - this contains the `.Lockable` object. Other parameters come from any Key/Values contained with the optional `-ArgumentList`: +There is always a parameter added to each task invocation in the `-Event` argument - this contains the `.Lockable` object. You can safely ignore/leave the parameter unbound if you do not need it. Other parameters come from any Key/Values contained with the optional `-ArgumentList`: ```powershell Add-PodeTask -Name 'Example' -ArgumentList @{ Name = 'Rick'; Environment = 'Multiverse' } -ScriptBlock { @@ -51,6 +51,18 @@ Add-PodeTask -Name 'Example' -ArgumentList @{ Name = 'Rick'; Environment = 'Mult } ``` +Tasks parameters **must** be bound in the param block in order to be used, but the values for the paramters can be set through the `-ArgumentList` hashtable parameter in either the Add-PodeTask definition or when invoking the task. The following snippet would populate the parameters to the task with the same values as the above example but the `-ArgumentList` parameter is populated during invocation. Note that Keys in the `-ArgumentList` hashtable parameter set during invocation override the same Keys set during task creation: + +```powershell +Add-PodeTask -Name 'Example' -ScriptBlock { + param($Event, $Name, $Environment) +} + +Add-PodeRoute -Method Get -Path '/invoke-task' -ScriptBlock { + Invoke-PodeTask -Name 'example' -ArgumentList @{ Name = 'Rick'; Environment = 'Multiverse' } +} +``` + !!! important In tasks, your scriptblock parameter names must be exact - including case-sensitivity. This is because the arguments are splatted into a runspace. If you pass in an argument called "Names", the param-block must have `$Names` exactly. Furthermore, the event parameter *must* be called `$Event`. diff --git a/docs/Tutorials/WebEvent.md b/docs/Tutorials/WebEvent.md index 93167b1e5..b90920a1c 100644 --- a/docs/Tutorials/WebEvent.md +++ b/docs/Tutorials/WebEvent.md @@ -15,49 +15,50 @@ Add-PodeRoute -Method Get -Path '/' -ScriptBlock { !!! warning It is advised not to directly alter these values, other than the ones through the documentation that say you can - such as Session Data. -| Name | Type | Description | Docs | -| ---- | ---- | ----------- | ---- | -| Auth | hashtable | Contains the information on the currently authenticated user from the `Add-PodeAuth` methods - the user's details can be further accessed in the sub `.User` property | [link](../Authentication/Overview/#users) | -| ContentType | string | The content type of the data in the Request's payload | n/a | -| Cookies | hashtable | Contains all cookies parsed from the Request's headers - it's best to use Pode's Cookie functions to access/change Cookies | [link](../Cookies) | -| Data | hashtable | Contains the parsed items from the Request's payload | [link](../Routes/Overview/#payloads) | -| Endpoint | hashtable | Contains the Address and Protocol of the endpoint being hit - such as "pode.example.com" or "127.0.0.2", or HTTP or HTTPS for the Protocol | [link](../Endpoints/Basics), [properties](#endpoints) | -| ErrorType | string | Set by the current Route being hit, this is the content type of the Error Page that will be used if an error occurs | [link](../Routes/Utilities/ErrorPages) | -| Files | hashtable | Contains any file data from the Request's payload | [link](../Misc/UploadFiles) | -| Lockable | hashtable | A synchronized hashtable that can be used with `Lock-PodeObject` | n/a | -| Method | string | The current HTTP method of the Request | [link](../Routes/Overview) | -| OnEnd | array | An array of extra Endware scriptblocks | [link](../Endware) | -| Parameters | hashtable | Contains the parsed parameter values from the Route's path | [link](../Routes/Overview/#parameters) | -| Path | string | The current path of the Request, after the endpoint - such as "/about" | [link](../Routes/Overview) | -| PendingCookies | hashtable | Contains cookies that will be written back on the Response - it's best to use Pode's Cookies functions to access/change Cookies | [link](../Cookies) | -| Query | hashtable | Contains the parsed items from the Request's query string | [link](../Routes/Overview/#query-strings) | -| Request | object | The raw Request object | [properties](#request) | -| Response | object | The raw Response object | [properties](#response) | -| Route | hashtable | The current Route that is being invoked - the properties here are the same as called [`Get-PodeRoute`](../../Functions/Routes/Get-PodeRoute) | [link](../Routes/Overview) | -| Session | hashtable | Contains details about, and any data stored in the current session - this data can be accessed in the sub `.Data` property | [link](../Middleware/Types/Sessions) | -| StaticContent | hashtable | Contains details about the source path, if the route is a custom Static Route | [link](../Routes/Utilities/StaticContent), [properties](#static-content) | -| Streamed | bool | Specifies whether the current server type uses streams for the Request/Response, or raw strings | n/a | -| Timestamp | datetime | The current date and time of the Request | n/a | +| Name | Type | Description | Docs | +| -------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| Auth | hashtable | Contains the information on the currently authenticated user from the `Add-PodeAuth` methods - the user's details can be further accessed in the sub `.User` property | [link](../Authentication/Overview/#users) | +| ContentType | string | The content type of the data in the Request's payload | n/a | +| Cookies | hashtable | Contains all cookies parsed from the Request's headers - it's best to use Pode's Cookie functions to access/change Cookies | [link](../Cookies) | +| Data | hashtable | Contains the parsed items from the Request's payload | [link](../Routes/Overview/#payloads) | +| Endpoint | hashtable | Contains the Address and Protocol of the endpoint being hit - such as "pode.example.com" or "127.0.0.2", or HTTP or HTTPS for the Protocol | [link](../Endpoints/Basics), [properties](#endpoints) | +| ErrorType | string | Set by the current Route being hit, this is the content type of the Error Page that will be used if an error occurs | [link](../Routes/Utilities/ErrorPages) | +| Files | hashtable | Contains any file data from the Request's payload | [link](../Misc/UploadFiles) | +| Lockable | hashtable | A synchronized hashtable that can be used with `Lock-PodeObject` | n/a | +| Metadata | hashtable | A hashtable which can be used by your scripts, or other modules, to store data appropriate for the current Request | n/a | +| Method | string | The current HTTP method of the Request | [link](../Routes/Overview) | +| OnEnd | array | An array of extra Endware scriptblocks | [link](../Endware) | +| Parameters | hashtable | Contains the parsed parameter values from the Route's path | [link](../Routes/Overview/#parameters) | +| Path | string | The current path of the Request, after the endpoint - such as "/about" | [link](../Routes/Overview) | +| PendingCookies | hashtable | Contains cookies that will be written back on the Response - it's best to use Pode's Cookies functions to access/change Cookies | [link](../Cookies) | +| Query | hashtable | Contains the parsed items from the Request's query string | [link](../Routes/Overview/#query-strings) | +| Request | object | The raw Request object | [properties](#request) | +| Response | object | The raw Response object | [properties](#response) | +| Route | hashtable | The current Route that is being invoked - the properties here are the same as called [`Get-PodeRoute`](../../Functions/Routes/Get-PodeRoute) | [link](../Routes/Overview) | +| Session | hashtable | Contains details about, and any data stored in the current session - this data can be accessed in the sub `.Data` property | [link](../Middleware/Types/Sessions) | +| StaticContent | hashtable | Contains details about the source path, if the route is a custom Static Route | [link](../Routes/Utilities/StaticContent), [properties](#static-content) | +| Streamed | bool | Specifies whether the current server type uses streams for the Request/Response, or raw strings | n/a | +| Timestamp | datetime | The current date and time of the Request | n/a | ### Endpoints These are the properties available for `$WebEvent.Endpoint` -| Name | Type | Description | Docs | -| ---- | ---- | ----------- | ---- | -| Address | string | The ip/hostname being used for the Request. ie: 127.0.0.1 or example.com | n/a | -| Name | string | The name of the Pode Endpoint being used for the Request | [link](../Endpoints/Basics/#endpoint-names) | -| Protocol | string | The protocol being used for the Request. ie: HTTP, HTTPS, WS, WSS, etc. | n/a | +| Name | Type | Description | Docs | +| -------- | ------ | ------------------------------------------------------------------------ | ------------------------------------------- | +| Address | string | The ip/hostname being used for the Request. ie: 127.0.0.1 or example.com | n/a | +| Name | string | The name of the Pode Endpoint being used for the Request | [link](../Endpoints/Basics/#endpoint-names) | +| Protocol | string | The protocol being used for the Request. ie: HTTP, HTTPS, WS, WSS, etc. | n/a | ### Static Content These are the properties available for `$WebEvent.StaticContent` -| Name | Type | Description | Docs | -| ---- | ---- | ----------- | ---- | -| IsCachable | bool | Whether or not the file should be cached on the client side | n/a | -| IsDownload | bool | Whether or not the file should be attached or rendered | n/a | -| Source | string | The local path, using PSDrives, to the file on the server | n/a | +| Name | Type | Description | Docs | +| ---------- | ------ | ----------------------------------------------------------- | ---- | +| IsCachable | bool | Whether or not the file should be cached on the client side | n/a | +| IsDownload | bool | Whether or not the file should be attached or rendered | n/a | +| Source | string | The local path, using PSDrives, to the file on the server | n/a | ### Request @@ -69,44 +70,44 @@ These are the properties available for `$WebEvent.Request` !!! warning Changing properties on this object could cause errors, unwanted behaviour, or a full server crash. Only edit them if you know what you're doing. Same for calling any methods. -| Name | Type | Description | Example | -| ---- | ---- | ----------- | ------- | -| Address | string | The address being used by the Request. This will favour hostnames over IPs | - | -| AllowClientCertificate | bool | Whether Pode should expect, and process, and client certificates | - | -| AwaitingBody | bool | If the request is chunked, this flags if Pode is still awaiting for the whole body to be sent | - | -| Body | string | The textually encoded version of the RawBody | - | -| Certificate | X509Certificate | The certificate being used for SSL connections. Usually defined from [`Add-PodeEndpoint`](../../Functions/Core/Add-PodeEndpoint) | - | -| ClientCertificate | X509Certificate2 | If being used, the client certificate supplied on the Request | - | -| ClientCertificateErrors | SslPolicyErrors | Contains any errors that might have occurred while validating the client certificate. Pode ignores these by default, so they will need checking the [Client Certificate Authenication](../Authentication/Methods/ClientCertificate) | - | -| CloseImmediately | bool | Whether this Request should be closed immediately. Used internally, you'll likely never see this set to true | - | -| ContentEncoding | Encoding | The encoding used for the content | UTF8 | -| ContentLength | int | The size of the content in the Request's payload | - | -| ContentType | string | The type of content being supplied in the Request's payload | application/json | -| Error | HttpRequestException | Contains any errors thrown internally, that will be bubbled back up to Pode for logging | | -| Form | PodeForm | Contains information about any form elements sent in the Request | - | -| Headers | Hashtable | A collectio of every header sent in the Request | - | -| Host | string | The ip/hostname used for the Request | 127.0.0.1, example.com | -| HttpMethod | string | The HTTP method of the current Request | GET, POST, etc. | -| InputStream | Stream | The stream used to read the inbound connection's data | - | -| IsAborted | bool | Whether the Request should be aborted. Used internally, you'll likely never see this set to true | - | -| IsDisposed | bool | Whether the current Request is disposed | - | -| IsProcessable | bool | Whether this Request should be processed. Used internally, you'll likely never see this set to false | - | -| IsSsl | bool | Whether the connection is currently over SSL or not | - | -| KeepAlive | bool | Whether the connection should be kept alive, or terminated after use | - | -| LocalEndPoint | EndPoint | Details about the local connection | - | -| Protocol | string | The protocol type being used | HTTP/1.1 | -| Protocols | SslProtocols | The SSL protocols allowed to be used for connections | SSL3, TLS1.2 | -| ProtocolVersion | string | The protocol version of the protocol type | 1.1 | -| QueryString | NameValueCollection | A collection of the key/values supplied on the Request's query string | - | -| RawBody | byte[] | The raw bytes of the Request's payload | - | -| RemoteEndPoint | EndPoint | Details about the remote connection | - | -| Scheme | string | The connection scheme being used | HTTP, HTTPS, etc. | -| SslUpgraded | bool | Whether this connection has been upgraded to SSL. Used for implicit connections | - | -| TlsMode | PodeTlsMode | Whether the connection is using implicit or explicit TLS | - | -| TransferEncoding | string | The transfer encoding used for the content | gzip, chunked, identity | -| Url | Uri | The whole Request URL that was made | http://example.com?name=value | -| UrlReferrer | string | The referred of the Request | - | -| UserAgent | string | The user agent of where the Request originated | - | +| Name | Type | Description | Example | +| ----------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------- | +| Address | string | The address being used by the Request. This will favour hostnames over IPs | - | +| AllowClientCertificate | bool | Whether Pode should expect, and process, and client certificates | - | +| AwaitingBody | bool | If the request is chunked, this flags if Pode is still awaiting for the whole body to be sent | - | +| Body | string | The textually encoded version of the RawBody | - | +| Certificate | X509Certificate | The certificate being used for SSL connections. Usually defined from [`Add-PodeEndpoint`](../../Functions/Core/Add-PodeEndpoint) | - | +| ClientCertificate | X509Certificate2 | If being used, the client certificate supplied on the Request | - | +| ClientCertificateErrors | SslPolicyErrors | Contains any errors that might have occurred while validating the client certificate. Pode ignores these by default, so they will need checking the [Client Certificate Authenication](../Authentication/Methods/ClientCertificate) | - | +| CloseImmediately | bool | Whether this Request should be closed immediately. Used internally, you'll likely never see this set to true | - | +| ContentEncoding | Encoding | The encoding used for the content | UTF8 | +| ContentLength | int | The size of the content in the Request's payload | - | +| ContentType | string | The type of content being supplied in the Request's payload | application/json | +| Error | HttpRequestException | Contains any errors thrown internally, that will be bubbled back up to Pode for logging | | +| Form | PodeForm | Contains information about any form elements sent in the Request | - | +| Headers | Hashtable | A collectio of every header sent in the Request | - | +| Host | string | The ip/hostname used for the Request | 127.0.0.1, example.com | +| HttpMethod | string | The HTTP method of the current Request | GET, POST, etc. | +| InputStream | Stream | The stream used to read the inbound connection's data | - | +| IsAborted | bool | Whether the Request should be aborted. Used internally, you'll likely never see this set to true | - | +| IsDisposed | bool | Whether the current Request is disposed | - | +| IsProcessable | bool | Whether this Request should be processed. Used internally, you'll likely never see this set to false | - | +| IsSsl | bool | Whether the connection is currently over SSL or not | - | +| KeepAlive | bool | Whether the connection should be kept alive, or terminated after use | - | +| LocalEndPoint | EndPoint | Details about the local connection | - | +| Protocol | string | The protocol type being used | HTTP/1.1 | +| Protocols | SslProtocols | The SSL protocols allowed to be used for connections | SSL3, TLS1.2 | +| ProtocolVersion | string | The protocol version of the protocol type | 1.1 | +| QueryString | NameValueCollection | A collection of the key/values supplied on the Request's query string | - | +| RawBody | byte[] | The raw bytes of the Request's payload | - | +| RemoteEndPoint | EndPoint | Details about the remote connection | - | +| Scheme | string | The connection scheme being used | HTTP, HTTPS, etc. | +| SslUpgraded | bool | Whether this connection has been upgraded to SSL. Used for implicit connections | - | +| TlsMode | PodeTlsMode | Whether the connection is using implicit or explicit TLS | - | +| TransferEncoding | string | The transfer encoding used for the content | gzip, chunked, identity | +| Url | Uri | The whole Request URL that was made | http://example.com?name=value | +| UrlReferrer | string | The referred of the Request | - | +| UserAgent | string | The user agent of where the Request originated | - | ### Response @@ -118,18 +119,18 @@ These are the properties available for `$WebEvent.Response` !!! warning Changing properties on this object could cause errors, unwanted behaviour, or a full server crash. Only edit them if you know what you're doing. Same for calling any methods. -| Name | Type | Description | Example | -| ---- | ---- | ----------- | ------- | -| ContentLength64 | long | The length of the data that is being sent back | - | -| ContentType | string | The content type of the data that's being sent back | application/json | -| Headers | PodeResponseHeaders | A collection of headers that should be sent back to the client | - | -| HttpResponseLine | string | Internal Only. This is just a prebuilt value, which represents the first line of a raw HTTP Response | - | -| IsDisposed | bool | Whether the current Response is disposed | - | -| OutputStream | MemoryStream | The stream that's used to write data back to the client | - | -| SendChunked | bool | Whether or not the response should be sent back in chunks | - | -| Sent | bool | Whether or not this Response has already been sent tot the client | - | -| StatusCode | int | The status code to send back to the client | 200, 401, 500, etc. | -| StatusDescription | string | The statuc description to send back, based on the status code | OK, Not Found, etc. | +| Name | Type | Description | Example | +| ----------------- | ------------------- | ---------------------------------------------------------------------------------------------------- | ------------------- | +| ContentLength64 | long | The length of the data that is being sent back | - | +| ContentType | string | The content type of the data that's being sent back | application/json | +| Headers | PodeResponseHeaders | A collection of headers that should be sent back to the client | - | +| HttpResponseLine | string | Internal Only. This is just a prebuilt value, which represents the first line of a raw HTTP Response | - | +| IsDisposed | bool | Whether the current Response is disposed | - | +| OutputStream | MemoryStream | The stream that's used to write data back to the client | - | +| SendChunked | bool | Whether or not the response should be sent back in chunks | - | +| Sent | bool | Whether or not this Response has already been sent tot the client | - | +| StatusCode | int | The status code to send back to the client | 200, 401, 500, etc. | +| StatusDescription | string | The statuc description to send back, based on the status code | OK, Not Found, etc. | ## Customise diff --git a/docs/index.md b/docs/index.md index c5d175bd9..533d2603b 100644 --- a/docs/index.md +++ b/docs/index.md @@ -23,8 +23,7 @@ Pode is a Cross-Platform framework to create web servers that host REST APIs, We * Azure Functions, AWS Lambda, and IIS support * OpenAPI, Swagger, and ReDoc support * Listen on a single or multiple IP address/hostnames -* Cross-platform support for HTTP(S), SMTP(S), and TCP(S) -* Cross-platform support for WebSockets, including secure WebSockets +* Cross-platform support for HTTP(S), WS(S), SSE, SMTP(S), and TCP(S) * Host REST APIs, Web Pages, and Static Content (with caching) * Support for custom error pages * Request and Response compression using GZip/Deflate @@ -44,6 +43,7 @@ Pode is a Cross-Platform framework to create web servers that host REST APIs, We * Generate/bind self-signed certificates * Secret management support to load secrets from vaults * Support for File Watchers +* In-memory caching, with optional support for external providers (such as Redis) * (Windows) Open the hosted server as a desktop application ## 🏢 Companies using Pode diff --git a/docs/release-notes.md b/docs/release-notes.md index eec9e4468..4883f37ff 100644 --- a/docs/release-notes.md +++ b/docs/release-notes.md @@ -1,5 +1,48 @@ # Release Notes +## v2.10.0 + +Date: 15th April 2024 + +```plain +### Features +* #1197: Adds support for inbuilt caching of values +* #1238: Adds support for creating custom scoped variables +* #1256: Adds support for converting HTTP connections into SSE connections +* #1266: Adds support for a File Browsing page on static routes (thanks @mdaneri!) + +### Enhancements +* #1136: Adds full support for OpenAPI v3.0.3 and v3.1 (**huge** thanks to @mdaneri! 🎉) +* #1239: Adds the missing HTTP 425 response status code +* #1242: Adds support for enabling "session per browser Tab" +* #1265: Adds support for customising the default folder paths, such as `/views` (thanks @mdaneri!) +* #1267: Adds support for `-DualMode` on `Add-PodeEndpoint`, allowing endpoints to listen on IPv4 and IPv6 +* #1276: Adds supported and EOL PowerShell checks during server start (thanks @mdaneri!) + +### Bugs +* #1246: Fixes static route ordering, and redirecting to default file +* #1258: Fixes a script modification issue when using scriptblocks with `Add-PodePage` (thanks @mdaneri!) +* #1279: Fixes a scoping issue when using `Add-PodeRouteGroup` +* #1281: Removes an erroneous `break` command when broadcasting messages to websockets +* #1138: Fixes the status code for expired JWT, from 400 to 401 (thanks @mdaneri!) + +### Documentation +* #1232: Updates Sessions page to fix Redis example (thanks @Szeraax!) +* #1234: Updates Tasks page to explain Task concurrency and Argument passing (thanks @Szeraax!) +* #1276: Adds supported PowerShell documentation (thanks @mdaneri!) +* #1277: Fix for missing merged authentication documentation +* #1282: Adds documentation describing how to debug Pode + +### Packaging +* #1261: Add support to the build script for Linux and Mac (thanks @mdaneri!) +* #1262: Migrates tests to Pester 5.5.0 (thanks @mdaneri!) +* #1269: Adds PSScriptAnalyzerSettings to run during CI pipelines (thanks @mdaneri!) +* #1264, #1273: Adds CI pipelines per supported PowerShell version (thanks @mdaneri!) +* #1276: Adds .NET8 support (thanks @mdaneri!) +* #1284: Adds additional unit tests to verify PowerShell syntax and structure +* #1286: General tidy-up and release prep +``` + ## v2.9.0 Date: 30th October 2023 diff --git a/examples/FileBrowser/FileBrowser.ps1 b/examples/FileBrowser/FileBrowser.ps1 new file mode 100644 index 000000000..517f459e3 --- /dev/null +++ b/examples/FileBrowser/FileBrowser.ps1 @@ -0,0 +1,58 @@ +$FileBrowserPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Path +$podePath = Split-Path -Parent -Path (Split-Path -Parent -Path $FileBrowserPath) +if (Test-Path -Path "$($podePath)/src/Pode.psm1" -PathType Leaf) { + Import-Module "$($podePath)/src/Pode.psm1" -Force -ErrorAction Stop +} +else { + Import-Module -Name 'Pode' +} + +$directoryPath = $podePath +# Start Pode server +Start-PodeServer -ScriptBlock { + + Add-PodeEndpoint -Address localhost -Port 8081 -Protocol Http -Default + + New-PodeLoggingMethod -Terminal | Enable-PodeRequestLogging + New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging + + # setup basic auth (base64> username:password in header) + New-PodeAuthScheme -Basic -Realm 'Pode Static Page' | Add-PodeAuth -Name 'Validate' -Sessionless -ScriptBlock { + param($username, $password) + + # here you'd check a real user storage, this is just for example + if ($username -eq 'morty' -and $password -eq 'pickle') { + return @{ + User = @{ + ID = 'M0R7Y302' + Name = 'Morty' + Type = 'Human' + } + } + } + + return @{ Message = 'Invalid details supplied' } + } + Add-PodeRoute -Method Get -Path '/LICENSE.txt' -ScriptBlock { + $value = @' +Don't kidding me. Nobody will believe that you want to read this legalise nonsense. +I want to be kind; this is a summary of the content: + +Nothing to report :D +'@ + Write-PodeTextResponse -Value $value + } + Add-PodeStaticRouteGroup -FileBrowser -Routes { + + Add-PodeStaticRoute -Path '/' -Source $using:directoryPath + Add-PodeStaticRoute -Path '/download' -Source $using:directoryPath -DownloadOnly + Add-PodeStaticRoute -Path '/nodownload' -Source $using:directoryPath + Add-PodeStaticRoute -Path '/any/*/test' -Source $using:directoryPath + Add-PodeStaticRoute -Path '/auth' -Source $using:directoryPath -Authentication 'Validate' + } + Add-PodeStaticRoute -Path '/nobrowsing' -Source $directoryPath + + Add-PodeRoute -Method Get -Path '/attachment/*/test' -ScriptBlock { + Set-PodeResponseAttachment -Path 'ruler.png' + } +} diff --git a/examples/FileBrowser/public/ruler.png b/examples/FileBrowser/public/ruler.png new file mode 100644 index 000000000..4dff97339 Binary files /dev/null and b/examples/FileBrowser/public/ruler.png differ diff --git a/examples/OpenApiTuttiFrutti.ps1 b/examples/OpenApiTuttiFrutti.ps1 new file mode 100644 index 000000000..691c1043b --- /dev/null +++ b/examples/OpenApiTuttiFrutti.ps1 @@ -0,0 +1,974 @@ +$path = Split-Path -Parent -Path (Split-Path -Parent -Path $MyInvocation.MyCommand.Path) +if (Test-Path -Path "$($path)/src/Pode.psm1" -PathType Leaf) { + Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop +} else { + Import-Module -Name 'Pode' +} + +Start-PodeServer -Threads 2 -ScriptBlock { + Add-PodeEndpoint -Address localhost -Port 8081 -Protocol Http -Default + New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging + $InfoDescription = @' +This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about Swagger at [http://swagger.io](http://swagger.io). +In the third iteration of the pet store, we've switched to the design first approach! +You can now help us improve the API whether it's by making changes to the definition itself or to the code. +That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + +Some useful links: +- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) +- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) +'@ + + + + #Enable-PodeOpenApi -Path '/docs/openapi' -OpenApiVersion '3.0.0' -EnableSchemaValidation -DisableMinimalDefinitions -DefaultResponses @{} + # New-PodeOAExternalDoc -Name 'SwaggerDocs' -Description 'Find out more about Swagger' -Url 'http://swagger.io' + # Add-PodeOAExternalDoc -Reference 'SwaggerDocs' + + Enable-PodeOpenApi -Path '/docs/openapi/v3.0' -OpenApiVersion '3.0.3' -EnableSchemaValidation -DisableMinimalDefinitions -NoDefaultResponses -DefinitionTag 'v3' + Enable-PodeOpenApi -Path '/docs/openapi/v3.1' -OpenApiVersion '3.1.0' -EnableSchemaValidation -DisableMinimalDefinitions -NoDefaultResponses -DefinitionTag 'v3.1' + $swaggerDocs = New-PodeOAExternalDoc -Description 'Find out more about Swagger' -Url 'http://swagger.io' + + $swaggerDocs | Add-PodeOAExternalDoc -DefinitionTag 'v3', 'v3.1' + + + # Add-PodeOAInfo -Title 'Swagger Petstore - OpenAPI 3.0' -Version 1.0.17 -Description $InfoDescription -TermsOfService 'http://swagger.io/terms/' -LicenseName 'Apache 2.0' -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' -ContactName 'API Support' -ContactEmail 'apiteam@swagger.io' -ContactUrl 'http://example.com/support' + + + Add-PodeOAServerEndpoint -url '/api/v3' -Description 'default endpoint' -DefinitionTag 'v3', 'v3.1' + + Add-PodeOAInfo -Title 'Swagger Petstore - OpenAPI 3.0' -Version 1.0.17 -Description $InfoDescription -TermsOfService 'http://swagger.io/terms/' -LicenseName 'Apache 2.0' ` + -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' -ContactName 'API Support' -ContactEmail 'apiteam@swagger.io' -DefinitionTag 'v3' + + Add-PodeOAInfo -Title 'Swagger Petstore - OpenAPI 3.1' -Version 1.0.17 -Description $InfoDescription -TermsOfService 'http://swagger.io/terms/' -LicenseName 'Apache 2.0' ` + -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' -ContactName 'API Support' -ContactEmail 'apiteam@swagger.io' -DefinitionTag 'v3.1' + + + Enable-PodeOAViewer -Type Swagger -Path '/docs/swagger' -DefinitionTag 'v3' + Enable-PodeOAViewer -Type ReDoc -Path '/docs/redoc' -DarkMode -DefinitionTag 'v3' + Enable-PodeOAViewer -Type RapiDoc -Path '/docs/rapidoc' -DarkMode -DefinitionTag 'v3' + Enable-PodeOAViewer -Type StopLight -Path '/docs/stoplight' -DarkMode -DefinitionTag 'v3' + Enable-PodeOAViewer -Type Explorer -Path '/docs/explorer' -DarkMode -DefinitionTag 'v3' + Enable-PodeOAViewer -Type RapiPdf -Path '/docs/rapipdf' -DarkMode -DefinitionTag 'v3' + Enable-PodeOAViewer -Editor -DefinitionTag 'v3' + Enable-PodeOAViewer -Bookmarks -Path '/docs' -DefinitionTag 'v3' + + + Enable-PodeOAViewer -Type Swagger -Path '/docs/v3.1/swagger' -DefinitionTag 'v3.1' + Enable-PodeOAViewer -Type ReDoc -Path '/docs/v3.1/redoc' -DarkMode -DefinitionTag 'v3.1' + Enable-PodeOAViewer -Type RapiDoc -Path '/docs/v3.1/rapidoc' -DarkMode -DefinitionTag 'v3.1' + Enable-PodeOAViewer -Type StopLight -Path '/docs/v3.1/stoplight' -DarkMode -DefinitionTag 'v3.1' + Enable-PodeOAViewer -Type Explorer -Path '/docs/v3.1/explorer' -DarkMode -DefinitionTag 'v3.1' + + Enable-PodeOAViewer -Bookmarks -Path '/docs/v3.1' -DefinitionTag 'v3.1' + + Select-PodeOADefinition -Tag 'v3', 'v3.1' -Scriptblock { + + Add-PodeOATag -Name 'user' -Description 'Operations about user' -ExternalDoc $swaggerDocs + Add-PodeOATag -Name 'store' -Description 'Access to Petstore orders' -ExternalDoc $swaggerDocs + Add-PodeOATag -Name 'pet' -Description 'Everything about your Pets' -ExternalDoc $swaggerDocs + + + <# Add-PodeOAComponentSchema -Name 'Address' -Schema ( + New-PodeOAObjectProperty -Name 'Address' -XmlName 'address' } -Description 'Shipping Address' -Properties ( + New-PodeOAStringProperty -Name 'street' -Example '437 Lytton' -Required | + New-PodeOAStringProperty -Name 'city' -Example 'Palo Alto' -Required | + New-PodeOAStringProperty -Name 'state' -Example 'CA' -Required | + New-PodeOAStringProperty -Name 'zip' -Example '94031' -Required + )) + Merge-PodeOAProperty -Type OneOf -ObjectDefinitions @( + (New-PodeOAIntProperty -Name 'userId' -Object), + (New-PodeOAStringProperty -Name 'name' -Object), + (New-PodeOABoolProperty -Name 'enabled' -Object) + )|Add-PodeOAComponentSchema -Name 'Test123' + + New-PodeOAStringProperty -Name 'lastName' -Example 'James' | + New-PodeOAObjectProperty -Name 'User' -XmlName 'user' } -Properties ( + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 1 -ReadOnly | + New-PodeOAStringProperty -Name 'username' -Example 'theUser' -Required ) | + New-PodeOAStringProperty -Name 'username' -Example 'theUser' -Required | + New-PodeOAStringProperty -Name 'firstName' -Example 'John' | + New-PodeOAStringProperty -Name 'lastName' -Example 'James' | + New-PodeOAObjectProperty -Name 'test' | Add-PodeOAComponentSchema -Name 'Test' + +#> + New-PodeOAStringProperty -Name 'street' -Example '437 Lytton' -Required | + New-PodeOAStringProperty -Name 'city' -Example 'Palo Alto' -Required | + New-PodeOAStringProperty -Name 'state' -Example 'CA' -Required | + New-PodeOAStringProperty -Name 'zip' -Example '94031' -Required | + New-PodeOAObjectProperty -Name 'Address' -XmlName 'address' -Description 'Shipping Address' | + Add-PodeOAComponentSchema -Name 'Address' + + + New-PodeOAIntProperty -Name 'id'-Format Int64 -ReadOnly -Example 10 | + New-PodeOAIntProperty -Name 'petId' -Format Int64 -Example 198772 | + New-PodeOAIntProperty -Name 'quantity' -Format Int32 -Example 7 | + New-PodeOAStringProperty -Name 'shipDate' -Format Date-Time | + New-PodeOAStringProperty -Name 'status' -Description 'Order Status' -Example 'approved' -Enum @('placed', 'approved', 'delivered') | + New-PodeOABoolProperty -Name 'complete' | + New-PodeOASchemaProperty -Name 'Address' -Reference 'Address' | + New-PodeOAObjectProperty -Name 'Order' -XmlName 'order' -AdditionalProperties (New-PodeOAStringProperty ) | + Add-PodeOAComponentSchema -Name 'Order' + + Add-PodeOAComponentSchema -Name 'Category' -Schema ( + New-PodeOAObjectProperty -Name 'Category' -XmlName 'category' -Properties ( + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 1 | + New-PodeOAStringProperty -Name 'name' -Example 'Dogs' + )) + + Add-PodeOAComponentSchema -Name 'User' -Schema ( + New-PodeOAObjectProperty -Name 'User' -XmlName 'user' -Properties ( + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 1 -ReadOnly | + New-PodeOAStringProperty -Name 'username' -Example 'theUser' -Required | + New-PodeOAStringProperty -Name 'firstName' -Example 'John' | + New-PodeOAStringProperty -Name 'lastName' -Example 'James' | + New-PodeOAStringProperty -Name 'email' -Format email -Example 'john@email.com' | + New-PodeOAStringProperty -Name 'lastName' -Example 'James' | + New-PodeOAStringProperty -Name 'password' -Format Password -Example '12345' -Required | + New-PodeOAStringProperty -Name 'phone' -Example '12345' | + New-PodeOAIntProperty -Name 'userStatus'-Format int32 -Description 'User Status' -Example 1 + )) + + Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'Address', 'User' | Add-PodeOAComponentSchema -Name 'aaaaa' + Add-PodeOAComponentSchema -Name 'Tag' -Component ( + New-PodeOAObjectProperty -Name 'Tag' -XmlName 'tag' -Properties ( + New-PodeOAIntProperty -Name 'id'-Format Int64 | + New-PodeOAStringProperty -Name 'name' + )) + + Add-PodeOAComponentSchema -Name 'Pet' -Component ( + New-PodeOAObjectProperty -Name 'Pet' -XmlName 'pet' -Properties ( + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example @(10, 2, 4) -ReadOnly | + New-PodeOAStringProperty -Name 'name' -Example 'doggie' -Required | + New-PodeOASchemaProperty -Name 'category' -Reference 'Category' | + New-PodeOAStringProperty -Name 'petType' -Example 'dog' -Required | + New-PodeOAStringProperty -Name 'photoUrls' -Array | + New-PodeOASchemaProperty -Name 'tags' -Reference 'Tag' | + New-PodeOAStringProperty -Name 'status' -Description 'pet status in the store' -Enum @('available', 'pending', 'sold') + )) + + Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'Pet', ( + New-PodeOAStringProperty -Name 'huntingSkill' -Description 'The measured skill for hunting' -Enum @( 'clueless', 'lazy', 'adventurous', 'aggressive') | New-PodeOAObjectProperty + ) | Add-PodeOAComponentSchema -Name 'NewCat' + + #XML teest + New-PodeOAIntProperty -Name 'id' -Format Int32 -XmlAttribute | New-PodeOAStringProperty -Name 'name' -XmlPrefix 'sample' -XmlNamespace 'http://example.com/schema/sample' | + New-PodeOAObjectProperty | Add-PodeOAComponentSchema -Name 'XmlPrefixAndNamespace' + + New-PodeOAStringProperty -Array -XmlItemName 'animal' | Add-PodeOAComponentSchema -Name 'animals' + + New-PodeOAStringProperty -Array -XmlItemName 'animal' -XmlName 'aliens' | Add-PodeOAComponentSchema -Name 'AnimalsNoAliens' + + New-PodeOAStringProperty -Array -XmlWrapped | Add-PodeOAComponentSchema -Name 'WrappedAnimals' + + New-PodeOAStringProperty -Array -XmlWrapped -XmlItemName 'animal' | Add-PodeOAComponentSchema -Name 'WrappedAnimal' + + New-PodeOAStringProperty -Array -XmlWrapped -XmlItemName 'animal' -XmlName 'aliens' | Add-PodeOAComponentSchema -Name 'WrappedAliens' + + New-PodeOAStringProperty -Array -XmlWrapped -XmlName 'aliens' | Add-PodeOAComponentSchema -Name 'WrappedAliensWithItems' + + + New-PodeOAStringProperty -Name 'name' | + New-PodeOAStringProperty -Name 'type' | + New-PodeOASchemaProperty -Name 'children' -Array -Reference 'StructPart' | + New-PodeOAObjectProperty | + Add-PodeOAComponentSchema -Name 'StructPart' + + + #Define Pet schema + New-PodeOAStringProperty -Name 'name' | New-PodeOAStringProperty -Name 'petType' | + New-PodeOAObjectProperty -DiscriminatorProperty 'petType' | Add-PodeOAComponentSchema -Name 'Pet2' + + #Define Cat schema + Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'Pet2', +(New-PodeOAStringProperty -Name 'huntingSkill' -Description 'The measured skill for hunting' -Default 'lazy' -Enum 'clueless', 'lazy', 'adventurous', 'aggressive' -Required -Object ) | + Add-PodeOAComponentSchema -Name 'Cat2' -Description "A representation of a cat. Note that `Cat` will be used as the discriminator value." + + + #Define Dog schema + Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'Pet2', +(New-PodeOAIntProperty -Name 'packSize' -Description 'the size of the pack the dog is from' -Default 0 -Minimum 0 -Format Int32 -Required -Object ) | + Add-PodeOAComponentSchema -Name 'Dog2' -Description "A representation of a dog. Note that `Dog` will be used as the discriminator value." + + + <# Alternative : + Add-PodeOAComponentSchema -Name 'Pet' -Schema ( + New-PodeOAObjectProperty -Name 'Pet' -XmlName 'pet' } -Properties @( + (New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 10 -ReadOnly), + (New-PodeOAStringProperty -Name 'name' -Example 'doggie' -Required), + (New-PodeOASchemaProperty -Name 'category' -Component 'Category'), + (New-PodeOAStringProperty -Name 'petType' -Example 'dog' -Required), + (New-PodeOAStringProperty -Name 'photoUrls' -Array), + (New-PodeOASchemaProperty -Name 'tags' -Component 'Tag') + (New-PodeOAStringProperty -Name 'status' -Description 'pet status in the store' -Enum @('available', 'pending', 'sold')) + )) #> + + <# Add-PodeOAComponentSchema -Name 'Cat' -Schema ( New-PodeOAObjectProperty -Name 'testcat' -Description 'Type of cat' -Properties ( + New-PodeOAStringProperty -Name 'breed' -Description 'Type of Breed' -Enum @( 'Abyssinian', 'Balinese-Javanese', 'Burmese', 'British Shorthair') | + Merge-PodeOAProperty -Type AllOf -ObjectDefinitions @( 'Pet', + (New-PodeOAStringProperty -Name 'huntingSkill' -Description 'The measured skill for hunting' -Enum @( 'clueless', 'lazy', 'adventurous', 'aggressive') -Object) + ) + ) + )#> + Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'Pet', (New-PodeOAStringProperty -Name 'rootCause' -required -object) | + Add-PodeOAComponentSchema -Name 'ExtendedErrorModel' + + New-PodeOAStringProperty -Name 'huntingSkill' -Description 'The measured skill for hunting' -Enum @( 'clueless', 'lazy', 'adventurous', 'aggressive') -Object | + Merge-PodeOAProperty -Type AllOf -ObjectDefinitions 'Pet' | + New-PodeOAStringProperty -Name 'breed' -Description 'Type of Breed' -Enum @( 'Abyssinian', 'Balinese-Javanese', 'Burmese', 'British Shorthair') | + + New-PodeOAObjectProperty -Description 'Type of cat' | Add-PodeOAComponentSchema -Name 'Cat' + + + + + + Add-PodeOAComponentSchema -Name 'Dog' -Component ( + Merge-PodeOAProperty -Type AllOf -ObjectDefinitions @( 'Pet', ( New-PodeOAObjectProperty -Properties ( + New-PodeOAStringProperty -Name 'breed' -Description 'Type of Breed' -Enum @( 'Dingo', 'Husky', 'Retriever', 'Shepherd') | + New-PodeOABoolProperty -Name 'bark' + )) + ) + ) + + + Add-PodeOAComponentSchema -Name 'Pets' -Component ( + Merge-PodeOAProperty -Type OneOf -ObjectDefinitions @( 'Cat', 'Dog') -DiscriminatorProperty 'petType') + + + Add-PodeOAComponentSchema -Name 'ApiResponse' -Component ( + New-PodeOAObjectProperty -Name 'ApiResponse' -XmlName '##default' -Properties ( + New-PodeOAIntProperty -Name 'code'-Format Int32 | + New-PodeOAStringProperty -Name 'type' -Example 'doggie' | + New-PodeOAStringProperty -Name 'message' + ) + ) + + New-PodeOAStringProperty -Name 'message' | New-PodeOAIntProperty -Name 'code'-Format Int32 | New-PodeOAObjectProperty | Add-PodeOAComponentSchema -Name 'ErrorModel' + + + Add-PodeRoute -PassThru -Method Get -Path '/peta/:id' -ScriptBlock { + Write-PodeJsonResponse -Value (Get-Pet -Id $WebEvent.Parameters['id']) -StatusCode 200 + } | + Set-PodeOARouteInfo -Summary 'Find pets by ID' -Description 'Returns pets based on ID' -OperationId 'getPetsById' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAStringProperty -Name 'id' -Description 'ID of pet to use' -array | ConvertTo-PodeOAParameter -In Path -Style Simple -Required )) | + Add-PodeOAResponse -StatusCode 200 -Description 'pet response' -Content (@{ '*/*' = New-PodeOASchemaProperty -Reference 'Pet' -array }) -PassThru | + Add-PodeOAResponse -Default -Description 'error payload' -Content (@{ 'text/html' = 'ApiResponse' }) -PassThru + + + + + + New-PodeOAIntProperty -Format Int32 -Description 'calls per hour allowed by the user' | Add-PodeOAComponentHeader -Name 'X-Rate-Limit' + New-PodeOAStringProperty -Format Date-Time -Description 'date in UTC when token expires' | Add-PodeOAComponentHeader -Name 'X-Expires-After' + + #define '#/components/responses/' + Add-PodeOAComponentResponse -Name 'UserOpSuccess' -Description 'Successful operation' -ContentSchemas (@{'application/json' = 'User' ; 'application/xml' = 'User' }) + + Add-PodeOAComponentRequestBody -Name 'PetBodySchema' -Required -Description 'Pet in the store' -ContentSchemas (@{ 'application/json' = 'Pets'; 'application/xml' = 'Pets'; 'application/x-www-form-urlencoded' = 'Pets' }) + + + #define '#/components/parameters/' + Add-PodeOAComponentParameter -Name 'PetIdParam' -Parameter ( New-PodeOAIntProperty -Name 'petId' -Format Int64 -Description 'ID of the pet' -Required | ConvertTo-PodeOAParameter -In Path ) + } + + + + # setup apikey authentication to validate a user + New-PodeAuthScheme -ApiKey -LocationName 'api_key' | Add-PodeAuth -Name 'api_key' -Sessionless -ScriptBlock { + param($key) + if ($key) { + # here you'd check a real storage, this is just for example + if ($key -eq 'test-key') { + return @{ + User = @{ + 'ID' = 'M0R7Y302' + 'Name' = 'Morty' + 'Type' = 'Human' + } + } + } + + # authentication failed + return @{ + Code = 401 + Challenge = 'qop="auth", nonce=""' + } + } else { + return @{ + Message = 'No Authorization header found' + Code = 401 + } + + } + } + New-PodeAuthScheme -Basic | Add-PodeAuth -Name 'Login' -Sessionless -ScriptBlock { + param($username, $password) + # check if the user is valid + return @{ User = $user } + } + New-PodeAuthScheme -ApiKey | Add-PodeAuth -Name 'LoginApiKey' -Sessionless -ScriptBlock { + param($username, $password) + # check if the user is valid + return @{ User = $user } + } + # jwt with no signature: + New-PodeAuthScheme -Bearer -AsJWT | Add-PodeAuth -Name 'Jwt' -Sessionless -ScriptBlock { + param($payload) + + return ConvertFrom-PodeJwt -Token $payload + } + + + New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'read' -Description 'Grant read-only access to all your data except for the account and user info' + New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'write' -Description 'Grant write-only access to all your data except for the account and user info' + New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'profile' -Description 'Grant read-only access to the account and user info only' + # setup session details + Enable-PodeSessionMiddleware -Duration 120 -Extend + + $clientId = '123123123' + $clientSecret = 'acascascasca>zzzcz' + $tenantId = '56456232' + + <# $InnerScheme = New-PodeAuthScheme -Form + $scheme = New-PodeAuthScheme ` + -OAuth2 ` + -ClientId $ClientId ` + -ClientSecret $ClientSecret ` + -AuthoriseUrl "https://login.microsoftonline.com/$($tenantId)/oauth2/v2.0/authorize" ` + -TokenUrl "https://login.microsoftonline.com/$($tenantId)/oauth2/v2.0/token" ` + -UserUrl 'https://graph.microsoft.com/oidc/userinfo' ` + -RedirectUrl $RedirectUrl ` + -InnerScheme $InnerScheme ` + # -Middleware $Middleware ` + -Scope 'read', 'write', 'profile' + $scheme | Add-PodeAuth -Name 'Login-OAuth2' -FailureUrl '/LoginOAuth2' -SuccessUrl '/' -ScriptBlock { + param($user, $accessToken, $refreshToken) + return @{ User = $user } + }#> + New-PodeAuthScheme ` + -OAuth2 ` + -ClientId $ClientId ` + -ClientSecret $ClientSecret ` + -AuthoriseUrl 'http://example.org/api/oauth/dialog' ` + -TokenUrl 'http://example.org/api/oauth/token' ` + -Scope 'read', 'write' | Add-PodeAuth -Name 'Login-OAuth2' -FailureUrl '/LoginOAuth2' -SuccessUrl '/' -ScriptBlock { + param($user, $accessToken, $refreshToken) + return @{ User = $user } + } + Merge-PodeAuth -Name 'test' -Authentication 'Login-OAuth2', 'api_key' + + $ex = + New-PodeOAExample -MediaType 'application/json' -Name 'user' -Summary 'User Example' -ExternalValue 'http://foo.bar/examples/user-example.json' | + New-PodeOAExample -MediaType 'application/xml' -Name 'user' -Summary 'User Example in XML' -ExternalValue 'http://foo.bar/examples/user-example.xml' | + New-PodeOAExample -MediaType 'text/plain' -Name 'user' -Summary 'User Example in Plain text' -ExternalValue 'http://foo.bar/examples/user-example.txt' | + New-PodeOAExample -MediaType '*/*' -Name 'user' -Summary 'User example in other forma' -ExternalValue 'http://foo.bar/examples/user-example.whatever' + Select-PodeOADefinition -Tag 'v3' -Scriptblock { + Add-PodeRouteGroup -Path '/api/v4' -Routes { + + Add-PodeRoute -PassThru -Method Put -Path '/pat/:petId' -ScriptBlock { + $JsonPet = ConvertTo-Json $WebEvent.data + if ( Update-Pet -Id $WebEvent.Parameters['petId'] -Data $JsonPet) { + Write-PodeJsonResponse -Value @{} -StatusCode 200 + } else { + Write-PodeJsonResponse -Value @{} -StatusCode 405 + } + } | Set-PodeOARouteInfo -Summary 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatePasdadaetWithForm' -PassThru | + Set-PodeOARequest -Parameters @( + (New-PodeOAStringProperty -Name 'petId' -Description 'ID of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Path -Required) + ) -RequestBody ( + New-PodeOARequestBody -Description 'user to add to the system' -Content @{ 'application/json' = 'User'; 'application/xml' = 'User' } -Examples $ex + + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Pet updated.' -Content (@{ 'application/json' = '' ; 'application/xml' = '' }) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Method Not Allowed' -Content (@{ 'application/json' = '' ; 'application/xml' = '' }) + + Add-PodeRoute -PassThru -Method Put -Path '/paet/:petId' -ScriptBlock { + $JsonPet = ConvertTo-Json $WebEvent.data + if ( Update-Pet -Id $WebEvent.Parameters['id'] -Data $JsonPet) { + Write-PodeJsonResponse -Value @{} -StatusCode 200 + } else { + Write-PodeJsonResponse -Value @{} -StatusCode 405 + } + } | Set-PodeOARouteInfo -Summary 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatepaet' -PassThru | + Set-PodeOARequest -Parameters @( + (New-PodeOAStringProperty -Name 'petId' -Description 'ID of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Path -Required -Examples ( + New-PodeOAExample -Name 'user' -Summary 'User Example' -Value 'http://foo.bar/examples/user-example.json' | + New-PodeOAExample -Name 'user1' -Summary 'User Example in XML' -Value 'http://foo.bar/examples/user-example.xml' | + New-PodeOAExample -Name 'user2' -Summary 'User Example in Plain text' -Value 'http://foo.bar/examples/user-example.txt' | + New-PodeOAExample -Name 'user3' -Summary 'User example in other forma' -Value 'http://foo.bar/examples/user-example.whatever' )) + ) -RequestBody (New-PodeOARequestBody -Required -Content (@{ + 'application/x-www-form-urlencoded' = New-PodeOAObjectProperty -Properties @( + (New-PodeOAStringProperty -Name 'name' -Description 'Updated name of the pet'), + (New-PodeOAStringProperty -Name 'status' -Description 'Updated status of the pet' -Required) + ) + }) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Pet updated.' -Content (@{ 'application/json' = '' ; 'application/xml' = '' }) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Method Not Allowed' -Content (@{ 'application/json' = '' ; 'application/xml' = '' }) + + + #Start 3.1 + Select-PodeOADefinition -Tag 'v3.1' -Scriptblock { + + Add-PodeOAComponentPathItem -Name 'GetPetByIdWithRef' -Method Get -PassThru | Set-PodeOARouteInfo -Summary 'Find pet by ID' -Description 'Returns a single pet.' -Tags 'pet' -OperationId 'getPetByIdWithRef' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( + New-PodeOAIntProperty -Name 'petId' -Description 'ID of pet to return' -Format Int64 | + ConvertTo-PodeOAParameter -In Path -Required ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet') -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Pet not found' -PassThru | + Add-PodeOAResponse -StatusCode 415 + + Add-PodeOAWebhook -Name 'newPet' -Method Post -PassThru | Set-PodeOARouteInfo -Description 'Information about a new pet in the system' -PassThru | + Set-PodeOARequest -PassThru -RequestBody ( + New-PodeOARequestBody -Content @{ 'application/json' = 'Pets' } + ) | Add-PodeOAResponse -StatusCode 200 -Description 'Return a 200 status to indicate that the data was received successfully' + + } + #end 3.1 + Add-PodeRoute -PassThru -Method Put -Path '/paet2/:petId' -ScriptBlock { + $JsonPet = ConvertTo-Json $WebEvent.data + if ( Update-Pet -Id $WebEvent.Parameters['id'] -Data $JsonPet) { + Write-PodeJsonResponse -Value @{} -StatusCode 200 + } else { + Write-PodeJsonResponse -Value @{} -StatusCode 405 + } + } | Set-PodeOARouteInfo -Summary 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatepaet2' -PassThru | + Set-PodeOARequest -Parameters @( + (New-PodeOAStringProperty -Name 'petId' -Description 'ID of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Path -Required) + ) -RequestBody (New-PodeOARequestBody -Description 'user to add to the system' -Content @{ 'text/plain' = New-PodeOAStringProperty -array } ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Pet updated.' -Content (@{ 'application/json' = '' ; 'application/xml' = '' }) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Method Not Allowed' -Content (@{ 'application/json' = '' ; 'application/xml' = '' }) + + + + $ex = + New-PodeOAExample -MediaType 'application/json' -Name 'user' -Summary 'User Example' -ExternalValue 'http://foo.bar/examples/user-example.json' | + New-PodeOAExample -MediaType 'application/xml' -Name 'user' -Summary 'User Example in XML' -ExternalValue 'http://foo.bar/examples/user-example.xml' | + New-PodeOAExample -MediaType 'text/plain' -Name 'user' -Summary 'User Example in Plain text' -ExternalValue 'http://foo.bar/examples/user-example.txt' | + New-PodeOAExample -MediaType '*/*' -Name 'user' -Summary 'User example in other forma' -ExternalValue 'http://foo.bar/examples/user-example.whatever' + + Add-PodeOAComponentExample -name 'frog-example' -Summary "An example of a frog with a cat's name" -Value @{name = 'Jaguar'; petType = 'Panthera'; color = 'Lion'; gender = 'Male'; breed = 'Mantella Baroni' } + + Add-PodeRoute -PassThru -Method Put -Path '/paet3/:petId' -ScriptBlock { + $JsonPet = ConvertTo-Json $WebEvent.data + if ( Update-Pet -Id $WebEvent.Parameters['id'] -Data $JsonPet) { + Write-PodeJsonResponse -Value @{} -StatusCode 200 + } else { + Write-PodeJsonResponse -Value @{} -StatusCode 405 + } + } | Set-PodeOARouteInfo -Summary 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatepaet3' -PassThru | + Set-PodeOARequest -Parameters @( + (New-PodeOAStringProperty -Name 'petId' -Description 'ID of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Path -Required) + ) -RequestBody (New-PodeOARequestBody -Description 'user to add to the system' -Content @{ 'application/json' = 'NewCat' } -Examples ( + New-PodeOAExample -MediaType 'application/json' -Name 'cat' -Summary 'An example of a cat' -Value @{name = 'Fluffy'; petType = 'Cat'; color = 'White'; gender = 'male'; breed = 'Persian' } | + New-PodeOAExample -MediaType 'application/json' -Name 'dog' -Summary "An example of a dog with a cat's name" -Value @{name = 'Puma'; petType = 'Dog'; color = 'Black'; gender = 'Female'; breed = 'Mixed' } | + New-PodeOAExample -MediaType 'application/json' -Reference 'frog-example' + ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Pet updated.' -Content (@{ 'application/json' = '' ; 'application/xml' = '' }) -PassThru | + Add-PodeOAResponse -StatusCode 4XX -Description 'Method Not Allowed' -Content (@{ 'application/json' = '' ; 'application/xml' = '' }) + + + Add-PodeRoute -PassThru -Method Put -Path '/paet4/:petId' -ScriptBlock { + $JsonPet = ConvertTo-Json $WebEvent.data + if ( Update-Pet -Id $WebEvent.Parameters['id'] -Data $JsonPet) { + Write-PodeJsonResponse -Value @{} -StatusCode 200 + } else { + Write-PodeJsonResponse -Value @{} -StatusCode 405 + } + } | Set-PodeOARouteInfo -Summary 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatepaet4' -PassThru | + Set-PodeOARequest -Parameters @( + (New-PodeOAStringProperty -Name 'petId' -Description 'ID of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Path -Required -ContentType 'application/json') + ) -RequestBody (New-PodeOARequestBody -Description 'user to add to the system' -Content @{ 'application/json' = 'Pet' } -Examples ( + New-PodeOAExample -MediaType 'application/json' -Name 'cat' -Summary 'An example of a cat' -Value @{name = 'Fluffy'; petType = 'Cat'; color = 'White'; gender = 'male'; breed = 'Persian' } | + New-PodeOAExample -MediaType 'application/json' -Name 'dog' -Summary "An example of a dog with a cat's name" -Value @{name = 'Puma'; petType = 'Dog'; color = 'Black'; gender = 'Female'; breed = 'Mixed' } | + New-PodeOAExample -MediaType 'application/json' -Reference 'frog-example' + ) + + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Pet updated.' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content '') -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Method Not Allowed' -Content (@{ 'application/json' = '' ; 'application/xml' = '' }) + + } + } + Add-PodeAuthMiddleware -Name test -Authentication 'test' -Route '/api/*' + Select-PodeOADefinition -Tag 'v3.1', 'v3' -Scriptblock { + Add-PodeRouteGroup -Path '/api/v3' -Routes { + #PUT + Add-PodeRoute -PassThru -Method Put -Path '/pet' -ScriptBlock { + $JsonPet = ConvertTo-Json $WebEvent.data + $Validate = Test-PodeOAJsonSchemaCompliance -Json $JsonPet -SchemaReference 'Pet' + if ($Validate.result) { + $Pet = $WebEvent.data + $Pet.tags.id = Get-Random -Minimum 1 -Maximum 9999999 + Write-PodeJsonResponse -Value ($Pet | ConvertTo-Json -Depth 20 ) -StatusCode 200 + } else { + Write-PodeJsonResponse -StatusCode 405 -Value @{ + result = $Validate.result + message = $Validate.message -join ', ' + } + } + } | Set-PodeOARouteInfo -Summary 'Update an existing pet' -Description 'Update an existing pet by Id' -Tags 'pet' -OperationId 'updatePet' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Reference 'PetBodySchema' ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Pet not found' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Validation exception' -Content @{ + 'application/json' = (New-PodeOAObjectProperty -Properties @( (New-PodeOAStringProperty -Name 'result'), (New-PodeOAStringProperty -Name 'message') )) + } + + Add-PodeRoute -PassThru -Method Post -Path '/pet' -Authentication 'Login-OAuth2' -Scope 'write' -ScriptBlock { + + $JsonPet = ConvertTo-Json $WebEvent.data + $Validate = Test-PodeOAJsonSchemaCompliance -Json $JsonPet -SchemaReference 'Pet' + if ($Validate.result) { + $Pet = $WebEvent.data + $Pet.tags.id = Get-Random -Minimum 1 -Maximum 9999999 + Write-PodeJsonResponse -Value ($Pet | ConvertTo-Json -Depth 20 ) -StatusCode 200 + } else { + Write-PodeJsonResponse -StatusCode 405 -Value @{ + result = $Validate.result + message = $Validate.message -join ', ' + } + } + } | Set-PodeOARouteInfo -Summary 'Add a new pet to the store' -Description 'Add a new pet to the store' -Tags 'pet' -OperationId 'addPet' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Reference 'PetBodySchema' ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Validation exception' -Content @{ + 'application/json' = (New-PodeOAObjectProperty -Properties @( (New-PodeOAStringProperty -Name 'result'), (New-PodeOAStringProperty -Name 'message') )) + } + + Add-PodeRoute -PassThru -Method Post -Path '/petcallback' -Authentication 'Login-OAuth2' -Scope 'write' -ScriptBlock { + $JsonPet = ConvertTo-Json $WebEvent.data + $Validate = Test-PodeOAJsonSchemaCompliance -Json $JsonPet -SchemaReference 'Pet' + if ($Validate.result) { + $Pet = $WebEvent.data + $Pet.tags.id = Get-Random -Minimum 1 -Maximum 9999999 + Write-PodeJsonResponse -Value ($Pet | ConvertTo-Json -Depth 20 ) -StatusCode 200 + } else { + Write-PodeJsonResponse -StatusCode 405 -Value @{ + result = $Validate.result + message = $Validate.message -join ', ' + } + } + } | Set-PodeOARouteInfo -Summary 'Add a new pet to the store' -Description 'Add a new pet to the store' -Tags 'pet' -OperationId 'addPetcallback' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Reference 'PetBodySchema' ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Validation exception' -Content @{ + 'application/json' = (New-PodeOAObjectProperty -Properties @( (New-PodeOAStringProperty -Name 'result'), (New-PodeOAStringProperty -Name 'message') )) + } -PassThru | + Add-PodeOACallBack -Name 'test' -Path '{$request.body#/id}' -Method Post -RequestBody (New-PodeOARequestBody -Content @{'*/*' = (New-PodeOAStringProperty -Name 'id') } ) ` + -Response ( + New-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' -Array) | + New-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' | + New-PodeOAResponse -StatusCode 404 -Description 'Pet not found' | + New-PodeOAResponse -Default -Description 'Something is wrong' + ) + + #Define CallBack Reference + + Add-PodeOAComponentCallBack -Name 'test' -Path '{$request.body#/id}' -Method Post -RequestBody (New-PodeOARequestBody -Content @{'*/*' = (New-PodeOAStringProperty -Name 'id') } ) ` + -Response ( + New-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' -Array) | + New-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' | + New-PodeOAResponse -StatusCode 404 -Description 'Pet not found' | + New-PodeOAResponse -Default -Description 'Something is wrong' + ) + + + Add-PodeRoute -PassThru -Method Post -Path '/petcallbackReference' -Authentication 'Login-OAuth2' -Scope 'write' -ScriptBlock { + $JsonPet = ConvertTo-Json $WebEvent.data + $Validate = Test-PodeOAJsonSchemaCompliance -Json $JsonPet -SchemaReference 'Pet' + if ($Validate.result) { + $Pet = $WebEvent.data + $Pet.tags.id = Get-Random -Minimum 1 -Maximum 9999999 + Write-PodeJsonResponse -Value ($Pet | ConvertTo-Json -Depth 20 ) -StatusCode 200 + } else { + Write-PodeJsonResponse -StatusCode 405 -Value @{ + result = $Validate.result + message = $Validate.message -join ', ' + } + } + } | Set-PodeOARouteInfo -Summary 'Add a new pet to the store' -Description 'Add a new pet to the store' -Tags 'pet' -OperationId 'petcallbackReference' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Reference 'PetBodySchema' ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Validation exception' -Content @{ + 'application/json' = ( New-PodeOAStringProperty -Name 'result' | New-PodeOAStringProperty -Name 'message' | New-PodeOAObjectProperty ) + } -PassThru | + Add-PodeOACallBack -Name 'test1' -Reference 'test' + + + Add-PodeRoute -PassThru -Method get -Path '/pet/findByStatus' -Authentication 'Login-OAuth2' -Scope 'read' -AllowAnon -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Finds Pets by status' -Description 'Multiple status values can be provided with comma separated strings' -Tags 'pet' -OperationId 'findPetsByStatus' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAStringProperty -Name 'status' -Description 'Status values that need to be considered for filter' -Default 'available' -Enum @('available', 'pending', 'sold') | ConvertTo-PodeOAParameter -In Query ) + ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' -Array) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid status value' + + + + + + + + + + Add-PodeRoute -PassThru -Method get -Path '/pet/findByTag' -Authentication 'test' -Scope 'read' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Finds Pets by tags' -Description 'Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.' -Tags 'pet' -OperationId 'findPetsByTags' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAStringProperty -Name 'tag' -Description 'Tags to filter by' -Array | ConvertTo-PodeOAParameter -In Query -Explode) + ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) -PassThru | #missing array application/json: + # schema: + # type: array + # items: + # $ref: '#/components/schemas/Pet' + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid status value' -PassThru | + Add-PodeOAResponse -Default -Description 'Unexpected error' -Content (New-PodeOAContentMediaType -MediaType 'application/json' -Content 'ErrorModel' ) + + Add-PodeRoute -PassThru -Method Get -Path '/pet/:petId' -Authentication 'Login-OAuth2' -Scope 'read' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Find pet by ID' -Description 'Returns a single pet.' -Tags 'pet' -OperationId 'getPetById' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( ConvertTo-PodeOAParameter -Reference 'PetIdParam' ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (@{ 'application/json' = 'Pet' ; 'application/xml' = 'Pet' }) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Pet not found' + + Add-PodeRoute -PassThru -Method post -Path '/pet/:petId' -Authentication 'Login-OAuth2' -Scope 'write' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Updates a pet in the store' -Description 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatePetWithForm' -PassThru | + Set-PodeOARequest -PassThru -Parameters @(( ConvertTo-PodeOAParameter -Reference 'PetIdParam' ), + ( New-PodeOAStringProperty -Name 'name' -Description 'Name of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) , + ( New-PodeOAStringProperty -Name 'status' -Description 'Status of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) + ) -RequestBody ( + # New-PodeOARequestBody -Content @{ + # 'application/x-www-form-urlencoded' = (New-PodeOAObjectProperty -Properties @( (New-PodeOAStringProperty -format 'uuid'), (New-PodeOAObjectProperty -Properties @()))) + New-PodeOARequestBody -Properties -Content @{ + 'multipart/form-data' = (New-PodeOAStringProperty -Name 'file' -Format binary -Array) + }) | Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + + + Add-PodeRoute -PassThru -Method post -Path '/pet2/:petId' -Authentication 'Login-OAuth2' -Scope 'write' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Updates a pet in the store' -Description 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatePet2WithForm' -PassThru | + Set-PodeOARequest -PassThru -Parameters @(( ConvertTo-PodeOAParameter -Reference 'PetIdParam' ), + ( New-PodeOAStringProperty -Name 'name' -Description 'Name of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) , + ( New-PodeOAStringProperty -Name 'status' -Description 'Status of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) + ) -RequestBody ( + New-PodeOARequestBody -Content @{ + 'application/x-www-form-urlencoded' = (New-PodeOAObjectProperty -Properties @( + (New-PodeOAStringProperty -name 'id' -format 'uuid'), (New-PodeOAObjectProperty -name 'address' -NoProperties))) + + }) | Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + Add-PodeRoute -PassThru -Method post -Path '/pet3/:petId' -Authentication 'Login-OAuth2' -Scope 'write' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Updates a pet in the store' -Description 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatePet3WithForm' -PassThru | + Set-PodeOARequest -PassThru -Parameters @(( ConvertTo-PodeOAParameter -Reference 'PetIdParam' ), + ( New-PodeOAStringProperty -Name 'name' -Description 'Name of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) , + ( New-PodeOAStringProperty -Name 'status' -Description 'Status of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) + ) -RequestBody (New-PodeOARequestBody -Content @{'multipart/form-data' = + New-PodeOAStringProperty -name 'id' -format 'uuid' | + New-PodeOAObjectProperty -name 'address' -NoProperties | + New-PodeOAStringProperty -name 'children' -array | + New-PodeOASchemaProperty -Name 'addresses' -Reference 'Address' -Array | + New-PodeOAObjectProperty + }) | Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + + Add-PodeRoute -PassThru -Method post -Path '/pet4/:petId' -Authentication 'Login-OAuth2' -Scope 'write' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Updates a pet in the store' -Description 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatePet4WithForm' -PassThru | + Set-PodeOARequest -PassThru -Parameters @(( ConvertTo-PodeOAParameter -Reference 'PetIdParam' ), + ( New-PodeOAStringProperty -Name 'name' -Description 'Name of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) , + ( New-PodeOAStringProperty -Name 'status' -Description 'Status of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) + ) -RequestBody (New-PodeOARequestBody -Content @{'multipart/form-data' = + New-PodeOAStringProperty -name 'id' -format 'uuid' | + New-PodeOAObjectProperty -name 'address' -NoProperties | + New-PodeOAObjectProperty -name 'historyMetadata' -Description 'metadata in XML format' -NoProperties | + New-PodeOAStringProperty -name 'profileImage' -Format Binary | + New-PodeOAObjectProperty + } -Encoding ( + New-PodeOAEncodingObject -Name 'historyMetadata' -ContentType 'application/xml; charset=utf-8' | + New-PodeOAEncodingObject -Name 'profileImage' -ContentType 'image/png, image/jpeg' -Headers ( + New-PodeOAIntProperty -name 'X-Rate-Limit-Limit' -Description 'The number of allowed requests in the current period' -Default 3 -Enum @(1, 2, 3) -Maximum 3 | + New-PodeOAIntProperty -Name 'X-Rate-Limit-Reset' -Description 'The number of seconds left in the current period' -Minimum 2 + ) + ) + ) | Add-PodeOAResponse -StatusCode 200 -PassThru -Description 'A simple string response' -Content ( New-PodeOAContentMediaType -MediaType 'text/plain' -Content ( New-PodeOAStringProperty) ) | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + + + Add-PodeRoute -PassThru -Method post -Path '/pet/:petId/uploadImage2' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Uploads an image' -Description 'Updates a pet in the store with a new image' -Tags 'pet' -OperationId 'uploadFile2' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAIntProperty -Name 'petId' -Format Int64 -Description 'ID of pet that needs to be updated' -Required | ConvertTo-PodeOAParameter -In Path ), + ( New-PodeOAStringProperty -Name 'additionalMetadata' -Description 'Additional Metadata' | ConvertTo-PodeOAParameter -In Query ) + ) -RequestBody (New-PodeOARequestBody -Required -Content @{ 'multipart/form-data' = New-PodeOAObjectProperty -Properties @( (New-PodeOAStringProperty -Name 'image' -Format Binary )) } ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'A simple string response' -Content ( + New-PodeOAContentMediaType -MediaType 'text/plain' -Content ( New-PodeOAStringProperty -Example 'whoa!') ) -Headers ( + New-PodeOAIntProperty -Name 'X-Rate-Limit-Limit' -Description 'The number of allowed requests in the current period' | + New-PodeOAIntProperty -Name 'X-Rate-Limit-Remaining' -Description 'The number of remaining requests in the current period' | + New-PodeOAIntProperty -Name 'X-Rate-Limit-Reset' -Description 'The number of seconds left in the current period' -Maximum 3 + ) + + Add-PodeRoute -PassThru -Method Delete -Path '/pet/:petId' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Deletes a pet' -Description 'Deletes a pet.' -Tags 'pet' -OperationId 'deletePet' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( ConvertTo-PodeOAParameter -Reference 'PetIdParam' ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Pet not found' + + Add-PodeRoute -PassThru -Method post -Path '/pet/:petId/uploadmultiImage' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Uploads an image' -Description 'Updates a pet in the store with a new image' -Tags 'pet' -OperationId 'uploadFilemulti' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAIntProperty -Name 'petId' -Format Int64 -Description 'ID of pet that needs to be updated' -Required | ConvertTo-PodeOAParameter -In Path ), + ( New-PodeOAStringProperty -Name 'additionalMetadata' -Description 'Additional Metadata' | ConvertTo-PodeOAParameter -In Query ) + ) -RequestBody ( + New-PodeOARequestBody -Required -Content ( New-PodeOAContentMediaType -MediaType 'multipart/form-data' -Upload -PartContentMediaType 'application/octect-stream' -Content ( + New-PodeOAIntProperty -name 'orderId' | New-PodeOAStringProperty -Name 'image' -Format Binary | New-PodeOAObjectProperty )) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content @{'application/json' = 'ApiResponse' } -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + + Add-PodeRoute -PassThru -Method post -Path '/pet/:petId/uploadImageOctet' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Uploads an image' -Description 'Updates a pet in the store with a new image' -Tags 'pet' -OperationId 'uploadFileOctet' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAIntProperty -Name 'petId' -Format Int64 -Description 'ID of pet that needs to be updated' -Required | ConvertTo-PodeOAParameter -In Path ), + ( New-PodeOAStringProperty -Name 'additionalMetadata' -Description 'Additional Metadata' | ConvertTo-PodeOAParameter -In Query ) + ) -RequestBody ( + New-PodeOARequestBody -Required -Content ( New-PodeOAContentMediaType -MediaType 'application/octet-stream' -Upload ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content @{'application/json' = 'ApiResponse' } -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + Add-PodeRoute -PassThru -Method Get -Path '/store/inventory' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Returns pet inventories by status' -Description 'Returns a map of status codes to quantities' -Tags 'store' -OperationId 'getInventory' -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content @{ 'application/json' = New-PodeOAObjectProperty -Properties @(New-PodeOAStringProperty -Name 'none' ) } #missing additionalProperties + + + Add-PodeRoute -PassThru -Method post -Path '/store/order' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Deprecated -Summary 'Place an order for a pet' -Description 'Place a new order in the store' -Tags 'store' -OperationId 'placeOrder' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Required -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'Order' )) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (@{ 'application/json' = 'Order' ; 'application/xml' = 'Order' }) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + Add-PodeRoute -PassThru -Method Get -Path '/store/order/:orderId' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | + Add-PodeOAExternalRoute -Servers ( + New-PodeOAServerEndpoint -Url 'http://ext.server.com/api/v12' -Description 'ext test server' | + New-PodeOAServerEndpoint -Url 'http://ext13.server.com/api/v12' -Description 'ext test server 13' | + New-PodeOAServerEndpoint -Url 'http://ext14.server.com/api/v12' -Description 'ext test server 14' + ) -PassThru | + Set-PodeOARouteInfo -Summary 'Find purchase order by ID' -Description 'For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions.' -Tags 'store' -OperationId 'getOrderById' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAIntProperty -Name 'orderId' -Format Int64 -Description 'ID of order that needs to be fetched' -Required | ConvertTo-PodeOAParameter -In Path ) + ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'Order' ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Order not found' + + Add-PodeRoute -PassThru -Method Delete -Path '/store/order/:orderId' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Delete purchase order by ID' -Description 'For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors.' -Tags 'store' -OperationId 'deleteOrder' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAIntProperty -Name 'orderId' -Format Int64 -Description ' ID of the order that needs to be deleted' -Required | ConvertTo-PodeOAParameter -In Path ) + ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Order not found' + + + Add-PodeRoute -PassThru -Method post -Path '/user' -ScriptBlock { + $JsonUser = ConvertTo-Json $WebEvent.data + $Validate = Test-PodeOAJsonSchemaCompliance -Json $JsonUser -SchemaReference 'User' + if ($Validate.result) { + $User = $WebEvent.data + $User.id = Get-Random -Minimum 1 -Maximum 9999999 + Write-PodeJsonResponse -Value ($User | ConvertTo-Json -Depth 20 ) -StatusCode 200 + } else { + Write-PodeJsonResponse -StatusCode 405 -Value @{ + result = $Validate.result + message = $Validate.message -join ', ' + } + } + } | Set-PodeOARouteInfo -Summary 'Create user.' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'createUser' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Required -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' )) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Reference 'UserOpSuccess' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' -Content @{ + 'application/json' = (New-PodeOAObjectProperty -Properties @( (New-PodeOAStringProperty -Name 'result'), (New-PodeOAStringProperty -Name 'message') )) + } + + Add-PodeRoute -PassThru -Method post -Path '/user/createWithList' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Creates list of users with given input array.' -Description 'Creates list of users with given input array.' -Tags 'user' -OperationId 'createUsersWithListInput' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Required -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' )) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Reference 'UserOpSuccess' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + Add-PodeRoute -PassThru -Method Get -Path '/user/login' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Logs user into the system.' -Description 'Logs user into the system.' -Tags 'user' -OperationId 'loginUser' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAStringProperty -Name 'username' -Description 'The user name for login' | ConvertTo-PodeOAParameter -In Query ) + ( New-PodeOAStringProperty -Name 'password' -Description 'The password for login in clear text' -Format Password | ConvertTo-PodeOAParameter -In Query ) + ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'string' ) ` + -Header @('X-Rate-Limit', 'X-Expires-After') -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username/password supplied' + + + Add-PodeRoute -PassThru -Method Get -Path '/user/logout' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Logs out current logged in user session.' -Description 'Logs out current logged in user session.' -Tags 'user' -OperationId 'logoutUser' -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' + + Add-PodeRoute -PassThru -Method Get -Path '/user/:username' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Get user by user name' -Description 'Get user by user name.' -Tags 'user' -OperationId 'getUserByName' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAStringProperty -Name 'username' -Description 'The name that needs to be fetched. Use user1 for testing.' -Required | ConvertTo-PodeOAParameter -In Path ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Reference 'UserOpSuccess' -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' + + $Responses = New-PodeOAResponse -StatusCode 200 -Reference 'UserOpSuccess' | + New-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' | + New-PodeOAResponse -StatusCode 404 -Description 'User not found' | + New-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + + Add-PodeRoute -PassThru -Method Put -Path '/user_1/:username' -OAResponses $Responses -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Update user' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'updateUser_1' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAStringProperty -Name 'username' -Description ' name that need to be updated.' -Required | ConvertTo-PodeOAParameter -In Path ) + ) -RequestBody (New-PodeOARequestBody -Required -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'StructPart' )) + + + Add-PodeRoute -PassThru -Method Put -Path '/user/:username' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Update user' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'updateUser' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAStringProperty -Name 'username' -Description ' name that need to be updated.' -Required | ConvertTo-PodeOAParameter -In Path ) + ) -RequestBody (New-PodeOARequestBody -Required -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' )) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Reference 'UserOpSuccess' -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + + + Add-PodeRoute -PassThru -Method Put -Path '/userLink/:username' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Update user' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'updateUserLink' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAStringProperty -Name 'username' -Description ' name that need to be updated.' -Required | ConvertTo-PodeOAParameter -In Path ) + ) -RequestBody (New-PodeOARequestBody -Required -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' )) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Content @{'application/json' = 'User' } -PassThru ` + -Links (New-PodeOAResponseLink -Name address -OperationId 'getUserByName' -Parameters @{'username' = '$request.path.username' } ) | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + #Add link reference + Add-PodeOAComponentResponseLink -Name 'address' -OperationId 'getUserByName' -Parameters @{'username' = '$request.path.username' } + + #use link reference + Add-PodeRoute -PassThru -Method Put -Path '/userLinkByRef/:username' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Update user' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'updateUserLinkByRef' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAStringProperty -Name 'username' -Description ' name that need to be updated.' -Required | ConvertTo-PodeOAParameter -In Path ) + ) -RequestBody (New-PodeOARequestBody -Required -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' )) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Content @{'application/json' = 'User' } -PassThru ` + -Links (New-PodeOAResponseLink -Name 'address2' -Reference 'address' ) | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + + + Add-PodeRoute -PassThru -Method Delete -Path '/usera/:username' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Delete user' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'deleteUser' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAStringProperty -Name 'username' -Description 'The name that needs to be deleted.' -Required | ConvertTo-PodeOAParameter -In Path ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' + + + Remove-PodeRoute -Method Delete -Path '/api/v3/usera/:username' + + + Add-PodeRoute -PassThru -Method Delete -Path '/user/:username' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Delete user' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'deleteUser' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAStringProperty -Name 'username' -Description 'The name that needs to be deleted.' -Required | ConvertTo-PodeOAParameter -In Path ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' + + + + Add-PodeOAExternalRoute -Method Get -Path '/stores/order/:orderId' -Servers ( + New-PodeOAServerEndpoint -Url 'http://ext.server.com/api/v12' -Description 'ext test server' | + New-PodeOAServerEndpoint -Url 'http://ext13.server.com/api/v12' -Description 'ext test server 13' | + New-PodeOAServerEndpoint -Url 'http://ext14.server.com/api/v12' -Description 'ext test server 14' + ) -PassThru | Set-PodeOARouteInfo -Summary 'Find purchase order by ID' -Description 'For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions.' -Tags 'store' -OperationId 'getOrderExternalById' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAIntProperty -Name 'orderId' -Format Int64 -Description 'ID of order that needs to be fetched' -Required | ConvertTo-PodeOAParameter -In Path ) + ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'Order' ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Order not found' + } + } + Select-PodeOADefinition -Tag 'v3.1' -Scriptblock { + Add-PodeRouteGroup -Path '/api/v5' -Routes { + + Add-PodeRoute -Method Get -Path '/petbyRef/:petId' -Authentication 'api_key' -Scope 'read' -OAReference 'GetPetByIdWithRef' -ScriptBlock { + Write-PodeJsonResponse -Value 'done' -StatusCode 2005 + } + + } + } + + + $yaml = PodeOADefinition -Format Yaml -DefinitionTag 'v3.1' + $json = PodeOADefinition -Format Json -DefinitionTag 'v3' + + Write-PodeHost "`rYAML Tag: v3.1 Output:`r $yaml" + + Write-PodeHost "`rJSON Tag: v3 Output:`r $json" +} \ No newline at end of file diff --git a/examples/PetStore/Order.psm1 b/examples/PetStore/Order.psm1 new file mode 100644 index 000000000..c511fdcad --- /dev/null +++ b/examples/PetStore/Order.psm1 @@ -0,0 +1,130 @@ +$orders = @{} +function Initialize-Order { + param ( + [switch] + $Reset + ) + New-PodeLockable -Name 'PetOrderLock' + if ($Reset.IsPresent) { + $now = (Get-Date) + Lock-PodeObject -Name 'PetOrderLock' -ScriptBlock { + Set-PodeState -Scope 'Orders' -Name 'orders' -Value @{} | Out-Null + Add-Order -Id 1 -PetId 1 -Quantity 100 -ShipDate $now -Status 'placed' -Complete + Add-Order -Id 2 -PetId 1 -Quantity 50 -ShipDate $now -Status 'approved' -Complete + Add-Order -Id 3 -PetId 1 -Quantity 50 -ShipDate $now -Status 'delivered' -Complete + Add-Order -Id 4 -PetId 1 -Quantity 20 -ShipDate $now -Status 'placed' + } + } +} + +function Add-Order { + [CmdletBinding(DefaultParameterSetName = 'Items')] + param ( + [Parameter(Mandatory, ParameterSetName = 'Items')] + [long] + $Id, + + [Parameter(Mandatory, ParameterSetName = 'Items')] + [long] + $PetId, + + [Parameter(Mandatory, ParameterSetName = 'Items')] + [int] + $Quantity, + + [Parameter(Mandatory, ParameterSetName = 'Items')] + [datetime] + $ShipDate, + + [Parameter(Mandatory, ParameterSetName = 'Items')] + [string] + $Status, + + [Parameter( ParameterSetName = 'Items')] + [switch] + $Complete, + + [Parameter(Mandatory, ParameterSetName = 'Object')] + [hashtable] + $Order + ) + Lock-PodeObject -Name 'PetOrderLock' -ScriptBlock { + $orders = Get-PodeState -Name 'orders' + switch ($PSCmdlet.ParameterSetName) { + 'Items' { + $orders["$Id"] = @{ + id = $Id + petId = $PetId + quantity = $Quantity + shipdate = $ShipDate + status = $Status + complete = $Complete.IsPresent + } + } + 'Object' { + $orders["$($Order.id)"] = $Order + } + } + } +} + + +function Get-Order { + param ( + [Parameter(Mandatory)] + [long] + $Id + ) + return Lock-PodeObject -Name 'PetOrderLock' -Return -ScriptBlock { + $orders = Get-PodeState -Name 'orders' + return $orders["$Id"] + } +} + +function Test-Order { + param ( + [Parameter(Mandatory)] + [long] + $Id + ) + return Lock-PodeObject -Name 'PetOrderLock' -Return -ScriptBlock { + $orders = Get-PodeState -Name 'orders' + return $orders.ContainsKey("$Id") + } +} + + +function Get-CountByStatus { + return Lock-PodeObject -Name 'PetOrderLock' -Return -ScriptBlock { + $result = @{} + foreach ($order in (Get-PodeState -Name 'orders').Values) { + $status = $order.status + if ($result.containsKey($status)) { + $result[$status] += $order.quantity + } else { + $result[$status] = $order.quantity + } + } + return $result + } +} + +function Remove-Order { + param ( + [Parameter(Mandatory)] + [long] + $Id + ) + Lock-PodeObject -Name 'PetOrderLock' -ScriptBlock { + $order = (Get-PodeState -Name 'orders') + $order.Remove( "$Id") + } +} + + +Export-ModuleMember -Function Initialize-Order +Export-ModuleMember -Function Get-Order +Export-ModuleMember -Function Get-CountByStatus +Export-ModuleMember -Function Add-Order +Export-ModuleMember -Function Test-Order +Export-ModuleMember -Function Remove-Order \ No newline at end of file diff --git a/examples/PetStore/PetData.psm1 b/examples/PetStore/PetData.psm1 new file mode 100644 index 000000000..d4f2c0408 --- /dev/null +++ b/examples/PetStore/PetData.psm1 @@ -0,0 +1,311 @@ + + + +function Initialize-Categories { + param ( + [switch] + $Reset + ) + New-PodeLockable -Name 'PetCategoryLock' + if ($Reset.IsPresent) { + Lock-PodeObject -Name 'PetCategoryLock' -ScriptBlock { + Set-PodeState -Scope 'Categories' -Name 'categories' -Value @{} | Out-Null + Add-Category -Id 1 -Name 'Dogs' + Add-Category -Id 2 -Name 'Cats' + Add-Category -Id 3 -Name 'Rabbits' + Add-Category -Id 4 -Name 'Lions' + } + } +} +function Initialize-Pet { + param ( + [switch] + $Reset + ) + New-PodeLockable -Name 'PetLock' + if ($Reset.IsPresent) { + Lock-PodeObject -Name 'PetLock' -ScriptBlock { + Set-PodeState -Scope 'Pets' -Name 'pets' -Value @{} | Out-Null + Add-Pet -Id 1 -Cat 'Cats' -Name 'Cat 1' -Urls 'url1', 'url2' -Tags 'tag1', 'tag2' -Status available + Add-Pet -Id 2 -Cat 'Cats' -Name 'Cat 2' -Urls 'url1', 'url2' -Tags 'tag2', 'tag3' -Status available + Add-Pet -Id 3 -Cat 'Cats' -Name 'Cat 2' -Urls 'url1', 'url2' -Tags 'tag3', 'tag4' -Status pending + + Add-Pet -Id 4 -Cat 'Dogs' -Name 'Dog 1' -Urls 'url1', 'url2' -Tags 'tag1', 'tag2' -Status available + Add-Pet -Id 5 -Cat 'Dogs' -Name 'Dog 2' -Urls 'url1', 'url2' -Tags 'tag2', 'tag3' -Status sold + Add-Pet -Id 6 -Cat 'Dogs' -Name 'Dog 2' -Urls 'url1', 'url2' -Tags 'tag3', 'tag4' -Status pending + + Add-Pet -Id 7 -Cat 'Lions' -Name 'Lion 1' -Urls 'url1', 'url2' -Tags 'tag1', 'tag2' -Status available + Add-Pet -Id 8 -Cat 'Lions' -Name 'Lion 2' -Urls 'url1', 'url2' -Tags 'tag2', 'tag3' -Status available + Add-Pet -Id 9 -Cat 'Lions' -Name 'Lion 2' -Urls 'url1', 'url2' -Tags 'tag3', 'tag4' -Status available + + Add-Pet -Id 10 -Cat 'Rabbits' -Name 'Rabbit 1' -Urls 'url1', 'url2' -Tags 'tag2', 'tag3' -Status available + Add-Pet -Id 11 -Cat 'Rabbits' -Name 'Rabbit 2' -Urls 'url1', 'url2' -Tags 'tag3', 'tag4' -Status pending + } + } +} + + +function Add-Pet { + + [CmdletBinding(DefaultParameterSetName = 'Items')] + param ( + [Parameter(Mandatory, ParameterSetName = 'Items')] + [long] + $Id, + [Parameter( ParameterSetName = 'Items')] + [String] + $Category, + [Parameter(Mandatory, ParameterSetName = 'Items')] + [string] + $Name, + [Parameter(Mandatory, ParameterSetName = 'Items')] + [string[]] + $Urls, + [Parameter( ParameterSetName = 'Items')] + [string[]] + $Tags, + [Parameter( ParameterSetName = 'Items')] + [ValidateSet('pending', 'available', 'sold')] + [string] + $Status, + + [Parameter(Mandatory, ParameterSetName = 'Object')] + [hashtable] + $Pet + ) + Lock-PodeObject -Name 'PetLock' -ScriptBlock { + $pets = Get-PodeState -Name 'pets' + switch ($PSCmdlet.ParameterSetName) { + 'Items' { + $pets["$Id"] = @{ + id = $Id + categoryName = Get-Category -Name $Category + name = $Name + photoUrls = $Urls + tags = $Tags + status = $Status + } + } + 'Object' { + $pets["$($Pet.id)"] = $Pet + } + } } +} + + + + + +function Update-Pet { + + [CmdletBinding(DefaultParameterSetName = 'Items')] + param ( + [Parameter(Mandatory, ParameterSetName = 'Items')] + [long] + $Id, + [Parameter( ParameterSetName = 'Items')] + [String] + $Category, + [Parameter(Mandatory, ParameterSetName = 'Items')] + [string] + $Name, + [Parameter(Mandatory, ParameterSetName = 'Items')] + [string[]] + $Urls, + [Parameter( ParameterSetName = 'Items')] + [string[]] + $Tags, + [Parameter( ParameterSetName = 'Items')] + [ValidateSet('pending', 'available', 'sold')] + [string] + $Status, + + [Parameter(Mandatory, ParameterSetName = 'Object')] + [hashtable] + $Pet + ) + return Lock-PodeObject -Name 'PetLock' -Return -ScriptBlock { + $pets = Get-PodeState -Name 'pets' + switch ($PSCmdlet.ParameterSetName) { + 'Items' { + if ($pets.ContainsKey("$Id")) { + if ($Category) { + $pets["$Id"].categoryName = Get-Category -Name $Category + } + if ($Name) { + $pets["$Id"].name = $Name + } + if ($Urls) { + $pets["$Id"].photoUrls = $Urls + } + if ($Tags) { + $pets["$Id"].tags = $Tags + } + if ($Status) { + $pets["$Id"].status = $Status + } + return $true + } + } + 'Object' { + if ($pets.ContainsKey("$($Pet.id)")) { + $pets["$($Pet.id)"] = $Pet + return $true + } + } + } + return $false + } +} + + +function Get-Pet { + param ( + [Parameter(Mandatory)] + [long] + $Id + ) + return Lock-PodeObject -Name 'PetLock' -Return -ScriptBlock { + $pets = Get-PodeState -Name 'pets' + return $pets["$Id"] + } +} + + +function Test-Pet { + param ( + [Parameter(Mandatory)] + [long] + $Id + ) + return Lock-PodeObject -Name 'PetLock' -Return -ScriptBlock { + $pets = Get-PodeState -Name 'pets' + return $pets.ContainsKey("$Id") + } +} + + + +function Find-PetByStatus { + param ( + [Parameter(Mandatory)] + [string[]] + $Status + ) + return Lock-PodeObject -Name 'PetLock' -Return -ScriptBlock { + $result = @() + foreach ($pet in (Get-PodeState -Name 'pets').Values) { + foreach ($s in $Status) { + if ($s -ieq $pet.status) { + $result += $pet + break + } + } + } + return $result + } + +} + + +function Find-PetByTags { + param ( + [Parameter(Mandatory)] + [string[]] + $Tags + ) + + return Lock-PodeObject -Name 'PetLock' -Return -ScriptBlock { + $result = @() + foreach ($pet in (Get-PodeState -Name 'pets').Values) { + if ($pet.tags) { + foreach ($tag in $pet.tags) { + foreach ($tagListString in $Tags) { + if ($tagListString -ieq $tag) { + $result += $pet + break + } + } + } + } + } + return $result + } +} + + +function Remove-Pet { + param ( + [Parameter(Mandatory)] + [long] + $Id + ) + Lock-PodeObject -Name 'PetLock' -ScriptBlock { + $pets = (Get-PodeState -Name 'pets') + $pets.Remove( "$Id") + } +} + + +function Add-Category { + param ( + [Parameter(Mandatory)] + [long] + $Id, + [Parameter(Mandatory)] + [string] + $Name + ) + Lock-PodeObject -Name 'PetCategoryLock' -ScriptBlock { + $categories = (Get-PodeState -Name 'categories') + $categories[$Name] = $Id + } +} + + +function Get-Category { + [CmdletBinding(DefaultParameterSetName = 'Name')] + param ( + [Parameter(Mandatory, ParameterSetName = 'Name')] + [string] + $Name, + [Parameter(Mandatory, ParameterSetName = 'Id')] + [long] + $Id + ) + return Lock-PodeObject -Name 'PetCategoryLock' -Return -ScriptBlock { + $categories = (Get-PodeState -Name 'categories') + switch ($PSCmdlet.ParameterSetName) { + 'Name' { + if ($categories.ContainsKey($name)) { + return @{ + name = $name + id = $categories[$name] + } + } + } + 'Id' { + foreach ($c in $categories) { + if ($c.id -eq $Id ) { + return @{ + name = $c.name + id = $Id + } + } + } + } + } + return $null + } +} +Export-ModuleMember -Function Initialize-Categories +Export-ModuleMember -Function Initialize-Pet +Export-ModuleMember -Function Add-Pet +Export-ModuleMember -Function Update-Pet +Export-ModuleMember -Function Get-Pet +Export-ModuleMember -Function Find-PetByTags +Export-ModuleMember -Function Find-PetByStatus +Export-ModuleMember -Function Remove-Pet +Export-ModuleMember -Function Add-Category +Export-ModuleMember -Function Get-Category +Export-ModuleMember -Function Test-Pet \ No newline at end of file diff --git a/examples/PetStore/Petstore-openApi.ps1 b/examples/PetStore/Petstore-openApi.ps1 new file mode 100644 index 000000000..dafd4dfd3 --- /dev/null +++ b/examples/PetStore/Petstore-openApi.ps1 @@ -0,0 +1,854 @@ +param ( + [switch] + $Reset +) +$petStorePath = Split-Path -Parent -Path $MyInvocation.MyCommand.Path +$podePath = Split-Path -Parent -Path (Split-Path -Parent -Path $petStorePath) +if (Test-Path -Path "$($podePath)/src/Pode.psm1" -PathType Leaf) { + Import-Module "$($podePath)/src/Pode.psm1" -Force -ErrorAction Stop +} +else { + Import-Module -Name 'Pode' +} +function Write-ObjectContent { + param ( + [Parameter(Mandatory = $true, ValueFromPipeline = $true)] + $Object + ) + + Write-PodeHost -ForegroundColor Blue "Type:$($Object.gettype())" + $objectString = $Object | Out-String + Write-PodeHost -ForegroundColor Blue -Object $objectString + +} + +Import-Module -Name "$petStorePath/PetData.psm1" +Import-Module -Name "$petStorePath/Order.psm1" +Import-Module -Name "$petStorePath/UserData.psm1" + +Start-PodeServer -Threads 1 -ScriptBlock { + + $script:PetDataPath = Join-Path -Path $PetStorePath -ChildPath 'data' + If (!(Test-Path -PathType container -Path $script:PetDataPath)) { + New-Item -ItemType Directory -Path $script:PetDataPath -Force | Out-Null + } + + $script:PetImagesPath = Join-Path -Path $PetStorePath -ChildPath 'images' + If (!(Test-Path -PathType container -Path $script:PetImagesPath)) { + New-Item -ItemType Directory -Path $script:PetImagesPath -Force | Out-Null + } + + $script:CertsPath = Join-Path -Path $PetStorePath -ChildPath 'certs' + If (!(Test-Path -PathType container -Path $script:CertsPath)) { + New-Item -ItemType Directory -Path $script:CertsPath -Force | Out-Null + } + + + #Load data + $script:PetDataJson = Join-Path -Path $PetDataPath -ChildPath 'PetData.json' + if ($Reset.IsPresent -or !(Test-Path -Path $script:PetDataJson -PathType Leaf )) { + Initialize-Categories -Reset + Initialize-Pet -Reset + Initialize-Order -Reset + Initialize-Users -Reset + Save-PodeState -Path $script:PetDataJson + } + else { + Initialize-Categories + Initialize-Pet + Initialize-Order + Initialize-Users + # attempt to re-initialise the state (will do nothing if the file doesn't exist) + Restore-PodeState -Path $script:PetDataJson + } + + + if ((Get-PodeConfig).Protocol -eq 'Https') { + $Certificate = Join-Path -Path $CertsPath -ChildPath (Get-PodeConfig).Certificate + $CertificateKey = Join-Path -Path $CertsPath -ChildPath (Get-PodeConfig).CertificateKey + Add-PodeEndpoint -Address (Get-PodeConfig).Address -Port (Get-PodeConfig).RestFulPort -Protocol Https -Certificate $Certificate -CertificateKey $CertificateKey -CertificatePassword (Get-PodeConfig).CertificatePassword -Default + } + else { + Add-PodeEndpoint -Address (Get-PodeConfig).Address -Port (Get-PodeConfig).RestFulPort -Protocol Http -Default + } + + New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging + + #Configure CORS + Set-PodeSecurityAccessControl -Origin '*' -Duration 7200 -WithOptions -AuthorizationHeader -autoMethods -AutoHeader -Credentials -CrossDomainXhrRequests #-Header 'content-type' # -Header 'Accept','Content-Type' ,'Connection' #-Headers '*' 'x-requested-with' ,'crossdomain'# + + + #image folder + Add-PodeStaticRoute -Path '/images' -Source $script:PetImagesPath + + + + Enable-PodeOpenApi -Path '/docs/openapi' -OpenApiVersion '3.0.3' -EnableSchemaValidation -DisableMinimalDefinitions -NoDefaultResponses + + $swaggerDocs = New-PodeOAExternalDoc -Description 'Find out more about Swagger' -Url 'http://swagger.io' + $swaggerDocs | Add-PodeOAExternalDoc + + $InfoDescription = @' +This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about Swagger at [http://swagger.io](http://swagger.io). +In the third iteration of the pet store, we've switched to the design first approach! +You can now help us improve the API whether it's by making changes to the definition itself or to the code. +That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + +Some useful links: +- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) +- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) +'@ + + + Add-PodeOAInfo -Title 'Swagger Petstore - OpenAPI 3.0' -Version 1.0.17 -Description $InfoDescription -TermsOfService 'http://swagger.io/terms/' -LicenseName 'Apache 2.0' ` + -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' -ContactName 'API Support' -ContactEmail 'apiteam@swagger.io' + Add-PodeOAServerEndpoint -url '/api/v3' -Description 'default endpoint' + + + Enable-PodeOAViewer -Type Swagger -Path '/docs/swagger' + Enable-PodeOAViewer -Type ReDoc -Path '/docs/redoc' -DarkMode + Enable-PodeOAViewer -Type RapiDoc -Path '/docs/rapidoc' -DarkMode + Enable-PodeOAViewer -Type StopLight -Path '/docs/stoplight' -DarkMode + Enable-PodeOAViewer -Type Explorer -Path '/docs/explorer' -DarkMode + Enable-PodeOAViewer -Type RapiPdf -Path '/docs/rapipdf' -DarkMode + + Enable-PodeOAViewer -Editor -Path '/docs/swagger-editor' + Enable-PodeOAViewer -Bookmarks -Path '/docs' + + # setup session details + Enable-PodeSessionMiddleware -Duration 120 -Extend + + New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'read:pets' -Description 'read your pets' + New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'write:pets' -Description 'modify pets in your account' + $clientId = '123123123' + $clientSecret = '' + + New-PodeAuthScheme -OAuth2 -ClientId $ClientId -ClientSecret $ClientSecret ` + -AuthoriseUrl 'https://petstore3.swagger.io/oauth/authorize' ` + -TokenUrl 'https://petstore3.swagger.io/oauth/token' ` + -Scope 'read:pets', 'write:pets' | + Add-PodeAuth -Name 'petstore_auth' -FailureUrl 'https://petstore3.swagger.io/oauth/failure' -SuccessUrl '/' -ScriptBlock { + param($user, $accessToken, $refreshToken) + return @{ User = $user } + } + + New-PodeAuthScheme -ApiKey -LocationName 'api_key' | Add-PodeAuth -Name 'api_key' -Sessionless -ScriptBlock { + param($key) + if ($key) { + # here you'd check a real storage, this is just for example + if ($key -eq 'test-key') { + return @{ + User = @{ + 'ID' = 'M0R7Y302' + 'Name' = 'Morty' + 'Type' = 'Human' + } + } + } + + # authentication failed + return @{ + Code = 401 + Challenge = 'qop="auth", nonce=""' + } + } + else { + return @{ + Message = 'No Authorization header found' + Code = 401 + } + + } + } + + New-PodeAuthScheme -Basic -Realm 'PetStore' | Add-PodeAuth -Name 'Basic' -Sessionless -ScriptBlock { + param($username, $password) + + # here you'd check a real user storage, this is just for example + if ($username -eq 'morty' -and $password -eq 'pickle') { + return @{ + User = @{ + ID = 'M0R7Y302' + Name = 'Morty' + Type = 'Human' + Username = 'm.orty' + Scopes = @( 'read:pets' , 'write:pets' ) + } + } + } + return @{ Message = 'Invalid details supplied' } + } + + Merge-PodeAuth -Name 'merged_auth' -Authentication 'Basic', 'api_key' -Valid One + Merge-PodeAuth -Name 'merged_auth_All' -Authentication 'Basic', 'api_key' -Valid All -ScriptBlock {} + Merge-PodeAuth -Name 'merged_auth_nokey' -Authentication 'Basic' -Valid One + + Add-PodeOATag -Name 'user' -Description 'Operations about user' + Add-PodeOATag -Name 'store' -Description 'Access to Petstore orders' -ExternalDoc $swaggerDocs + Add-PodeOATag -Name 'pet' -Description 'Everything about your Pets' -ExternalDoc $swaggerDocs + + + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 10 -Required | + New-PodeOAIntProperty -Name 'petId' -Format Int64 -Example 198772 -Required | + New-PodeOAIntProperty -Name 'quantity' -Format Int32 -Example 7 -Required | + New-PodeOAStringProperty -Name 'shipDate' -Format Date-Time | + New-PodeOAStringProperty -Name 'status' -Description 'Order Status' -Required -Example 'approved' -Enum @('placed', 'approved', 'delivered') | + New-PodeOABoolProperty -Name 'complete' | + New-PodeOAObjectProperty -XmlName 'order' | + Add-PodeOAComponentSchema -Name 'Order' + + New-PodeOAStringProperty -Name 'street' -Example '437 Lytton' -Required | + New-PodeOAStringProperty -Name 'city' -Example 'Palo Alto' -Required | + New-PodeOAStringProperty -Name 'state' -Example 'CA' -Required | + New-PodeOAStringProperty -Name 'zip' -Example '94031' -Required | + New-PodeOAObjectProperty -XmlName 'address' | + Add-PodeOAComponentSchema -Name 'Address' + + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 100000 | + New-PodeOAStringProperty -Name 'username' -example 'fehguy' | + New-PodeOASchemaProperty -Name 'Address' -Reference 'Address' -Array -XmlName 'addresses' -XmlWrapped | + New-PodeOAObjectProperty -XmlName 'customer' | + Add-PodeOAComponentSchema -Name 'Customer' + + + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 1 | + New-PodeOAStringProperty -Name 'name' -Example 'Dogs' | + New-PodeOAObjectProperty -XmlName 'category' | + Add-PodeOAComponentSchema -Name 'Category' + + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 10 | + New-PodeOAStringProperty -Name 'username' -Example 'theUser' -Required | + New-PodeOAStringProperty -Name 'firstName' -Example 'John' | + New-PodeOAStringProperty -Name 'lastName' -Example 'James' | + New-PodeOAStringProperty -Name 'email' -Format email -Example 'john@email.com' | + New-PodeOAStringProperty -Name 'lastName' -Example 'James' | + New-PodeOAStringProperty -Name 'password' -Format Password -Example '12345' -Required | + New-PodeOAStringProperty -Name 'phone' -Example '12345' | + New-PodeOAIntProperty -Name 'userStatus'-Format Int32 -Description 'User Status' -Example 1 | + New-PodeOAObjectProperty -XmlName 'user' | + Add-PodeOAComponentSchema -Name 'User' + + + + New-PodeOAIntProperty -Name 'id'-Format Int64 | + New-PodeOAStringProperty -Name 'name' | + New-PodeOAObjectProperty -XmlName 'tag' | + Add-PodeOAComponentSchema -Name 'Tag' + + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 10 -Required | + New-PodeOAStringProperty -Name 'name' -Example 'doggie' -Required | + New-PodeOASchemaProperty -Name 'category' -Reference 'Category' | + New-PodeOAStringProperty -Name 'photoUrls' -Array -XmlWrapped -XmlItemName 'photoUrl' -Required | + New-PodeOASchemaProperty -Name 'tags' -Reference 'Tag' -Array -XmlWrapped | + New-PodeOAStringProperty -Name 'status' -Description 'pet status in the store' -Enum @('available', 'pending', 'sold') | + New-PodeOAObjectProperty -XmlName 'pet' | + Add-PodeOAComponentSchema -Name 'Pet' + + + + New-PodeOAIntProperty -Name 'code'-Format Int32 | + New-PodeOAStringProperty -Name 'type' | + New-PodeOAStringProperty -Name 'message' | + New-PodeOAObjectProperty -XmlName '##default' | + Add-PodeOAComponentSchema -Name 'ApiResponse' + + + Add-PodeOAComponentRequestBody -Name 'Pet' -Description 'Pet object that needs to be added to the store' -Content ( + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet') + + Add-PodeOAComponentRequestBody -Name 'UserArray' -Description 'List of user object' -Content ( + New-PodeOAContentMediaType -MediaType 'application/json' -Content 'User' -Array) + + + + + Add-PodeRouteGroup -Path '/api/v3' -Routes { + <# + PUT '/pet' + #> + Add-PodeRoute -PassThru -Method Put -Path '/pet' -Authentication 'merged_auth_nokey' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + switch ($contentType) { + 'application/xml' { + $pet = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $pet = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($pet -and $WebEvent.data.id) { + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $pet -SchemaReference 'Pet' + } + else { + $Validate = @{'result' = $true } + } + if ($Validate.result) { + if (Update-Pet -Pet (convertfrom-json -InputObject $pet -AsHashtable)) { + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -StatusCode 404 -Value 'Pet not found' + } + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } + } + else { + Write-PodeHtmlResponse -StatusCode 400 -Value 'Invalid ID supplied' + } + } | Set-PodeOARouteInfo -Summary 'Update an existing pet' -Description 'Update an existing pet by Id' -Tags 'pet' -OperationId 'updatePet' -PassThru | + Set-PodeOARequest -RequestBody ( + New-PodeOARequestBody -Description 'Update an existent pet in the store' -Required -Content ( + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Pet not found' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Validation exception' + + + <# + POST '/pet' + #> + Add-PodeRoute -PassThru -Method Post -Path '/pet' -Authentication 'merged_auth_nokey' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + switch ($contentType) { + 'application/xml' { + $pet = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $pet = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $pet -SchemaReference 'Pet' + } + else { + $Validate = @{'result' = $true } + } + if ($Validate.result) { + Add-Pet -Pet (convertfrom-json -InputObject $pet -AsHashtable) + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } + } | Set-PodeOARouteInfo -Summary 'Add a new pet to the store' -Description 'Add a new pet to the store' -Tags 'pet' -OperationId 'addPet' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Description 'Create a new pet in the store' -Required -Content ( + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid input' + + + <# + GET '/pet/findByStatus' + #> + Add-PodeRoute -PassThru -Method get -Path '/pet/findByStatus' -Authentication 'merged_auth_nokey' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $status = $WebEvent.Query['status'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($status) { + $pets = Find-PetByStatus -Status $status + if ($null -eq $pets) { + $pets = @() + } + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $pets -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $pets -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'Invalid status value' -StatusCode 400 + } + + } | Set-PodeOARouteInfo -Summary 'Finds Pets by status' -Description 'Multiple status values can be provided with comma separated strings' -Tags 'pet' -OperationId 'findPetsByStatus' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( + New-PodeOAStringProperty -Name 'status' -Description 'Status values that need to be considered for filter' -Default 'available' -Enum @('available', 'pending', 'sold') | + ConvertTo-PodeOAParameter -In Query -Explode ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' -Array) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid status value' -PassThru | + Add-PodeOAResponse -StatusCode 415 + + <# + GET '/pet/findByTags' + #> + Add-PodeRoute -PassThru -Method get -Path '/pet/findByTags' -Authentication 'merged_auth_nokey' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $tags = $WebEvent.Query['tags'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($tags) { + $pets = Find-PetByTags -Tags $tags + if ($null -eq $pets) { + $pets = @() + } + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $pets -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $pets -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'Invalid tag value' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Finds Pets by tags' -Description 'Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.' -Tags 'pet' -OperationId 'findPetsByTags' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( + New-PodeOAStringProperty -Name 'tags' -Description 'Tags to filter by' -Array | + ConvertTo-PodeOAParameter -In Query -Explode ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' -Array) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid tag value' -PassThru | + Add-PodeOAResponse -StatusCode 415 + + + + <# + GET '/pet/{petId}' + #> + Add-PodeRoute -PassThru -Method Get -Path '/pet/:petId' -Authentication 'merged_auth' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $petId = $WebEvent.Parameters['petId'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($petId) { + $pet = Get-Pet -Id $petId + if ($pet) { + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $pet -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $pet -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'Pet not found' -StatusCode 404 + } + } + else { + Write-PodeJsonResponse -Value 'Invalid ID supplied' -StatusCode 400 + } + + } | Set-PodeOARouteInfo -Summary 'Find pet by ID' -Description 'Returns a single pet.' -Tags 'pet' -OperationId 'getPetById' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( + New-PodeOAIntProperty -Name 'petId' -Description 'ID of pet to return' -Format Int64 | + ConvertTo-PodeOAParameter -In Path -Required ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet') -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Pet not found' -PassThru | + Add-PodeOAResponse -StatusCode 415 + + + <# + POST '/pet/{petId}' + #> + + Add-PodeRoute -PassThru -Method post -Path '/pet/:petId' -Authentication 'petstore_auth' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $petId = $WebEvent.Parameters['petId'] + $name = $WebEvent.Query['name'] + $status = $WebEvent.Query['status'] + + if ($petId -and (Test-Pet -Id $petId)) { + if (Update-Pet -Id $petId -Name $name -Status $status) { + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value 'Invalid Input' + } + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value 'Invalid Input' + } + } | Set-PodeOARouteInfo -Summary 'Updates pet with ID' -Description 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatePetWithForm' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( New-PodeOAIntProperty -Name 'petId' -Description 'ID of pet that needs to be updated' -Format Int64 | + ConvertTo-PodeOAParameter -In Path -Required ), + ( New-PodeOAStringProperty -Name 'name' -Description 'Name of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) , + ( New-PodeOAStringProperty -Name 'status' -Description 'Status of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + <# + DELETE '/pet/{petId}' + #> + Add-PodeRoute -PassThru -Method Delete -Path '/pet/:petId' -Authentication 'merged_auth_All' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $petId = $WebEvent.Parameters['petId'] + if ($petId -and (Test-Pet -Id $petId)) { + Remove-Pet -Id $petId + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -Value 'Invalid pet value' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Deletes pet by ID' -Description 'Deletes a pet.' -Tags 'pet' -OperationId 'deletePet' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( + New-PodeOAIntProperty -Name 'petId' -Description 'ID of pet that needs to be updated' -Format Int64 | + ConvertTo-PodeOAParameter -In Path -Required ) | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid pet value' + + + + #TO DO + <# + POST '/pet/{petId}/uploadImage' + #> + Add-PodeRoute -PassThru -Method post -Path '/pet/:petId/uploadImage' -Authentication 'petstore_auth' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $petId = $WebEvent.Parameters['petId'] + $additionalMetadata = $WebEvent.Query['additionalMetadata'] + if ($petId -and (Test-Pet -Id $petId)) { + $pet = Get-Pet -Id $petId + $image = "$petId-$(New-Guid).$additionalMetadata" + $outputFilePath = Join-Path -Path $using:PetImagesPath -AdditionalChildPath $image + [System.IO.File]::WriteAllBytes($outputFilePath, $WebEvent.data) + $url = "$((Get-PodeConfig).Protocol)://$((Get-PodeConfig).Address):$((Get-PodeConfig).RestFulPort)/images/$image" + $pet.photoUrls.add($url) + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -Value 'Invalid pet value' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Uploads an image' -Tags 'pet' -OperationId 'uploadFile' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAIntProperty -Name 'petId' -Format Int64 -Description 'ID of pet to update' -Required | ConvertTo-PodeOAParameter -In Path ), + ( New-PodeOAStringProperty -Name 'additionalMetadata' -Description 'Additional Metadata' | ConvertTo-PodeOAParameter -In Query ) + ) -RequestBody ( + New-PodeOARequestBody -Content ( New-PodeOAContentMediaType -MediaType 'application/octet-stream' -Upload ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content @{'application/json' = 'ApiResponse' } + + + + <# + GET '/store/inventory' + #> + Add-PodeRoute -PassThru -Method Get -Path '/store/inventory' -Authentication 'api_key' -ScriptBlock { + $result = Get-CountByStatus + Write-PodeJsonResponse -Value $result -StatusCode 200 + + } | Set-PodeOARouteInfo -Summary 'Returns pet inventories by status' -Description 'Returns a map of status codes to quantities' -Tags 'store' -OperationId 'getInventory' -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content @{ 'application/json' = New-PodeOAObjectProperty -AdditionalProperties (New-PodeOAIntProperty -Format Int32 ) } + + + <# + POST '/store/order' + #> + Add-PodeRoute -PassThru -Method post -Path '/store/order' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + switch ($contentType) { + 'application/xml' { + $order = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $order = ConvertTo-Json $WebEvent.data } + 'application/x-www-form-urlencoded' { $order = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $order -SchemaReference 'Order' + } + else { + #no test schema support for XML + $Validate = @{'result' = $true } + } + if ($Validate.result) { + Add-Order -Order (convertfrom-json -InputObject $order -AsHashtable) + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } + } | Set-PodeOARouteInfo -Summary 'Place an order for a pet' -Description 'Place a new order in the store' -Tags 'store' -OperationId 'placeOrder' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'Order' )) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (@{ 'application/json' = 'Order' }) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + <# + GET '/store/order/{orderId}' + #> + Add-PodeRoute -PassThru -Method Get -Path '/store/order/:orderId' -ScriptBlock { + $orderId = $WebEvent.Parameters['orderId'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($orderId) { + $order = Get-Order -Id $orderId + if ($order) { + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $order -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $order -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'Order not found' -StatusCode 404 + } + } + else { + Write-PodeHtmlResponse -Value 'No orderId provided. Try again?' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Find purchase order by ID' -Description 'For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions.' -Tags 'store' -OperationId 'getOrderById' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAIntProperty -Name 'orderId' -Format Int64 -Description 'ID of order that needs to be fetched' -Required | ConvertTo-PodeOAParameter -In Path ) + ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Order' ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Order not found' + + <# + DELETE '/store/order/{orderId}' + #> + Add-PodeRoute -PassThru -Method Delete -Path '/store/order/:orderId' -ScriptBlock { + $orderId = $WebEvent.Parameters['orderId'] + if ($orderId ) { + if ( Test-Order -Id $orderId) { + Remove-Order -Id $orderId + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -Value 'Order not found' -StatusCode 404 + } + } + else { + Write-PodeJsonReWrite-PodeHtmlResponsesponse -Value 'Invalid ID supplied' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Delete purchase order by ID' -Description 'For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors.' -Tags 'store' -OperationId 'deleteOrder' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAIntProperty -Name 'orderId' -Format Int64 -Description ' ID of the order that needs to be deleted' -Required | ConvertTo-PodeOAParameter -In Path ) + ) | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Order not found' + + + + <# + POST '/user' + #> + + Add-PodeRoute -PassThru -Method Post -Path '/user' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + $responseMediaType = Get-PodeHeader -Name 'Accept' + switch ($contentType) { + 'application/xml' { + $user = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $user = ConvertTo-Json $WebEvent.data } + 'application/x-www-form-urlencoded' { $user = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $user -SchemaReference 'User' + } + else { + #no test schema support for XML + $Validate = @{'result' = $true } + } + if ($Validate.result) { + $newUser = Add-user -User (convertfrom-json -InputObject $user -AsHashtable) + Save-PodeState -Path $using:PetDataJson + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $newUser -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $newUser -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } + } | Set-PodeOARouteInfo -Summary 'Create user.' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'createUser' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' )) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' -PassThru | + Add-PodeOAResponse -Default -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'User' ) + + + <# + POST '/user/createWithList' + #> + Add-PodeRoute -PassThru -Method post -Path '/user/createWithList' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + $responseMediaType = Get-PodeHeader -Name 'Accept' + $newUsers = @() + foreach ($user in $WebEvent.data) { + switch ($contentType) { + 'application/json' { $userJson = ConvertTo-Json $user } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $userJson -SchemaReference 'User' + } + else { + #no test schema support for XML + $Validate = @{'result' = $true } + } + if ($Validate.result) { + $newUsers += $user + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + return + } + } + $createdUsers = @() + foreach ($u in $newUsers) { + $createdUsers += Add-User -User $u + } + Save-PodeState -Path $using:PetDataJson + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $createdUsers -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $createdUsers -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } | Set-PodeOARouteInfo -Summary 'Creates list of users with given input array.' -Description 'Creates list of users with given input array.' -Tags 'user' -OperationId 'createUsersWithListInput' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Content (New-PodeOAContentMediaType -MediaType 'application/json' -Content 'User' -Array)) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'User' -Array ) -PassThru | + Add-PodeOAResponse -Default -Description 'successful operation' + + + <# + GET '/user/login' + #> + Add-PodeRoute -PassThru -Method Get -Path '/user/login' -ScriptBlock { + $username = $WebEvent.Query['username'] + $password = $WebEvent.Query['password'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($username) { + $user = Get-User -Username $username + if ($user -and $user['password'] -eq $password) { + Set-PodeHeader -Name 'X-Expires-After' -Value ((Get-Date).AddHours(1).ToString('yyyy-MM-ddTHH:mm:ssK')) + Set-PodeHeader -Name 'X-Rate-Limit' -Value '5000' + $result = @{'api_key' = 'test-key' } + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $result -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $result -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'Invalid username/password supplied' -StatusCode 400 + } + } + else { + Write-PodeHtmlResponse -Value 'Invalid username/password supplied' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Logs user into the system.' -Tags 'user' -OperationId 'loginUser' -PassThru | + Set-PodeOARequest -Parameters ( New-PodeOAStringProperty -Name 'username' -Description 'The user name for login' | ConvertTo-PodeOAParameter -In Query ), + ( New-PodeOAStringProperty -Name 'password' -Description 'The password for login in clear text' -Format Password | ConvertTo-PodeOAParameter -In Query ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'string' ) ` + -Headers (New-PodeOAIntProperty -Name 'X-Rate-Limit' -Description 'calls per hour allowed by the user' -Format Int32), + (New-PodeOAStringProperty -Name 'X-Expires-After' -Description 'date in UTC when token expires' -Format Date-Time) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username/password supplied' + + <# + GET '/user/logout' + #> + Add-PodeRoute -PassThru -Method Get -Path '/user/logout' -ScriptBlock { + Write-PodeJsonResponse -Value 'Successful operation' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Logs out current logged in user session.' -Tags 'user' -OperationId 'logoutUser' -PassThru | + Add-PodeOAResponse -Default -Description 'Successful operation' + + + <# + GET '/user/{username}' + #> + Add-PodeRoute -PassThru -Method Get -Path '/user/:username' -ScriptBlock { + $username = $WebEvent.Parameters['username'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($username) { + $user = Get-User -Username $username + if ($user) { + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $user -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $user -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'User not found' -StatusCode 404 + } + } + else { + Write-PodeHtmlResponse -Value 'Invalid username supplied' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Get user by user name' -Tags 'user' -OperationId 'getUserByName' -PassThru | + Set-PodeOARequest -Parameters ( New-PodeOAStringProperty -Name 'username' -Description 'The name that needs to be fetched. Use user1 for testing.' -Required | ConvertTo-PodeOAParameter -In Path ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'User' ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' + + <# + PUT '/user/{username}' + #> + Add-PodeRoute -PassThru -Method Put -Path '/user/:username' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + $username = $WebEvent.Parameters['username'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if (Test-User -Username $username) { + switch ($contentType) { + 'application/xml' { + $user = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $user = ConvertTo-Json $WebEvent.data } + 'application/x-www-form-urlencoded' { $user = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $user -SchemaReference 'User' + } + else { + #no test schema support for XML + $Validate = @{'result' = $true } + } + if ($Validate.result) { + $newUser = Add-user -User (convertfrom-json -InputObject $user -AsHashtable) + Save-PodeState -Path $using:PetDataJson + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $newUser -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $newUser -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } + } + else { + Write-PodeHtmlResponse -StatusCode 404 -Value 'User not found' + } + } | Set-PodeOARouteInfo -Summary 'Update user' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'updateUser' -PassThru | + Set-PodeOARequest -Parameters ( New-PodeOAStringProperty -Name 'username' -Description ' name that need to be updated.' -Required | ConvertTo-PodeOAParameter -In Path ) ` + -RequestBody ( New-PodeOARequestBody -Required -Description 'Update an existent user in the store' -Content ( + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' + )) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' -PassThru | + Add-PodeOAResponse -Default -Description 'successful operation' + + <# + DELETE '/user/{username}' + #> + Add-PodeRoute -PassThru -Method Delete -Path '/user/:username' -ScriptBlock { + $username = $WebEvent.Parameters['username'] + if ($username ) { + if ( Test-User -Username $username) { + Remove-User -Username $orderId + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -Value 'User not found' -StatusCode 404 + } + } + else { + Write-PodeJsonReWrite-PodeHtmlResponsesponse -Value 'Invalid username supplied' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Delete user' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'deleteUser' -PassThru | + Set-PodeOARequest -Parameters ( New-PodeOAStringProperty -Name 'username' -Description 'The name that needs to be deleted.' -Required | ConvertTo-PodeOAParameter -In Path ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' + } +} \ No newline at end of file diff --git a/examples/PetStore/Petstore-openApiMultiTag.ps1 b/examples/PetStore/Petstore-openApiMultiTag.ps1 new file mode 100644 index 000000000..c3461032c --- /dev/null +++ b/examples/PetStore/Petstore-openApiMultiTag.ps1 @@ -0,0 +1,871 @@ +param ( + [switch] + $Reset +) +$petStorePath = Split-Path -Parent -Path $MyInvocation.MyCommand.Path +$podePath = Split-Path -Parent -Path (Split-Path -Parent -Path $petStorePath) +if (Test-Path -Path "$($podePath)/src/Pode.psm1" -PathType Leaf) { + Import-Module "$($podePath)/src/Pode.psm1" -Force -ErrorAction Stop +} +else { + Import-Module -Name 'Pode' +} + +Import-Module -Name "$petStorePath/PetData.psm1" +Import-Module -Name "$petStorePath/Order.psm1" +Import-Module -Name "$petStorePath/UserData.psm1" + +Start-PodeServer -Threads 1 -ScriptBlock { + + $script:PetDataPath = Join-Path -Path $PetStorePath -ChildPath 'data' + If (!(Test-Path -PathType container -Path $script:PetDataPath)) { + New-Item -ItemType Directory -Path $script:PetDataPath -Force | Out-Null + } + + $script:PetImagesPath = Join-Path -Path $PetStorePath -ChildPath 'images' + If (!(Test-Path -PathType container -Path $script:PetImagesPath)) { + New-Item -ItemType Directory -Path $script:PetImagesPath -Force | Out-Null + } + + $script:CertsPath = Join-Path -Path $PetStorePath -ChildPath 'certs' + If (!(Test-Path -PathType container -Path $script:CertsPath)) { + New-Item -ItemType Directory -Path $script:CertsPath -Force | Out-Null + } + + + #Load data + $script:PetDataJson = Join-Path -Path $PetDataPath -ChildPath 'PetData.json' + if ($Reset.IsPresent -or !(Test-Path -Path $script:PetDataJson -PathType Leaf )) { + Initialize-Categories -Reset + Initialize-Pet -Reset + Initialize-Order -Reset + Initialize-Users -Reset + Save-PodeState -Path $script:PetDataJson + } + else { + Initialize-Categories + Initialize-Pet + Initialize-Order + Initialize-Users + # attempt to re-initialise the state (will do nothing if the file doesn't exist) + Restore-PodeState -Path $script:PetDataJson + } + + + if ((Get-PodeConfig).Protocol -eq 'Https') { + $Certificate = Join-Path -Path $CertsPath -ChildPath (Get-PodeConfig).Certificate + $CertificateKey = Join-Path -Path $CertsPath -ChildPath (Get-PodeConfig).CertificateKey + Add-PodeEndpoint -Address (Get-PodeConfig).Address -Port (Get-PodeConfig).RestFulPort -Protocol Https -Certificate $Certificate -CertificateKey $CertificateKey -CertificatePassword (Get-PodeConfig).CertificatePassword -Default + } + else { + Add-PodeEndpoint -Address (Get-PodeConfig).Address -Port (Get-PodeConfig).RestFulPort -Protocol Http -Default -Name 'endpoint_v3' + Add-PodeEndpoint -Address (Get-PodeConfig).Address -Port ((Get-PodeConfig).RestFulPort + 1) -Protocol Http -Default -Name 'endpoint_v3.1' + } + New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging + + #Configure CORS + Set-PodeSecurityAccessControl -Origin '*' -Duration 7200 -WithOptions -AuthorizationHeader -autoMethods -AutoHeader -Credentials -CrossDomainXhrRequests #-Header 'content-type' # -Header 'Accept','Content-Type' ,'Connection' #-Headers '*' 'x-requested-with' ,'crossdomain'# + + + #image folder + Add-PodeStaticRoute -Path '/images' -Source $script:PetImagesPath + + + + Enable-PodeOpenApi -Path '/docs/openapi/v3.0' -OpenApiVersion '3.0.2' -EnableSchemaValidation -DisableMinimalDefinitions -NoDefaultResponses -EndpointName 'endpoint_v3' + Enable-PodeOpenApi -Path '/docs/openapi/v3.1' -OpenApiVersion '3.1.0' -EnableSchemaValidation -DisableMinimalDefinitions -NoDefaultResponses -DefinitionTag 'v3.1' -EndpointName 'endpoint_v3.1' + $swaggerDocs = New-PodeOAExternalDoc -Description 'Find out more about Swagger' -Url 'http://swagger.io' + $swaggerDocs | Add-PodeOAExternalDoc -DefinitionTag 'v3.0.3', 'v3.1' + + + + $InfoDescription = @' +This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about Swagger at [http://swagger.io](http://swagger.io). +In the third iteration of the pet store, we've switched to the design first approach! +You can now help us improve the API whether it's by making changes to the definition itself or to the code. +That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + +Some useful links: +- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) +- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) +'@ + + + Add-PodeOAInfo -Title 'Swagger Petstore - OpenAPI 3.0' -Version 1.0.17 -Description $InfoDescription -TermsOfService 'http://swagger.io/terms/' -LicenseName 'Apache 2.0' ` + -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' -ContactName 'API Support' -ContactEmail 'apiteam@swagger.io' -DefinitionTag 'v3.0.3' + + Add-PodeOAInfo -Title 'Swagger Petstore - OpenAPI 3.1' -Version 1.0.17 -Description $InfoDescription -TermsOfService 'http://swagger.io/terms/' -LicenseName 'Apache 2.0' ` + -LicenseUrl 'http://www.apache.org/licenses/LICENSE-2.0.html' -ContactName 'API Support' -ContactEmail 'apiteam@swagger.io' -DefinitionTag 'v3.1' + + Add-PodeOAServerEndpoint -url '/api/v3' -Description 'default endpoint' -DefinitionTag 'v3.0.3', 'v3.1' + + #OpenAPI 3.0 + Enable-PodeOAViewer -Type Swagger -Path '/docs/swagger' -DefinitionTag 'v3.0.3' -EndpointName 'endpoint_v3' + Enable-PodeOAViewer -Type ReDoc -Path '/docs/redoc' -DarkMode -DefinitionTag 'v3.0.3' -EndpointName 'endpoint_v3' + Enable-PodeOAViewer -Type RapiDoc -Path '/docs/rapidoc' -DarkMode -DefinitionTag 'v3.0.3' -EndpointName 'endpoint_v3' + Enable-PodeOAViewer -Type StopLight -Path '/docs/stoplight' -DarkMode -DefinitionTag 'v3.0.3' -EndpointName 'endpoint_v3' + Enable-PodeOAViewer -Type Explorer -Path '/docs/explorer' -DarkMode -DefinitionTag 'v3.0.3' -EndpointName 'endpoint_v3' + Enable-PodeOAViewer -Type RapiPdf -Path '/docs/rapipdf' -DarkMode -DefinitionTag 'v3.0.3' -EndpointName 'endpoint_v3' + Enable-PodeOAViewer -Bookmarks -Path '/docs' -DefinitionTag 'v3.0.3' -EndpointName 'endpoint_v3' + Enable-PodeOAViewer -Editor -Path '/docs/swagger-editor' -DefinitionTag 'v3.0.3' -EndpointName 'endpoint_v3' + + #OpenAPI 3.1 + Enable-PodeOAViewer -Type Swagger -Path '/docs/swagger' -DefinitionTag 'v3.1' -EndpointName 'endpoint_v3.1' + Enable-PodeOAViewer -Type ReDoc -Path '/docs/vredoc' -DarkMode -DefinitionTag 'v3.1' -EndpointName 'endpoint_v3.1' + Enable-PodeOAViewer -Type RapiDoc -Path '/docs/rapidoc' -DarkMode -DefinitionTag 'v3.1' -EndpointName 'endpoint_v3.1' + Enable-PodeOAViewer -Type StopLight -Path '/docs/stoplight' -DarkMode -DefinitionTag 'v3.1' -EndpointName 'endpoint_v3.1' + Enable-PodeOAViewer -Type Explorer -Path '/docs/explorer' -DarkMode -DefinitionTag 'v3.1' -EndpointName 'endpoint_v3.1' + Enable-PodeOAViewer -Bookmarks -Path '/docs' -DefinitionTag 'v3.1' -EndpointName 'endpoint_v3.1' + + # setup session details + Enable-PodeSessionMiddleware -Duration 120 -Extend + + New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'read:pets' -Description 'read your pets' + New-PodeAccessScheme -Type Scope | Add-PodeAccess -Name 'write:pets' -Description 'modify pets in your account' + $clientId = '123123123' + $clientSecret = '' + + New-PodeAuthScheme -OAuth2 -ClientId $ClientId -ClientSecret $ClientSecret ` + -AuthoriseUrl 'https://petstore3.swagger.io/oauth/authorize' ` + -TokenUrl 'https://petstore3.swagger.io/oauth/token' ` + -Scope 'read:pets', 'write:pets' | + Add-PodeAuth -Name 'petstore_auth' -FailureUrl 'https://petstore3.swagger.io/oauth/failure' -SuccessUrl '/' -ScriptBlock { + param($user, $accessToken, $refreshToken) + return @{ User = $user } + } + + New-PodeAuthScheme -ApiKey -LocationName 'api_key' | Add-PodeAuth -Name 'api_key' -Sessionless -ScriptBlock { + param($key) + if ($key) { + # here you'd check a real storage, this is just for example + if ($key -eq 'test-key') { + return @{ + User = @{ + 'ID' = 'M0R7Y302' + 'Name' = 'Morty' + 'Type' = 'Human' + } + } + } + + # authentication failed + return @{ + Code = 401 + Challenge = 'qop="auth", nonce=""' + } + } + else { + return @{ + Message = 'No Authorization header found' + Code = 401 + } + + } + } + + New-PodeAuthScheme -Basic -Realm 'PetStore' | Add-PodeAuth -Name 'Basic' -Sessionless -ScriptBlock { + param($username, $password) + write-host $username + write-host $password + + # here you'd check a real user storage, this is just for example + if ($username -eq 'morty' -and $password -eq 'pickle') { + return @{ + User = @{ + ID = 'M0R7Y302' + Name = 'Morty' + Type = 'Human' + Username = 'm.orty' + Scopes = @( 'read:pets' , 'write:pets' ) + } + } + } + return @{ Message = 'Invalid details supplied' } + } + + Merge-PodeAuth -Name 'merged_auth' -Authentication 'Basic', 'api_key' -Valid One + Merge-PodeAuth -Name 'merged_auth_All' -Authentication 'Basic', 'api_key' -Valid All -ScriptBlock {} + Merge-PodeAuth -Name 'merged_auth_nokey' -Authentication 'Basic' -Valid One + + Add-PodeOATag -Name 'user' -Description 'Operations about user' -DefinitionTag 'v3.0.3' + Add-PodeOATag -Name 'store' -Description 'Access to Petstore orders' -ExternalDoc $swaggerDocs -DefinitionTag 'v3.0.3' + Add-PodeOATag -Name 'pet' -Description 'Everything about your Pets' -ExternalDoc $swaggerDocs -DefinitionTag 'v3.0.3' + + + Select-PodeOADefinition -Tag 'v3.0.3', 'v3.1' -Scriptblock { + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 10 -Required | + New-PodeOAIntProperty -Name 'petId' -Format Int64 -Example 198772 -Required | + New-PodeOAIntProperty -Name 'quantity' -Format Int32 -Example 7 -Required | + New-PodeOAStringProperty -Name 'shipDate' -Format Date-Time | + New-PodeOAStringProperty -Name 'status' -Description 'Order Status' -Required -Example 'approved' -Enum @('placed', 'approved', 'delivered') | + New-PodeOABoolProperty -Name 'complete' | + New-PodeOAObjectProperty -XmlName 'order' | + Add-PodeOAComponentSchema -Name 'Order' + + New-PodeOAStringProperty -Name 'street' -Example '437 Lytton' -Required | + New-PodeOAStringProperty -Name 'city' -Example 'Palo Alto' -Required | + New-PodeOAStringProperty -Name 'state' -Example 'CA' -Required | + New-PodeOAStringProperty -Name 'zip' -Example '94031' -Required | + New-PodeOAObjectProperty -XmlName 'address' | + Add-PodeOAComponentSchema -Name 'Address' + + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 100000 | + New-PodeOAStringProperty -Name 'username' -example 'fehguy' | + New-PodeOASchemaProperty -Name 'Address' -Reference 'Address' -Array -XmlName 'addresses' -XmlWrapped | + New-PodeOAObjectProperty -XmlName 'customer' | + Add-PodeOAComponentSchema -Name 'Customer' + + + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 1 | + New-PodeOAStringProperty -Name 'name' -Example 'Dogs' | + New-PodeOAObjectProperty -XmlName 'category' | + Add-PodeOAComponentSchema -Name 'Category' + + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 10 | + New-PodeOAStringProperty -Name 'username' -Example 'theUser' -Required | + New-PodeOAStringProperty -Name 'firstName' -Example 'John' | + New-PodeOAStringProperty -Name 'lastName' -Example 'James' | + New-PodeOAStringProperty -Name 'email' -Format email -Example 'john@email.com' | + New-PodeOAStringProperty -Name 'lastName' -Example 'James' | + New-PodeOAStringProperty -Name 'password' -Format Password -Example '12345' -Required | + New-PodeOAStringProperty -Name 'phone' -Example '12345' | + New-PodeOAIntProperty -Name 'userStatus'-Format Int32 -Description 'User Status' -Example 1 | + New-PodeOAObjectProperty -XmlName 'user' | + Add-PodeOAComponentSchema -Name 'User' + + + + New-PodeOAIntProperty -Name 'id'-Format Int64 | + New-PodeOAStringProperty -Name 'name' | + New-PodeOAObjectProperty -XmlName 'tag' | + Add-PodeOAComponentSchema -Name 'Tag' + + New-PodeOAIntProperty -Name 'id'-Format Int64 -Example 10 -Required | + New-PodeOAStringProperty -Name 'name' -Example 'doggie' -Required | + New-PodeOASchemaProperty -Name 'category' -Reference 'Category' | + New-PodeOAStringProperty -Name 'photoUrls' -Array -XmlWrapped -XmlItemName 'photoUrl' -Required | + New-PodeOASchemaProperty -Name 'tags' -Reference 'Tag' -Array -XmlWrapped | + New-PodeOAStringProperty -Name 'status' -Description 'pet status in the store' -Enum @('available', 'pending', 'sold') | + New-PodeOAObjectProperty -XmlName 'pet' | + Add-PodeOAComponentSchema -Name 'Pet' + + + + New-PodeOAIntProperty -Name 'code'-Format Int32 | + New-PodeOAStringProperty -Name 'type' | + New-PodeOAStringProperty -Name 'message' | + New-PodeOAObjectProperty -XmlName '##default' | + Add-PodeOAComponentSchema -Name 'ApiResponse' + + + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' | Add-PodeOAComponentRequestBody -Name 'Pet' -Description 'Pet object that needs to be added to the store' + + Add-PodeOAComponentRequestBody -Name 'UserArray' -Description 'List of user object' -Content ( + New-PodeOAContentMediaType -MediaType 'application/json' -Content 'User' -Array) + + + + + Add-PodeRouteGroup -Path '/api/v3' -Routes { + <# + PUT '/pet' + #> + Add-PodeRoute -PassThru -Method Put -Path '/pet' -Authentication 'merged_auth_nokey' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + switch ($contentType) { + 'application/xml' { + $pet = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $pet = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($pet -and $WebEvent.data.id) { + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $pet -SchemaReference 'Pet' + } + else { + $Validate = @{'result' = $true } + } + if ($Validate.result) { + if (Update-Pet -Pet (convertfrom-json -InputObject $pet -AsHashtable)) { + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -StatusCode 404 -Value 'Pet not found' + } + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } + } + else { + Write-PodeHtmlResponse -StatusCode 400 -Value 'Invalid ID supplied' + } + } | Set-PodeOARouteInfo -Summary 'Update an existing pet' -Description 'Update an existing pet by Id' -Tags 'pet' -OperationId 'updatePet' -PassThru | + Set-PodeOARequest -RequestBody ( + New-PodeOARequestBody -Description 'Update an existent pet in the store' -Required -Content ( + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Pet not found' -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Validation exception' + + + <# + POST '/pet' + #> + Add-PodeRoute -PassThru -Method Post -Path '/pet' -Authentication 'merged_auth_nokey' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + switch ($contentType) { + 'application/xml' { + $pet = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $pet = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $pet -SchemaReference 'Pet' + } + else { + $Validate = @{'result' = $true } + } + if ($Validate.result) { + Add-Pet -Pet (convertfrom-json -InputObject $pet -AsHashtable) + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } + } | Set-PodeOARouteInfo -Summary 'Add a new pet to the store' -Description 'Add a new pet to the store' -Tags 'pet' -OperationId 'addPet' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Description 'Create a new pet in the store' -Required -Content ( + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' ) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid input' + + + <# + GET '/pet/findByStatus' + #> + Add-PodeRoute -PassThru -Method get -Path '/pet/findByStatus' -Authentication 'merged_auth_nokey' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $status = $WebEvent.Query['status'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($status) { + $pets = Find-PetByStatus -Status $status + if ($null -eq $pets) { + $pets = @() + } + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $pets -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $pets -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'Invalid status value' -StatusCode 400 + } + + } | Set-PodeOARouteInfo -Summary 'Finds Pets by status' -Description 'Multiple status values can be provided with comma separated strings' -Tags 'pet' -OperationId 'findPetsByStatus' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( + New-PodeOAStringProperty -Name 'status' -Description 'Status values that need to be considered for filter' -Default 'available' -Enum @('available', 'pending', 'sold') | + ConvertTo-PodeOAParameter -In Query -Explode ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' -Array) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid status value' -PassThru | + Add-PodeOAResponse -StatusCode 415 + + <# + GET '/pet/findByTags' + #> + Add-PodeRoute -PassThru -Method get -Path '/pet/findByTags' -Authentication 'merged_auth_nokey' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $tags = $WebEvent.Query['tags'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($tags) { + $pets = Find-PetByTags -Tags $tags + if ($null -eq $pets) { + $pets = @() + } + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $pets -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $pets -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'Invalid tag value' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Finds Pets by tags' -Description 'Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.' -Tags 'pet' -OperationId 'findPetsByTags' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( + New-PodeOAStringProperty -Name 'tags' -Description 'Tags to filter by' -Array | + ConvertTo-PodeOAParameter -In Query -Explode ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet' -Array) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid tag value' -PassThru | + Add-PodeOAResponse -StatusCode 415 + + + + <# + GET '/pet/{petId}' + #> + Add-PodeRoute -PassThru -Method Get -Path '/pet/:petId' -Authentication 'merged_auth' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $petId = $WebEvent.Parameters['petId'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($petId) { + $pet = Get-Pet -Id $petId + if ($pet) { + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $pet -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $pet -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'Pet not found' -StatusCode 404 + } + } + else { + Write-PodeJsonResponse -Value 'Invalid ID supplied' -StatusCode 400 + } + + } | Set-PodeOARouteInfo -Summary 'Find pet by ID' -Description 'Returns a single pet.' -Tags 'pet' -OperationId 'getPetById' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( + New-PodeOAIntProperty -Name 'petId' -Description 'ID of pet to return' -Format Int64 | + ConvertTo-PodeOAParameter -In Path -Required ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Pet') -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Pet not found' -PassThru | + Add-PodeOAResponse -StatusCode 415 + + + <# + POST '/pet/{petId}' + #> + + Add-PodeRoute -PassThru -Method post -Path '/pet/:petId' -Authentication 'petstore_auth' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $petId = $WebEvent.Parameters['petId'] + $name = $WebEvent.Query['name'] + $status = $WebEvent.Query['status'] + + if ($petId -and (Test-Pet -Id $petId)) { + if (Update-Pet -Id $petId -Name $name -Status $status) { + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value 'Invalid Input' + } + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value 'Invalid Input' + } + } | Set-PodeOARouteInfo -Summary 'Updates pet with ID' -Description 'Updates a pet in the store with form data' -Tags 'pet' -OperationId 'updatePetWithForm' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( New-PodeOAIntProperty -Name 'petId' -Description 'ID of pet that needs to be updated' -Format Int64 | + ConvertTo-PodeOAParameter -In Path -Required ), + ( New-PodeOAStringProperty -Name 'name' -Description 'Name of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) , + ( New-PodeOAStringProperty -Name 'status' -Description 'Status of pet that needs to be updated' | ConvertTo-PodeOAParameter -In Query ) | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + <# + DELETE '/pet/{petId}' + #> + Add-PodeRoute -PassThru -Method Delete -Path '/pet/:petId' -Authentication 'merged_auth_All' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $petId = $WebEvent.Parameters['petId'] + if ($petId -and (Test-Pet -Id $petId)) { + Remove-Pet -Id $petId + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -Value 'Invalid pet value' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Deletes pet by ID' -Description 'Deletes a pet.' -Tags 'pet' -OperationId 'deletePet' -PassThru | + Set-PodeOARequest -PassThru -Parameters ( + New-PodeOAIntProperty -Name 'petId' -Description 'ID of pet that needs to be updated' -Format Int64 | + ConvertTo-PodeOAParameter -In Path -Required ) | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid pet value' + + + + #TO DO + <# + POST '/pet/{petId}/uploadImage' + #> + Add-PodeRoute -PassThru -Method post -Path '/pet/:petId/uploadImage' -Authentication 'petstore_auth' -Scope 'write:pets', 'read:pets' -ScriptBlock { + $petId = $WebEvent.Parameters['petId'] + $additionalMetadata = $WebEvent.Query['additionalMetadata'] + if ($petId -and (Test-Pet -Id $petId)) { + $pet = Get-Pet -Id $petId + $image = "$petId-$(New-Guid).$additionalMetadata" + $outputFilePath = Join-Path -Path $using:PetImagesPath -AdditionalChildPath $image + [System.IO.File]::WriteAllBytes($outputFilePath, $WebEvent.data) + $url = "$((Get-PodeConfig).Protocol)://$((Get-PodeConfig).Address):$((Get-PodeConfig).RestFulPort)/images/$image" + $pet.photoUrls.add($url) + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -Value 'Invalid pet value' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Uploads an image' -Tags 'pet' -OperationId 'uploadFile' -PassThru | + Set-PodeOARequest -Parameters @( + ( New-PodeOAIntProperty -Name 'petId' -Format Int64 -Description 'ID of pet to update' -Required | ConvertTo-PodeOAParameter -In Path ), + ( New-PodeOAStringProperty -Name 'additionalMetadata' -Description 'Additional Metadata' | ConvertTo-PodeOAParameter -In Query ) + ) -RequestBody ( + New-PodeOARequestBody -Content ( New-PodeOAContentMediaType -MediaType 'application/octet-stream' -Upload ) + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content @{'application/json' = 'ApiResponse' } + + + + <# + GET '/store/inventory' + #> + Add-PodeRoute -PassThru -Method Get -Path '/store/inventory' -Authentication 'api_key' -ScriptBlock { + $result = Get-CountByStatus + Write-PodeJsonResponse -Value $result -StatusCode 200 + + } | Set-PodeOARouteInfo -Summary 'Returns pet inventories by status' -Description 'Returns a map of status codes to quantities' -Tags 'store' -OperationId 'getInventory' -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content @{ 'application/json' = New-PodeOAObjectProperty -AdditionalProperties (New-PodeOAIntProperty -Format Int32 ) } + + + <# + POST '/store/order' + #> + Add-PodeRoute -PassThru -Method post -Path '/store/order' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + switch ($contentType) { + 'application/xml' { + $order = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $order = ConvertTo-Json $WebEvent.data } + 'application/x-www-form-urlencoded' { $order = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $order -SchemaReference 'Order' + } + else { + #no test schema support for XML + $Validate = @{'result' = $true } + } + if ($Validate.result) { + Add-Order -Order (convertfrom-json -InputObject $order -AsHashtable) + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } + } | Set-PodeOARouteInfo -Summary 'Place an order for a pet' -Description 'Place a new order in the store' -Tags 'store' -OperationId 'placeOrder' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'Order' )) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (@{ 'application/json' = 'Order' }) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' + + <# + GET '/store/order/{orderId}' + #> + Add-PodeRoute -PassThru -Method Get -Path '/store/order/:orderId' -ScriptBlock { + $orderId = $WebEvent.Parameters['orderId'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($orderId) { + $order = Get-Order -Id $orderId + if ($order) { + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $order -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $order -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'Order not found' -StatusCode 404 + } + } + else { + Write-PodeHtmlResponse -Value 'No orderId provided. Try again?' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Find purchase order by ID' -Description 'For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions.' -Tags 'store' -OperationId 'getOrderById' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAIntProperty -Name 'orderId' -Format Int64 -Description 'ID of order that needs to be fetched' -Required | ConvertTo-PodeOAParameter -In Path ) + ) | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'Order' ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Order not found' + + <# + DELETE '/store/order/{orderId}' + #> + Add-PodeRoute -PassThru -Method Delete -Path '/store/order/:orderId' -ScriptBlock { + $orderId = $WebEvent.Parameters['orderId'] + if ($orderId ) { + if ( Test-Order -Id $orderId) { + Remove-Order -Id $orderId + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -Value 'Order not found' -StatusCode 404 + } + } + else { + Write-PodeJsonReWrite-PodeHtmlResponsesponse -Value 'Invalid ID supplied' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Delete purchase order by ID' -Description 'For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors.' -Tags 'store' -OperationId 'deleteOrder' -PassThru | + Set-PodeOARequest -PassThru -Parameters @( + ( New-PodeOAIntProperty -Name 'orderId' -Format Int64 -Description ' ID of the order that needs to be deleted' -Required | ConvertTo-PodeOAParameter -In Path ) + ) | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid ID supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'Order not found' + + + + <# + POST '/user' + #> + + Add-PodeRoute -PassThru -Method Post -Path '/user' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + $responseMediaType = Get-PodeHeader -Name 'Accept' + switch ($contentType) { + 'application/xml' { + $user = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $user = ConvertTo-Json $WebEvent.data } + 'application/x-www-form-urlencoded' { $user = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $user -SchemaReference 'User' + } + else { + #no test schema support for XML + $Validate = @{'result' = $true } + } + if ($Validate.result) { + $newUser = Add-user -User (convertfrom-json -InputObject $user -AsHashtable) + Save-PodeState -Path $using:PetDataJson + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $newUser -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $newUser -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } + } | Set-PodeOARouteInfo -Summary 'Create user.' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'createUser' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' )) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' -PassThru | + Add-PodeOAResponse -Default -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'User' ) + + + <# + POST '/user/createWithList' + #> + Add-PodeRoute -PassThru -Method post -Path '/user/createWithList' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + $responseMediaType = Get-PodeHeader -Name 'Accept' + $newUsers = @() + foreach ($user in $WebEvent.data) { + switch ($contentType) { + 'application/json' { $userJson = ConvertTo-Json $user } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $userJson -SchemaReference 'User' + } + else { + #no test schema support for XML + $Validate = @{'result' = $true } + } + if ($Validate.result) { + $newUsers += $user + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + return + } + } + $createdUsers = @() + foreach ($u in $newUsers) { + $createdUsers += Add-User -User $u + } + Save-PodeState -Path $using:PetDataJson + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $createdUsers -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $createdUsers -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } | Set-PodeOARouteInfo -Summary 'Creates list of users with given input array.' -Description 'Creates list of users with given input array.' -Tags 'user' -OperationId 'createUsersWithListInput' -PassThru | + Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Content (New-PodeOAContentMediaType -MediaType 'application/json' -Content 'User' -Array)) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'User' -Array ) -PassThru | + Add-PodeOAResponse -Default -Description 'successful operation' + + + <# + GET '/user/login' + #> + Add-PodeRoute -PassThru -Method Get -Path '/user/login' -ScriptBlock { + $username = $WebEvent.Query['username'] + $password = $WebEvent.Query['password'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($username) { + $user = Get-User -Username $username + if ($user -and $user['password'] -eq $password) { + Set-PodeHeader -Name 'X-Expires-After' -Value ((Get-Date).AddHours(1).ToString('yyyy-MM-ddTHH:mm:ssK')) + Set-PodeHeader -Name 'X-Rate-Limit' -Value '5000' + $result = @{'api_key' = 'test-key' } + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $result -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $result -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'Invalid username/password supplied' -StatusCode 400 + } + } + else { + Write-PodeHtmlResponse -Value 'Invalid username/password supplied' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Logs user into the system.' -Tags 'user' -OperationId 'loginUser' -PassThru | + Set-PodeOARequest -Parameters ( New-PodeOAStringProperty -Name 'username' -Description 'The user name for login' | ConvertTo-PodeOAParameter -In Query ), + ( New-PodeOAStringProperty -Name 'password' -Description 'The password for login in clear text' -Format Password | ConvertTo-PodeOAParameter -In Query ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Description 'Successful operation' -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'string' ) ` + -Headers (New-PodeOAIntProperty -Name 'X-Rate-Limit' -Description 'calls per hour allowed by the user' -Format Int32), + (New-PodeOAStringProperty -Name 'X-Expires-After' -Description 'date in UTC when token expires' -Format Date-Time) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username/password supplied' + + <# + GET '/user/logout' + #> + Add-PodeRoute -PassThru -Method Get -Path '/user/logout' -ScriptBlock { + Write-PodeJsonResponse -Value 'Successful operation' -StatusCode 200 + } | Set-PodeOARouteInfo -Summary 'Logs out current logged in user session.' -Tags 'user' -OperationId 'logoutUser' -PassThru | + Add-PodeOAResponse -Default -Description 'Successful operation' + + + <# + GET '/user/{username}' + #> + Add-PodeRoute -PassThru -Method Get -Path '/user/:username' -ScriptBlock { + $username = $WebEvent.Parameters['username'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if ($username) { + $user = Get-User -Username $username + if ($user) { + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $user -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $user -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -Value 'User not found' -StatusCode 404 + } + } + else { + Write-PodeHtmlResponse -Value 'Invalid username supplied' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Get user by user name' -Tags 'user' -OperationId 'getUserByName' -PassThru | + Set-PodeOARequest -Parameters ( New-PodeOAStringProperty -Name 'username' -Description 'The name that needs to be fetched. Use user1 for testing.' -Required | ConvertTo-PodeOAParameter -In Path ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Content (New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml' -Content 'User' ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' + + <# + PUT '/user/{username}' + #> + Add-PodeRoute -PassThru -Method Put -Path '/user/:username' -ScriptBlock { + $contentType = Get-PodeHeader -Name 'Content-Type' + $username = $WebEvent.Parameters['username'] + $responseMediaType = Get-PodeHeader -Name 'Accept' + if (Test-User -Username $username) { + switch ($contentType) { + 'application/xml' { + $user = ConvertFrom-PodeXml -node $WebEvent.data | ConvertTo-Json + } + 'application/json' { $user = ConvertTo-Json $WebEvent.data } + 'application/x-www-form-urlencoded' { $user = ConvertTo-Json $WebEvent.data } + default { + Write-PodeHtmlResponse -StatusCode 415 + return + } + } + if ($contentType -eq 'application/json') { + $Validate = Test-PodeOAJsonSchemaCompliance -Json $user -SchemaReference 'User' + } + else { + #no test schema support for XML + $Validate = @{'result' = $true } + } + if ($Validate.result) { + $newUser = Add-user -User (convertfrom-json -InputObject $user -AsHashtable) + Save-PodeState -Path $using:PetDataJson + switch ($responseMediaType) { + 'application/xml' { Write-PodeXmlResponse -Value $newUser -StatusCode 200 } + 'application/json' { Write-PodeJsonResponse -Value $newUser -StatusCode 200 } + default { Write-PodeHtmlResponse -StatusCode 415 } + } + } + else { + Write-PodeHtmlResponse -StatusCode 405 -Value ($Validate.message -join ', ') + } + } + else { + Write-PodeHtmlResponse -StatusCode 404 -Value 'User not found' + } + } | Set-PodeOARouteInfo -Summary 'Update user' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'updateUser' -PassThru | + Set-PodeOARequest -Parameters ( New-PodeOAStringProperty -Name 'username' -Description ' name that need to be updated.' -Required | ConvertTo-PodeOAParameter -In Path ) ` + -RequestBody ( New-PodeOARequestBody -Required -Description 'Update an existent user in the store' -Content ( + New-PodeOAContentMediaType -MediaType 'application/json', 'application/xml', 'application/x-www-form-urlencoded' -Content 'User' + )) -PassThru | + Add-PodeOAResponse -StatusCode 405 -Description 'Invalid Input' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' -PassThru | + Add-PodeOAResponse -Default -Description 'successful operation' + + <# + DELETE '/user/{username}' + #> + Add-PodeRoute -PassThru -Method Delete -Path '/user/:username' -ScriptBlock { + $username = $WebEvent.Parameters['username'] + if ($username ) { + if ( Test-User -Username $username) { + Remove-User -Username $orderId + Save-PodeState -Path $using:PetDataJson + } + else { + Write-PodeHtmlResponse -Value 'User not found' -StatusCode 404 + } + } + else { + Write-PodeJsonReWrite-PodeHtmlResponsesponse -Value 'Invalid username supplied' -StatusCode 400 + } + } | Set-PodeOARouteInfo -Summary 'Delete user' -Description 'This can only be done by the logged in user.' -Tags 'user' -OperationId 'deleteUser' -PassThru | + Set-PodeOARequest -Parameters ( New-PodeOAStringProperty -Name 'username' -Description 'The name that needs to be deleted.' -Required | ConvertTo-PodeOAParameter -In Path ) -PassThru | + Add-PodeOAResponse -StatusCode 400 -Description 'Invalid username supplied' -PassThru | + Add-PodeOAResponse -StatusCode 404 -Description 'User not found' + } + } + $yaml = get-PodeOADefinition -Format Yaml -DefinitionTag 'v3.0.3' + + $yaml_31 = get-PodeOADefinition -Format Yaml -DefinitionTag 'v3.1' + + + + #$r= ConvertFrom-PodeXml -node $xmlDoc + + #$pet=$r |convertto-json + + #$Validate = Test-PodeOAJsonSchemaCompliance -Json $pet -SchemaReference 'Pet' + # $json= PodeOADefinition -Format Json +} \ No newline at end of file diff --git a/examples/PetStore/UserData.psm1 b/examples/PetStore/UserData.psm1 new file mode 100644 index 000000000..6cb8be1ec --- /dev/null +++ b/examples/PetStore/UserData.psm1 @@ -0,0 +1,130 @@ + +function Initialize-Users { + param ( + [switch] + $Reset + ) + New-PodeLockable -Name 'UserLock' + if ($Reset.IsPresent) { + Lock-PodeObject -Name 'UserLock' -ScriptBlock { + Set-PodeState -Scope 'Users' -Name 'users' -Value @{} | Out-Null + Add-User -Id 1 -Username 'user1' -FirstName 'first name 1' -LastName 'last name 1' -Email 'email1@test.com' -Phone '123-456-7890' -UserStatus 1 + + Add-User -Id 2 -Username 'user2' -FirstName 'first name 2' -LastName 'last name 2' -Email 'email2@test.com' -Phone '123-456-7890' -UserStatus 2 + + Add-User -Id 3 -Username 'user3' -FirstName 'first name 3' -LastName 'last name 3' -Email 'email3@test.com' -Phone '123-456-7890' -UserStatus 3 + + Add-User -Id 4 -Username 'user4' -FirstName 'first name 4' -LastName 'last name 4' -Email 'email4@test.com' -Phone '123-456-7890' -UserStatus 1 + + Add-User -Id 5 -Username 'user5' -FirstName 'first name 5' -LastName 'last name 5' -Email 'email5@test.com' -Phone '123-456-7890' -UserStatus 2 + + Add-User -Id 6 -Username 'user6' -FirstName 'first name 6' -LastName 'last name 6' -Email 'email6@test.com' -Phone '123-456-7890' -UserStatus 3 + + Add-User -Id 7 -Username 'user7' -FirstName 'first name 7' -LastName 'last name 7' -Email 'email7@test.com' -Phone '123-456-7890' -UserStatus 1 + + Add-User -Id 8 -Username 'user8' -FirstName 'first name 8' -LastName 'last name 8' -Email 'email8@test.com' -Phone '123-456-7890' -UserStatus 2 + + Add-User -Id 9 -Username 'user9' -FirstName 'first name 9' -LastName 'last name 9' -Email 'email9@test.com' -Phone '123-456-7890' -UserStatus 3 + + Add-User -Id 10 -Username 'user10' -FirstName 'first name 10' -LastName 'last name 10' -Email 'email10@test.com' -Phone '123-456-7890' -UserStatus 1 + + Add-User -Id 11 -Username 'user?10' -FirstName 'first name ?10' -LastName 'last name ?10' -Email 'email101@test.com' -Phone '123-456-7890' -UserStatus 1 + } + } +} +function Add-User { + + [CmdletBinding(DefaultParameterSetName = 'Items')] + param ( + [Parameter(Mandatory , ParameterSetName = 'Items')] + [long] + $Id, + [Parameter(Mandatory , ParameterSetName = 'Items')] + [String] + $Username, + [Parameter(Mandatory , ParameterSetName = 'Items')] + [String] + $FirstName, + [Parameter(Mandatory , ParameterSetName = 'Items')] + [String] + $LastName, + [Parameter(Mandatory , ParameterSetName = 'Items')] + [String] + $Email, + [Parameter(Mandatory , ParameterSetName = 'Items')] + [String] + $Phone, + [Parameter(Mandatory , ParameterSetName = 'Items')] + [int] + $UserStatus, + [Parameter(Mandatory, ParameterSetName = 'Object')] + [hashtable] + $User + ) + return Lock-PodeObject -Name 'UserLock' -Return -ScriptBlock { + $users = Get-PodeState -Name 'users' + switch ($PSCmdlet.ParameterSetName) { + 'Items' { + $users[$Username] = @{ + id = $Id + username = $Username + firstName = $FirstName + lastName = $LastName + email = $Email + password = 'XXXXXXXXXXX' + phone = $Phone + userStatus = $UserStatus + } + return $users[$Username] + } + 'Object' { + $users[$User.username] = $User + return $User + } + } + } +} + + +function Remove-User { + param ( + [Parameter(Mandatory )] + [String] + $Username + ) + Lock-PodeObject -Name 'UserLock' -ScriptBlock { + $users = Get-PodeState -Name 'users' + $users.Remove( $Username) + } +} + +function Get-User { + param ( + [Parameter(Mandatory )] + [String] + $Username + ) + return Lock-PodeObject -Name 'UserLock' -Return -ScriptBlock { + $users = Get-PodeState -Name 'users' + return $users[$username] + } +} + +function Test-User { + param ( + [Parameter(Mandatory )] + [String] + $Username + ) + return Lock-PodeObject -Name 'UserLock' -Return -ScriptBlock { + $users = Get-PodeState -Name 'users' + return $users.containsKey($username) + } +} + + +Export-ModuleMember -Function Initialize-Users +Export-ModuleMember -Function Get-User +Export-ModuleMember -Function Add-User +Export-ModuleMember -Function Test-User +Export-ModuleMember -Function Remove-User \ No newline at end of file diff --git a/examples/PetStore/data/PetData.json b/examples/PetStore/data/PetData.json new file mode 100644 index 000000000..dfee685c6 --- /dev/null +++ b/examples/PetStore/data/PetData.json @@ -0,0 +1,363 @@ +{ + "categories": { + "Value": { + "Cats": 2, + "Dogs": 1, + "Rabbits": 3, + "Lions": 4 + }, + "Scope": [ + "Categories" + ] + }, + "orders": { + "Value": { + "3": { + "status": "delivered", + "complete": true, + "shipdate": "2024-02-12T17:08:06.6050923-08:00", + "petId": 1, + "id": 3, + "quantity": 50 + }, + "1": { + "status": "placed", + "complete": true, + "shipdate": "2024-02-12T17:08:06.6050923-08:00", + "petId": 1, + "id": 1, + "quantity": 100 + }, + "4": { + "status": "placed", + "complete": false, + "shipdate": "2024-02-12T17:08:06.6050923-08:00", + "petId": 1, + "id": 4, + "quantity": 20 + }, + "2": { + "status": "approved", + "complete": true, + "shipdate": "2024-02-12T17:08:06.6050923-08:00", + "petId": 1, + "id": 2, + "quantity": 50 + } + }, + "Scope": [ + "Orders" + ] + }, + "pets": { + "Value": { + "5": { + "status": "sold", + "tags": [ + "tag2", + "tag3" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 1, + "name": "Dogs" + }, + "name": "Dog 2", + "id": 5 + }, + "11": { + "status": "pending", + "tags": [ + "tag3", + "tag4" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 3, + "name": "Rabbits" + }, + "name": "Rabbit 2", + "id": 11 + }, + "8": { + "status": "available", + "tags": [ + "tag2", + "tag3" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 4, + "name": "Lions" + }, + "name": "Lion 2", + "id": 8 + }, + "7": { + "status": "available", + "tags": [ + "tag1", + "tag2" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 4, + "name": "Lions" + }, + "name": "Lion 1", + "id": 7 + }, + "4": { + "status": "available", + "tags": [ + "tag1", + "tag2" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 1, + "name": "Dogs" + }, + "name": "Dog 1", + "id": 4 + }, + "1": { + "status": "available", + "tags": [ + "tag1", + "tag2" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 2, + "name": "Cats" + }, + "name": "Cat 1", + "id": 1 + }, + "2": { + "status": "available", + "tags": [ + "tag2", + "tag3" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 2, + "name": "Cats" + }, + "name": "Cat 2", + "id": 2 + }, + "10": { + "status": "available", + "tags": [ + "tag2", + "tag3" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 3, + "name": "Rabbits" + }, + "name": "Rabbit 1", + "id": 10 + }, + "6": { + "status": "pending", + "tags": [ + "tag3", + "tag4" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 1, + "name": "Dogs" + }, + "name": "Dog 2", + "id": 6 + }, + "3": { + "status": "pending", + "tags": [ + "tag3", + "tag4" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 2, + "name": "Cats" + }, + "name": "Cat 2", + "id": 3 + }, + "9": { + "status": "available", + "tags": [ + "tag3", + "tag4" + ], + "photoUrls": [ + "url1", + "url2" + ], + "categoryName": { + "id": 4, + "name": "Lions" + }, + "name": "Lion 2", + "id": 9 + } + }, + "Scope": [ + "Pets" + ] + }, + "users": { + "Value": { + "user5": { + "userStatus": 2, + "firstName": "first name 5", + "email": "email5@test.com", + "lastName": "last name 5", + "phone": "123-456-7890", + "username": "user5", + "id": 5, + "password": "XXXXXXXXXXX" + }, + "user2": { + "userStatus": 2, + "firstName": "first name 2", + "email": "email2@test.com", + "lastName": "last name 2", + "phone": "123-456-7890", + "username": "user2", + "id": 2, + "password": "XXXXXXXXXXX" + }, + "user?10": { + "userStatus": 1, + "firstName": "first name ?10", + "email": "email101@test.com", + "lastName": "last name ?10", + "phone": "123-456-7890", + "username": "user?10", + "id": 11, + "password": "XXXXXXXXXXX" + }, + "user10": { + "userStatus": 1, + "firstName": "first name 10", + "email": "email10@test.com", + "lastName": "last name 10", + "phone": "123-456-7890", + "username": "user10", + "id": 10, + "password": "XXXXXXXXXXX" + }, + "user7": { + "userStatus": 1, + "firstName": "first name 7", + "email": "email7@test.com", + "lastName": "last name 7", + "phone": "123-456-7890", + "username": "user7", + "id": 7, + "password": "XXXXXXXXXXX" + }, + "user1": { + "userStatus": 1, + "firstName": "first name 1", + "email": "email1@test.com", + "lastName": "last name 1", + "phone": "123-456-7890", + "username": "user1", + "id": 1, + "password": "XXXXXXXXXXX" + }, + "user8": { + "userStatus": 2, + "firstName": "first name 8", + "email": "email8@test.com", + "lastName": "last name 8", + "phone": "123-456-7890", + "username": "user8", + "id": 8, + "password": "XXXXXXXXXXX" + }, + "user9": { + "userStatus": 3, + "firstName": "first name 9", + "email": "email9@test.com", + "lastName": "last name 9", + "phone": "123-456-7890", + "username": "user9", + "id": 9, + "password": "XXXXXXXXXXX" + }, + "user3": { + "userStatus": 3, + "firstName": "first name 3", + "email": "email3@test.com", + "lastName": "last name 3", + "phone": "123-456-7890", + "username": "user3", + "id": 3, + "password": "XXXXXXXXXXX" + }, + "user4": { + "userStatus": 1, + "firstName": "first name 4", + "email": "email4@test.com", + "lastName": "last name 4", + "phone": "123-456-7890", + "username": "user4", + "id": 4, + "password": "XXXXXXXXXXX" + }, + "user6": { + "userStatus": 3, + "firstName": "first name 6", + "email": "email6@test.com", + "lastName": "last name 6", + "phone": "123-456-7890", + "username": "user6", + "id": 6, + "password": "XXXXXXXXXXX" + } + }, + "Scope": [ + "Users" + ] + } +} diff --git a/examples/PetStore/server.psd1 b/examples/PetStore/server.psd1 new file mode 100644 index 000000000..844eed9d3 --- /dev/null +++ b/examples/PetStore/server.psd1 @@ -0,0 +1,18 @@ +@{ + RestFulPort = 8081 + Protocol = 'Http' + Address = 'localhost' + Certificate = 'Certificate.pem' + CertificateKey = 'CertificateKey.key' + CertificatePassword = 'password@01' + SessionsTtlMinutes = 360 + Server = @{ + Timeout = 60 + BodySize = 100MB + } + Web=@{ + OpenApi=@{ + DefaultDefinitionTag = 'v3.0.3' + } + } +} \ No newline at end of file diff --git a/examples/SwaggerEditor/swagger-editor.ps1 b/examples/SwaggerEditor/swagger-editor.ps1 new file mode 100644 index 000000000..1a5d17d0b --- /dev/null +++ b/examples/SwaggerEditor/swagger-editor.ps1 @@ -0,0 +1,29 @@ +param( + [int] + $Port = 8080 +) + +$path = Split-Path -Parent -Path (Split-Path -Parent -Path (Split-Path -Parent -Path $MyInvocation.MyCommand.Path)) +Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop + +# or just: +# Import-Module Pode + +# create a server, and start listening on port 8085 +Start-PodeServer -Threads 2 { + + # listen on localhost:8085 + Add-PodeEndpoint -Address localhost -Port $port -Protocol Http + New-PodeLoggingMethod -Terminal | Enable-PodeRequestLogging + New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging + + # set view engine to pode renderer + Set-PodeViewEngine -Type HTML + + # STATIC asset folder route + Add-PodeStaticRoute -Path '/editor/swagger-editor-dist' -Source "$($path)/src/Misc/swagger-editor-dist" -FileBrowser + Add-PodeStaticRoute -Path '/editor' -Source './www' -Defaults @('index.html') -FileBrowser + Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + Move-PodeResponseUrl -Url '/editor/index.html' + } +} \ No newline at end of file diff --git a/examples/SwaggerEditor/www/index.html b/examples/SwaggerEditor/www/index.html new file mode 100644 index 000000000..092a23bf9 --- /dev/null +++ b/examples/SwaggerEditor/www/index.html @@ -0,0 +1,112 @@ + + + + + + + Swagger Editor + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/examples/caching.ps1 b/examples/caching.ps1 new file mode 100644 index 000000000..36c8a6172 --- /dev/null +++ b/examples/caching.ps1 @@ -0,0 +1,64 @@ +$path = Split-Path -Parent -Path (Split-Path -Parent -Path $MyInvocation.MyCommand.Path) +Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop + +# or just: +# Import-Module Pode + +# create a server, and start listening on port 8085 +Start-PodeServer -Threads 3 { + # listen on localhost:8085 + Add-PodeEndpoint -Address * -Port 8090 -Protocol Http + + # log errors + New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging + + Set-PodeCacheDefaultTtl -Value 60 + + $params = @{ + Set = { + param($key, $value, $ttl) + $null = redis-cli -h localhost -p 6379 SET $key "$($value)" EX $ttl + } + Get = { + param($key, $metadata) + $result = redis-cli -h localhost -p 6379 GET $key + $result = [System.Management.Automation.Internal.StringDecorated]::new($result).ToString('PlainText') + if ([string]::IsNullOrEmpty($result) -or ($result -ieq '(nil)')) { + return $null + } + return $result + } + Test = { + param($key) + $result = redis-cli -h localhost -p 6379 EXISTS $key + return [System.Management.Automation.Internal.StringDecorated]::new($result).ToString('PlainText') + } + Remove = { + param($key) + $null = redis-cli -h localhost -p 6379 EXPIRE $key -1 + } + Clear = {} + } + Add-PodeCacheStorage -Name 'Redis' @params + + # set default value for cache + $cache:cpu = (Get-Random -Minimum 1 -Maximum 1000) + + # get cpu, and cache it + Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + if ((Test-PodeCache -Key 'cpu') -and ($null -ne $cache:cpu)) { + Write-PodeJsonResponse -Value @{ CPU = $cache:cpu } + # Write-PodeHost 'here - cached' + return + } + + # $cache:cpu = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue + Start-Sleep -Milliseconds 500 + $cache:cpu = (Get-Random -Minimum 1 -Maximum 1000) + Write-PodeJsonResponse -Value @{ CPU = $cache:cpu } + # $cpu = (Get-Random -Minimum 1 -Maximum 1000) + # Write-PodeJsonResponse -Value @{ CPU = $cpu } + # Write-PodeHost 'here - raw' + } + +} \ No newline at end of file diff --git a/examples/create-routes.ps1 b/examples/create-routes.ps1 new file mode 100644 index 000000000..8ae84cd7c --- /dev/null +++ b/examples/create-routes.ps1 @@ -0,0 +1,34 @@ + +#crete routes using different approaches +$ScriptPath=Split-Path -Parent -Path $MyInvocation.MyCommand.Path +$path = Split-Path -Parent -Path $ScriptPath +if (Test-Path -Path "$($path)/src/Pode.psm1" -PathType Leaf) { + Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop +} else { + Import-Module -Name 'Pode' +} + + +Start-PodeServer -Threads 1 -ScriptBlock { + Add-PodeEndpoint -Address localhost -Port 8081 -Protocol Http + New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging + + Add-PodeRoute -PassThru -Method Get -Path '/routeCreateScriptBlock/:id' -ScriptBlock ([ScriptBlock]::Create( (Get-Content -Path "$ScriptPath\scripts\routeScript.ps1" -Raw))) | + Set-PodeOARouteInfo -Summary 'Test' -OperationId 'routeCreateScriptBlock' -PassThru | + Set-PodeOARequest -Parameters @((New-PodeOAStringProperty -Name 'id' | ConvertTo-PodeOAParameter -In Path -Required) ) + + + Add-PodeRoute -PassThru -Method Post -Path '/routeFilePath/:id' -FilePath '.\scripts\routeScript.ps1' | Set-PodeOARouteInfo -Summary 'Test' -OperationId 'routeFilePath' -PassThru | + Set-PodeOARequest -Parameters @((New-PodeOAStringProperty -Name 'id' | ConvertTo-PodeOAParameter -In Path -Required) ) + + + Add-PodeRoute -PassThru -Method Get -Path '/routeScriptBlock/:id' -ScriptBlock { $Id = $WebEvent.Parameters['id'] ; Write-PodeJsonResponse -StatusCode 200 -Value @{'id' = $Id } } | + Set-PodeOARouteInfo -Summary 'Test' -OperationId 'routeScriptBlock' -PassThru | + Set-PodeOARequest -Parameters @((New-PodeOAStringProperty -Name 'id' | ConvertTo-PodeOAParameter -In Path -Required) ) + + + Add-PodeRoute -PassThru -Method Get -Path '/routeScriptSameScope/:id' -ScriptBlock { . $ScriptPath\scripts\routeScript.ps1 } | + Set-PodeOARouteInfo -Summary 'Test' -OperationId 'routeScriptSameScope' -PassThru | + Set-PodeOARequest -Parameters @((New-PodeOAStringProperty -Name 'id' | ConvertTo-PodeOAParameter -In Path -Required) ) + +} \ No newline at end of file diff --git a/examples/logging.ps1 b/examples/logging.ps1 index a752fad8a..65dfe4a02 100644 --- a/examples/logging.ps1 +++ b/examples/logging.ps1 @@ -1,15 +1,19 @@ $path = Split-Path -Parent -Path (Split-Path -Parent -Path $MyInvocation.MyCommand.Path) -Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop - +if (Test-Path -Path "$($path)/src/Pode.psm1" -PathType Leaf) { + Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop +} +else { + Import-Module -Name 'Pode' +} # or just: # Import-Module Pode -$LOGGING_TYPE = 'Terminal' # Terminal, File, Custom +$LOGGING_TYPE = 'terminal' # Terminal, File, Custom # create a server, and start listening on port 8085 Start-PodeServer { - Add-PodeEndpoint -Address * -Port 8085 -Protocol Http + Add-PodeEndpoint -Address localhost -Port 8085 -Protocol Http Set-PodeViewEngine -Type Pode switch ($LOGGING_TYPE.ToLowerInvariant()) { diff --git a/examples/public/scripts/sse.js b/examples/public/scripts/sse.js new file mode 100644 index 000000000..b63ef935b --- /dev/null +++ b/examples/public/scripts/sse.js @@ -0,0 +1,45 @@ +$(document).ready(() => { + $('button#local').off('click').on('click', (e) => { + const sse = new EventSource("/data"); + + sse.addEventListener("Action", (e) => { + $('#messages').append(`

Action: ${e.data}

`); + }); + + sse.addEventListener("BoldOne", (e) => { + $('#messages').append(`

BoldOne: ${e.data}

`); + }); + + sse.addEventListener("pode.close", (e) => { + console.log('CLOSE'); + sse.close(); + }); + + sse.addEventListener("pode.open", (e) => { + var data = JSON.parse(e.data); + console.log(`OPEN: ${data.clientId}`); + }); + + sse.onerror = (e) => { + console.log('ERROR!'); + } + }); + + $('button#global').off('click').on('click', (e) => { + const sse2 = new EventSource("/sse"); + + sse2.onmessage = (e) => { + $('#messages').append(`

${e.data}

`); + }; + + sse2.onerror = (e) => { + console.log('ERROR2!'); + sse.close(); + }; + + sse2.addEventListener("pode.close", (e) => { + console.log('CLOSE'); + sse2.close(); + }); + }); +}) \ No newline at end of file diff --git a/examples/rest-api.ps1 b/examples/rest-api.ps1 index 1f0793544..0c16c2c53 100644 --- a/examples/rest-api.ps1 +++ b/examples/rest-api.ps1 @@ -7,7 +7,7 @@ Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop # create a server, and start listening on port 8086 Start-PodeServer { - Add-PodeEndpoint -Address * -Port 8086 -Protocol Http + Add-PodeEndpoint -Address 'localhost' -Port 8086 -Protocol Http -DualMode # request logging New-PodeLoggingMethod -Terminal -Batch 10 -BatchTimeout 10 | Enable-PodeRequestLogging diff --git a/examples/scripts/routeScript.ps1 b/examples/scripts/routeScript.ps1 new file mode 100644 index 000000000..6ced6153f --- /dev/null +++ b/examples/scripts/routeScript.ps1 @@ -0,0 +1,4 @@ +{ + $Id = $WebEvent.Parameters['id'] + Write-PodeJsonResponse -StatusCode 200 -Value @{'id' = $Id } +} \ No newline at end of file diff --git a/examples/server.psd1 b/examples/server.psd1 index 31672c701..99191fb0f 100644 --- a/examples/server.psd1 +++ b/examples/server.psd1 @@ -1,23 +1,23 @@ @{ - Web = @{ - Static = @{ + Web = @{ + Static = @{ Defaults = @( 'index.html', 'default.html' ) - Cache = @{ - Enable = $true - MaxAge = 15 + Cache = @{ + Enable = $true + MaxAge = 15 Include = @( '*.jpg' ) } } - ErrorPages = @{ - ShowExceptions = $true + ErrorPages = @{ + ShowExceptions = $true StrictContentTyping = $true - Default = 'application/html' - Routes = @{ + Default = 'application/html' + Routes = @{ '/john' = 'application/json' } } @@ -27,29 +27,34 @@ } Server = @{ FileMonitor = @{ - Enable = $false + Enable = $false ShowFiles = $true } - Logging = @{ + Logging = @{ Masking = @{ Patterns = @( '(?Password=)\w+', '(?AppleWebKit\/)\d+\.\d+(?( + + + SSE Home + + + + + + +

Example of using SSE

+

Messages streamed from a local SSE connection

+ + +
+ + + \ No newline at end of file diff --git a/examples/web-auth-apikey-jwt.ps1 b/examples/web-auth-apikey-jwt.ps1 index 9c39f2aa8..0b94b8dcd 100644 --- a/examples/web-auth-apikey-jwt.ps1 +++ b/examples/web-auth-apikey-jwt.ps1 @@ -27,7 +27,7 @@ Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop Start-PodeServer -Threads 2 { # listen on localhost:8085 - Add-PodeEndpoint -Address * -Port 8085 -Protocol Http + Add-PodeEndpoint -Address localhost -Port 8085 -Protocol Http New-PodeLoggingMethod -File -Name 'requests' | Enable-PodeRequestLogging New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging diff --git a/examples/web-auth-basic-access.ps1 b/examples/web-auth-basic-access.ps1 index ca6ce591f..11959566e 100644 --- a/examples/web-auth-basic-access.ps1 +++ b/examples/web-auth-basic-access.ps1 @@ -26,14 +26,8 @@ Start-PodeServer -Threads 2 { Add-PodeEndpoint -Address * -Port 8085 -Protocol Http # setup RBAC - # Add-PodeAccess -Type Role -Name 'TestRbac' - # Add-PodeAccess -Type Group -Name 'TestGbac' New-PodeAccessScheme -Type Role | Add-PodeAccess -Name 'TestRbac' New-PodeAccessScheme -Type Group | Add-PodeAccess -Name 'TestGbac' - # Add-PodeAccess -Type Custom -Name 'TestRbac' -Path 'CustomAccess' -Validator { - # param($userRoles, $customValues) - # return $userRoles.Example -iin $customValues.Example - # } Merge-PodeAccess -Name 'TestMergedAll' -Access 'TestRbac', 'TestGbac' -Valid All Merge-PodeAccess -Name 'TestMergedOne' -Access 'TestRbac', 'TestGbac' -Valid One @@ -46,12 +40,12 @@ Start-PodeServer -Threads 2 { if ($username -eq 'morty' -and $password -eq 'pickle') { return @{ User = @{ - ID ='M0R7Y302' - Name = 'Morty' - Type = 'Human' - Username = 'm.orty' - Roles = @('Developer') - Groups = @('Software', 'Admins') + ID = 'M0R7Y302' + Name = 'Morty' + Type = 'Human' + Username = 'm.orty' + Roles = @('Developer') + Groups = @('Software', 'Admins') CustomAccess = @{ Example = 'test-val-1' } } } diff --git a/examples/web-auth-basic.ps1 b/examples/web-auth-basic.ps1 index fed990bee..1ac920dd4 100644 --- a/examples/web-auth-basic.ps1 +++ b/examples/web-auth-basic.ps1 @@ -1,5 +1,10 @@ $path = Split-Path -Parent -Path (Split-Path -Parent -Path $MyInvocation.MyCommand.Path) -Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop +if (Test-Path -Path "$($path)/src/Pode.psm1" -PathType Leaf) { + Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop +} +else { + Import-Module -Name 'Pode' +} # or just: # Import-Module Pode @@ -23,7 +28,7 @@ Invoke-RestMethod -Uri http://localhost:8085/users -Method Post -Headers @{ Auth Start-PodeServer -Threads 2 { # listen on localhost:8085 - Add-PodeEndpoint -Address * -Port 8085 -Protocol Http + Add-PodeEndpoint -Address localhost -Port 8085 -Protocol Http # request logging New-PodeLoggingMethod -Terminal -Batch 10 -BatchTimeout 10 | Enable-PodeRequestLogging diff --git a/examples/web-auth-form-access.ps1 b/examples/web-auth-form-access.ps1 index a7551dd30..de372faa3 100644 --- a/examples/web-auth-form-access.ps1 +++ b/examples/web-auth-form-access.ps1 @@ -1,8 +1,10 @@ $path = Split-Path -Parent -Path (Split-Path -Parent -Path $MyInvocation.MyCommand.Path) -Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop - -# or just: -# Import-Module Pode +if (Test-Path -Path "$($path)/src/Pode.psm1" -PathType Leaf) { + Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop +} +else { + Import-Module -Name 'Pode' +} <# This examples shows how to use session persistant authentication with access. @@ -22,7 +24,7 @@ take you back to the login page. Start-PodeServer -Threads 2 { # listen on localhost:8085 - Add-PodeEndpoint -Address * -Port 8085 -Protocol Http + Add-PodeEndpoint -Address localhost -Port 8085 -Protocol Http # set the view engine Set-PodeViewEngine -Type Pode diff --git a/examples/web-auth-form.ps1 b/examples/web-auth-form.ps1 index 6dda283a2..e9c5e57f9 100644 --- a/examples/web-auth-form.ps1 +++ b/examples/web-auth-form.ps1 @@ -37,7 +37,7 @@ Start-PodeServer -Threads 2 { if ($username -eq 'morty' -and $password -eq 'pickle') { return @{ User = @{ - ID ='M0R7Y302' + ID = 'M0R7Y302' Name = 'Morty' Type = 'Human' } @@ -55,8 +55,8 @@ Start-PodeServer -Threads 2 { Write-PodeViewResponse -Path 'auth-home' -Data @{ Username = $WebEvent.Auth.User.Name - Views = $session:Views - Expiry = Get-PodeSessionExpiry + Views = $session:Views + Expiry = Get-PodeSessionExpiry } } diff --git a/examples/web-auth-merged.ps1 b/examples/web-auth-merged.ps1 index 7dd84c36a..46992c209 100644 --- a/examples/web-auth-merged.ps1 +++ b/examples/web-auth-merged.ps1 @@ -21,24 +21,25 @@ Start-PodeServer -Threads 2 { New-PodeLoggingMethod -Terminal -Batch 10 -BatchTimeout 10 | Enable-PodeRequestLogging # setup access - Add-PodeAccess -Type Role -Name 'Rbac' - Add-PodeAccess -Type Group -Name 'Gbac' + New-PodeAccessScheme -Type Role | Add-PodeAccess -Name 'Rbac' + New-PodeAccessScheme -Type Group | Add-PodeAccess -Name 'Gbac' # setup a merged access Merge-PodeAccess -Name 'MergedAccess' -Access 'Rbac', 'Gbac' -Valid All # setup apikey auth - New-PodeAuthScheme -ApiKey -Location Header | Add-PodeAuth -Name 'ApiKey' -Access 'Gbac' -Sessionless -ScriptBlock { + New-PodeAuthScheme -ApiKey -Location Header | Add-PodeAuth -Name 'ApiKey' -Sessionless -ScriptBlock { param($key) # here you'd check a real user storage, this is just for example if ($key -ieq 'test-api-key') { return @{ User = @{ - ID ='M0R7Y302' - Name = 'Morty' - Type = 'Human' - Groups = @('Software') + ID = 'M0R7Y302' + Name = 'Morty' + Type = 'Human' + Roles = @('Developer') + Groups = @('Platform') } } } @@ -47,7 +48,7 @@ Start-PodeServer -Threads 2 { } # setup basic auth (base64> username:password in header) - New-PodeAuthScheme -Basic | Add-PodeAuth -Name 'Basic' -Access 'MergedAccess' -Sessionless -ScriptBlock { + New-PodeAuthScheme -Basic | Add-PodeAuth -Name 'Basic' -Sessionless -ScriptBlock { param($username, $password) # here you'd check a real user storage, this is just for example @@ -55,11 +56,11 @@ Start-PodeServer -Threads 2 { return @{ User = @{ Username = 'morty' - ID ='M0R7Y302' - Name = 'Morty' - Type = 'Human' - Roles = @('Developer') - Groups = @('Software') + ID = 'M0R7Y302' + Name = 'Morty' + Type = 'Human' + Roles = @('Developer') + Groups = @('Software') } } } @@ -68,10 +69,26 @@ Start-PodeServer -Threads 2 { } # merge the auths together - Merge-PodeAuth -Name 'MergedAuth' -Authentication 'ApiKey', 'Basic' -Valid All + Merge-PodeAuth -Name 'MergedAuth' -Authentication 'ApiKey', 'Basic' -Valid All -ScriptBlock { + param($results) + + $apiUser = $results['ApiKey'].User + $basicUser = $results['Basic'].User + + return @{ + User = @{ + Username = $basicUser.Username + ID = $apiUser.ID + Name = $apiUser.Name + Type = $apiUser.Type + Roles = @($apiUser.Roles + $basicUser.Roles) | Sort-Object -Unique + Groups = @($apiUser.Groups + $basicUser.Groups) | Sort-Object -Unique + } + } + } # GET request to get list of users (since there's no session, authentication will always happen) - Add-PodeRoute -Method Get -Path '/users' -Authentication 'MergedAuth' -Role Developer -Group Software -ScriptBlock { + Add-PodeRoute -Method Get -Path '/users' -Authentication 'MergedAuth' -Access 'MergedAccess' -Role Developer -Group Software -ScriptBlock { Write-PodeJsonResponse -Value @{ Users = $WebEvent.Auth.User } diff --git a/examples/web-auth-oauth2-form.ps1 b/examples/web-auth-oauth2-form.ps1 index 4bf3a0b75..6cbc1baa6 100644 --- a/examples/web-auth-oauth2-form.ps1 +++ b/examples/web-auth-oauth2-form.ps1 @@ -18,7 +18,7 @@ Note: You'll need to register a new app in Azure, and note you clientId, secret, Start-PodeServer -Threads 2 { # listen on localhost:8085 - Add-PodeEndpoint -Address * -Port 8085 -Protocol Http -Default + Add-PodeEndpoint -Address localhost -Port 8085 -Protocol Http -Default New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging # set the view engine diff --git a/examples/web-pages-using.ps1 b/examples/web-pages-using.ps1 index df5babb99..f0b5467e2 100644 --- a/examples/web-pages-using.ps1 +++ b/examples/web-pages-using.ps1 @@ -7,8 +7,7 @@ Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop $outerfoo = 'outer-bar' $outer_ken = 'Hello, there' -function Write-MyOuterResponse -{ +function Write-MyOuterResponse { Write-PodeJsonResponse -Value @{ Message = 'From an outer function' } } @@ -30,8 +29,7 @@ Start-PodeServer -Threads 2 { $innerfoo = 'inner-bar' $inner_ken = 'General Kenobi' - function Write-MyInnerResponse - { + function Write-MyInnerResponse { Write-PodeJsonResponse -Value @{ Message = 'From an inner function' } } @@ -40,7 +38,7 @@ Start-PodeServer -Threads 2 { New-PodeMiddleware -ScriptBlock { "M1: $($using:outer_ken) ... $($using:inner_ken)" | Out-Default return $true - } | Add-PodeMiddleware -Name 'TestUsingMiddleware1' + } | Add-PodeMiddleware -Name 'TestUsingMiddleware1' Add-PodeMiddleware -Name 'TestUsingMiddleware2' -ScriptBlock { "M2: $($using:outer_ken) ... $($using:inner_ken)" | Out-Default diff --git a/examples/web-rest-openapi-funcs.ps1 b/examples/web-rest-openapi-funcs.ps1 index 9f6c3a411..c50b72343 100644 --- a/examples/web-rest-openapi-funcs.ps1 +++ b/examples/web-rest-openapi-funcs.ps1 @@ -5,8 +5,14 @@ Start-PodeServer { Add-PodeEndpoint -Address localhost -Port 8080 -Protocol Http Enable-PodeOpenApi -Title 'OpenAPI Example' -RouteFilter '/api/*' -RestrictRoutes - Enable-PodeOpenApiViewer -Type Swagger -DarkMode - Enable-PodeOpenApiViewer -Type ReDoc + Enable-PodeOpenApiViewer -Type Swagger -Path '/docs/swagger' + Enable-PodeOpenApiViewer -Type ReDoc -Path '/docs/redoc' + Enable-PodeOpenApiViewer -Type RapiDoc -Path '/docs/rapidoc' + Enable-PodeOpenApiViewer -Type StopLight -Path '/docs/stoplight' + Enable-PodeOpenApiViewer -Type Explorer -Path '/docs/explorer' + Enable-PodeOpenApiViewer -Type RapiPdf -Path '/docs/rapipdf' + + Enable-PodeOpenApiViewer -Bookmarks -Path '/docs' #ConvertTo-PodeRoute -Path '/api' -Commands @('Get-ChildItem', 'New-Item') ConvertTo-PodeRoute -Path '/api' -Module Pester diff --git a/examples/web-rest-openapi-shared.ps1 b/examples/web-rest-openapi-shared.ps1 index 1054014b2..3571801c0 100644 --- a/examples/web-rest-openapi-shared.ps1 +++ b/examples/web-rest-openapi-shared.ps1 @@ -1,5 +1,6 @@ $path = Split-Path -Parent -Path (Split-Path -Parent -Path $MyInvocation.MyCommand.Path) Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop +#Import-Module -Name powershell-yaml -Force -ErrorAction Stop Start-PodeServer { Add-PodeEndpoint -Address localhost -Port 8080 -Protocol Http -Name 'user' @@ -8,8 +9,16 @@ Start-PodeServer { New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging Enable-PodeOpenApi -Title 'OpenAPI Example' -RouteFilter '/api/*' -RestrictRoutes - Enable-PodeOpenApiViewer -Type Swagger -DarkMode + Enable-PodeOpenApiViewer -Type Swagger Enable-PodeOpenApiViewer -Type ReDoc + Enable-PodeOpenApiViewer -Type RapiDoc + Enable-PodeOpenApiViewer -Type StopLight + Enable-PodeOpenApiViewer -Type Explorer + Enable-PodeOpenApiViewer -Type RapiPdf + + + Enable-PodeOpenApiViewer -Editor + Enable-PodeOpenApiViewer -Bookmarks New-PodeAuthScheme -Basic | Add-PodeAuth -Name 'Validate' -Sessionless -ScriptBlock { @@ -19,7 +28,7 @@ Start-PodeServer { if ($username -eq 'morty' -and $password -eq 'pickle') { return @{ User = @{ - ID ='M0R7Y302' + ID = 'M0R7Y302' Name = 'Morty' Type = 'Human' } @@ -34,59 +43,58 @@ Start-PodeServer { 'application/json' = (New-PodeOAObjectProperty -Properties @( (New-PodeOAStringProperty -Name 'Name'), (New-PodeOAIntProperty -Name 'UserId') - )) + )) } New-PodeOAIntProperty -Name 'userId' -Required | - ConvertTo-PodeOAParameter -In Path | - Add-PodeOAComponentParameter -Name 'UserId' - + ConvertTo-PodeOAParameter -In Path | + Add-PodeOAComponentParameter -Name 'UserId' Add-PodeAuthMiddleware -Name AuthMiddleware -Authentication Validate -Route '/api/*' - - Add-PodeRoute -Method Get -Path "/api/resources" -EndpointName 'user' -ScriptBlock { + Add-PodeRoute -Method Get -Path '/api/resources' -EndpointName 'user' -ScriptBlock { Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = 123 } } -PassThru | - Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Resources' -PassThru | - Add-PodeOAResponse -StatusCode 200 -Reference 'OK' + Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Resources' -PassThru | + Add-PodeOAResponse -StatusCode 200 -Reference 'OK' - Add-PodeRoute -Method Post -Path "/api/resources" -ScriptBlock { + Add-PodeRoute -Method Post -Path '/api/resources' -ScriptBlock { Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = 123 } } -PassThru | - Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Resources' -PassThru | - Add-PodeOAResponse -StatusCode 200 -Reference 'OK' + Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Resources' -PassThru | + Add-PodeOAResponse -StatusCode 200 -Reference 'OK' Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Parameters['userId'] } } -PassThru | - Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | - Set-PodeOARequest -Parameters @( + Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | + Set-PodeOARequest -Parameters @( (ConvertTo-PodeOAParameter -Reference 'UserId') - ) -PassThru | - Add-PodeOAResponse -StatusCode 200 -Reference 'OK' + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Reference 'OK' Add-PodeRoute -Method Get -Path '/api/users' -ScriptBlock { Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Query['userId'] } } -PassThru | - Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | - Set-PodeOARequest -Parameters @( + Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | + Set-PodeOARequest -Parameters @( (New-PodeOAIntProperty -Name 'userId' -Required | ConvertTo-PodeOAParameter -In Query) - ) -PassThru | - Add-PodeOAResponse -StatusCode 200 -Reference 'OK' + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Reference 'OK' Add-PodeRoute -Method Post -Path '/api/users' -ScriptBlock { Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Data.userId } } -PassThru | - Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | - Set-PodeOARequest -RequestBody ( - New-PodeOARequestBody -Required -ContentSchemas @{ - 'application/json' = (New-PodeOAIntProperty -Name 'userId' -Object) - } - ) -PassThru | - Add-PodeOAResponse -StatusCode 200 -Reference 'OK' + Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | + Set-PodeOARequest -RequestBody ( + New-PodeOARequestBody -Required -ContentSchemas @{ + 'application/json' = (New-PodeOAIntProperty -Name 'userId' -Object) + } + ) -PassThru | + Add-PodeOAResponse -StatusCode 200 -Reference 'OK' + } \ No newline at end of file diff --git a/examples/web-rest-openapi-simple.ps1 b/examples/web-rest-openapi-simple.ps1 index a578b1547..072e7eba2 100644 --- a/examples/web-rest-openapi-simple.ps1 +++ b/examples/web-rest-openapi-simple.ps1 @@ -8,43 +8,43 @@ Start-PodeServer { Enable-PodeOpenApi -Title 'OpenAPI Example' -RouteFilter '/api/*' -RestrictRoutes Enable-PodeOpenApiViewer -Type Swagger -DarkMode Enable-PodeOpenApiViewer -Type ReDoc + Enable-PodeOpenApiViewer -Bookmarks -Path '/docs' - - Add-PodeRoute -Method Get -Path "/api/resources" -EndpointName 'user' -ScriptBlock { + Add-PodeRoute -Method Get -Path '/api/resources' -EndpointName 'user' -ScriptBlock { Set-PodeResponseStatus -Code 200 } - Add-PodeRoute -Method Post -Path "/api/resources" -ScriptBlock { + Add-PodeRoute -Method Post -Path '/api/resources' -ScriptBlock { Set-PodeResponseStatus -Code 200 } Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Parameters['userId'] } - } -PassThru | - Set-PodeOARequest -Parameters @( - (New-PodeOAIntProperty -Name 'userId' -Enum @(100,300,999) -Required | ConvertTo-PodeOAParameter -In Path) - ) + } -PassThru | Set-PodeOARouteInfo -PassThru | + Set-PodeOARequest -Parameters @( + (New-PodeOAIntProperty -Name 'userId' -Enum @(100, 300, 999) -Required | ConvertTo-PodeOAParameter -In Path) + ) Add-PodeRoute -Method Get -Path '/api/users' -ScriptBlock { Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Query['userId'] } - } -PassThru | - Set-PodeOARequest -Parameters @( + } -PassThru | Set-PodeOARouteInfo -PassThru | + Set-PodeOARequest -Parameters @( (New-PodeOAIntProperty -Name 'userId' -Required | ConvertTo-PodeOAParameter -In Query) - ) + ) Add-PodeRoute -Method Post -Path '/api/users' -ScriptBlock { Write-PodeJsonResponse -Value @{ Name = $WebEvent.Data.Name; UserId = $WebEvent.Data.UserId } - } -PassThru | - Set-PodeOARequest -RequestBody ( - New-PodeOARequestBody -Required -ContentSchemas @{ - 'application/json' = (New-PodeOAObjectProperty -Properties @( + } -PassThru | Set-PodeOARouteInfo -PassThru | + Set-PodeOARequest -RequestBody ( + New-PodeOARequestBody -Required -ContentSchemas @{ + 'application/json' = (New-PodeOAObjectProperty -Properties @( (New-PodeOAStringProperty -Name 'Name' -MaxLength 5 -Pattern '[a-zA-Z]+'), (New-PodeOAIntProperty -Name 'UserId') )) - } - ) + } + ) } diff --git a/examples/web-rest-openapi.ps1 b/examples/web-rest-openapi.ps1 index 1e51408d8..0f6e25598 100644 --- a/examples/web-rest-openapi.ps1 +++ b/examples/web-rest-openapi.ps1 @@ -8,9 +8,14 @@ Start-PodeServer { New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging Enable-PodeOpenApi -Title 'OpenAPI Example' -RouteFilter '/api/*' -RestrictRoutes - Enable-PodeOpenApiViewer -Type Swagger -DarkMode - Enable-PodeOpenApiViewer -Type ReDoc - + Enable-PodeOpenApiViewer -Type Swagger -Path '/docs/swagger' + Enable-PodeOpenApiViewer -Type ReDoc -Path '/docs/redoc' + Enable-PodeOpenApiViewer -Type RapiDoc -Path '/docs/rapidoc' + Enable-PodeOpenApiViewer -Type StopLight -Path '/docs/stoplight' + Enable-PodeOpenApiViewer -Type Explorer -Path '/docs/explorer' + Enable-PodeOpenApiViewer -Type RapiPdf -Path '/docs/rapipdf' + Enable-PodeOpenApiViewer -Editor -Path '/docs/editor' + Enable-PodeOpenApiViewer -Bookmarks -Path '/docs' New-PodeAuthScheme -Basic | Add-PodeAuth -Name 'Validate' -Sessionless -ScriptBlock { return @{ diff --git a/examples/web-route-group.ps1 b/examples/web-route-group.ps1 index 8c0a36dce..166746465 100644 --- a/examples/web-route-group.ps1 +++ b/examples/web-route-group.ps1 @@ -43,7 +43,7 @@ Start-PodeServer -Threads 2 { # here you'd check a real user storage, this is just for example if ($username -eq 'morty' -and $password -eq 'pickle') { return @{ - User = @{ ID ='M0R7Y302' } + User = @{ ID = 'M0R7Y302' } } } diff --git a/examples/web-static-auth.ps1 b/examples/web-static-auth.ps1 index 8e16d9c67..b065771b0 100644 --- a/examples/web-static-auth.ps1 +++ b/examples/web-static-auth.ps1 @@ -1,14 +1,16 @@ $path = Split-Path -Parent -Path (Split-Path -Parent -Path $MyInvocation.MyCommand.Path) -Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop - -# or just: -# Import-Module Pode +if (Test-Path -Path "$($path)/src/Pode.psm1" -PathType Leaf) { + Import-Module "$($path)/src/Pode.psm1" -Force -ErrorAction Stop +} +else { + Import-Module -Name 'Pode' +} # create a server, and start listening on port 8085 Start-PodeServer -Threads 2 { # listen on localhost:8085 - Add-PodeEndpoint -Address * -Port 8085 -Protocol Http + Add-PodeEndpoint -Address localhost -Port 8085 -Protocol Http New-PodeLoggingMethod -Terminal | Enable-PodeRequestLogging New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging diff --git a/mkdocs.yml b/mkdocs.yml index 1025062f1..1b554ac12 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -10,8 +10,9 @@ theme: - navigation.tabs.sticky - navigation.tracking - navigation.top - - content.copy.code + - content.code.copy - content.action.edit + - content.action.view font: text: Fira Sans code: Fira Code @@ -40,6 +41,7 @@ markdown_extensions: repo_name: badgerati/pode repo_url: https://github.com/Badgerati/Pode +edit_uri: edit/master/docs extra: social: @@ -47,5 +49,7 @@ extra: link: https://discord.gg/fRqeGcbF6h - icon: fontawesome/brands/github link: https://github.com/badgerati/pode - - icon: fontawesome/brands/twitter - link: https://twitter.com/badgerati \ No newline at end of file + - icon: fontawesome/brands/x-twitter + link: https://twitter.com/badgerati + - icon: fontawesome/brands/docker + link: https://hub.docker.com/r/badgerati/pode \ No newline at end of file diff --git a/packers/choco/pode.nuspec b/packers/choco/pode_template.nuspec similarity index 95% rename from packers/choco/pode.nuspec rename to packers/choco/pode_template.nuspec index 6539329ef..2a9093c65 100644 --- a/packers/choco/pode.nuspec +++ b/packers/choco/pode_template.nuspec @@ -52,9 +52,10 @@ Pode is a Cross-Platform framework for creating web servers to host REST APIs an https://raw.githubusercontent.com/Badgerati/Pode/master/images/icon.png https://github.com/Badgerati/Pode/releases - - + + + \ No newline at end of file diff --git a/packers/choco/tools/ChocolateyInstall.ps1 b/packers/choco/tools/ChocolateyInstall_template.ps1 similarity index 100% rename from packers/choco/tools/ChocolateyInstall.ps1 rename to packers/choco/tools/ChocolateyInstall_template.ps1 diff --git a/packers/docker/arm32/Dockerfile b/packers/docker/arm32/Dockerfile index 9f842034a..8cc8c8b7f 100644 --- a/packers/docker/arm32/Dockerfile +++ b/packers/docker/arm32/Dockerfile @@ -1,6 +1,6 @@ FROM arm32v7/ubuntu:bionic -ENV PS_VERSION=7.3.1 +ENV PS_VERSION=7.3.11 ENV PS_PACKAGE=powershell-${PS_VERSION}-linux-arm32.tar.gz ENV PS_PACKAGE_URL=https://github.com/PowerShell/PowerShell/releases/download/v${PS_VERSION}/${PS_PACKAGE} diff --git a/pode.build.ps1 b/pode.build.ps1 index a0366fd10..6cd1d1010 100644 --- a/pode.build.ps1 +++ b/pode.build.ps1 @@ -1,6 +1,11 @@ +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSReviewUnusedParameter', '')] +[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')] param( [string] - $Version = '' + $Version = '0.0.0', + [string] + [ValidateSet( 'None', 'Normal' , 'Detailed', 'Diagnostic')] + $PesterVerbosity = 'Normal' ) <# @@ -8,20 +13,18 @@ param( #> $Versions = @{ - Pester = '4.8.0' + Pester = '5.5.0' MkDocs = '1.5.3' PSCoveralls = '1.0.0' SevenZip = '18.5.0.20180730' - DotNet = '7.0.1' - Checksum = '0.2.0' - MkDocsTheme = '9.4.6' + DotNet = '8.0' + MkDocsTheme = '9.5.17' PlatyPS = '0.14.2' } <# # Helper Functions #> - function Test-PodeBuildIsWindows { $v = $PSVersionTable return ($v.Platform -ilike '*win*' -or ($null -eq $v.Platform -and $v.PSEdition -ieq 'desktop')) @@ -87,40 +90,66 @@ function Install-PodeBuildModule($name) { Install-Module -Name "$($name)" -Scope CurrentUser -RequiredVersion "$($Versions[$name])" -Force -SkipPublisherCheck } -function Invoke-PodeBuildDotnetBuild($target) { - dotnet build --configuration Release --self-contained --framework $target - if (!$?) { - throw "dotnet build failed for $($target)" +function Invoke-PodeBuildDotnetBuild($target ) { + + # Retrieve the highest installed SDK version + $majorVersion = ([version](dotnet --version)).Major + + # Determine if the target framework is compatible + $isCompatible = $False + switch ($majorVersion) { + 8 { if ($target -in @('net6.0', 'net7.0', 'netstandard2.0', 'net8.0')) { $isCompatible = $True } } + 7 { if ($target -in @('net6.0', 'net7.0', 'netstandard2.0')) { $isCompatible = $True } } + 6 { if ($target -in @('net6.0', 'netstandard2.0')) { $isCompatible = $True } } + } + + # Skip build if not compatible + if ( $isCompatible) { + Write-Host "SDK for target framework $target is compatible with the installed SDKs" + } + else { + Write-Host "SDK for target framework $target is not compatible with the installed SDKs. Skipping build." + return + } + if ($Version) { + Write-Host "Assembly Version $Version" + $AssemblyVersion = "-p:Version=$Version" + } + else { + $AssemblyVersion = '' } - dotnet publish --configuration Release --self-contained --framework $target --output ../Libs/$target + dotnet publish --configuration Release --self-contained --framework $target $AssemblyVersion --output ../Libs/$target if (!$?) { throw "dotnet publish failed for $($target)" } + } +function Get-PodeBuildPwshEOL { + $eol = invoke-restmethod -Uri 'https://endoflife.date/api/powershell.json' -Headers @{Accept = 'application/json' } + return @{ + eol = ($eol | Where-Object { [datetime]$_.eol -lt [datetime]::Now }).cycle -join ',' + supported = ($eol | Where-Object { [datetime]$_.eol -ge [datetime]::Now }).cycle -join ',' + } +} <# # Helper Tasks #> # Synopsis: Stamps the version onto the Module -task StampVersion { - (Get-Content ./pkg/Pode.psd1) | ForEach-Object { $_ -replace '\$version\$', $Version } | Set-Content ./pkg/Pode.psd1 +Task StampVersion { + $pwshVersions = Get-PodeBuildPwshEOL + (Get-Content ./pkg/Pode.psd1) | ForEach-Object { $_ -replace '\$version\$', $Version -replace '\$versionsUntested\$', $pwshVersions.eol -replace '\$versionsSupported\$', $pwshVersions.supported -replace '\$buildyear\$', ((get-date).Year) } | Set-Content ./pkg/Pode.psd1 (Get-Content ./pkg/Pode.Internal.psd1) | ForEach-Object { $_ -replace '\$version\$', $Version } | Set-Content ./pkg/Pode.Internal.psd1 - (Get-Content ./packers/choco/pode.nuspec) | ForEach-Object { $_ -replace '\$version\$', $Version } | Set-Content ./packers/choco/pode.nuspec - (Get-Content ./packers/choco/tools/ChocolateyInstall.ps1) | ForEach-Object { $_ -replace '\$version\$', $Version } | Set-Content ./packers/choco/tools/ChocolateyInstall.ps1 + (Get-Content ./packers/choco/pode_template.nuspec) | ForEach-Object { $_ -replace '\$version\$', $Version } | Set-Content ./packers/choco/pode.nuspec + (Get-Content ./packers/choco/tools/ChocolateyInstall_template.ps1) | ForEach-Object { $_ -replace '\$version\$', $Version } | Set-Content ./packers/choco/tools/ChocolateyInstall.ps1 } # Synopsis: Generating a Checksum of the Zip -task PrintChecksum { - if (Test-PodeBuildIsWindows) { - $Script:Checksum = (checksum -t sha256 $Version-Binaries.zip) - } - else { - $Script:Checksum = (shasum -a 256 ./$Version-Binaries.zip | awk '{ print $1 }').ToUpper() - } - +Task PrintChecksum { + $Script:Checksum = (Get-FileHash "./deliverable/$Version-Binaries.zip" -Algorithm SHA256).Hash Write-Host "Checksum: $($Checksum)" } @@ -130,7 +159,7 @@ task PrintChecksum { #> # Synopsis: Installs Chocolatey -task ChocoDeps -If (Test-PodeBuildIsWindows) { +Task ChocoDeps -If (Test-PodeBuildIsWindows) { if (!(Test-PodeBuildCommand 'choco')) { Set-ExecutionPolicy Bypass -Scope Process -Force Invoke-Expression ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1')) @@ -138,26 +167,28 @@ task ChocoDeps -If (Test-PodeBuildIsWindows) { } # Synopsis: Install dependencies for packaging -task PackDeps -If (Test-PodeBuildIsWindows) ChocoDeps, { - if (!(Test-PodeBuildCommand 'checksum')) { - Invoke-PodeBuildInstall 'checksum' $Versions.Checksum - } - +Task PackDeps -If (Test-PodeBuildIsWindows) ChocoDeps, { if (!(Test-PodeBuildCommand '7z')) { Invoke-PodeBuildInstall '7zip' $Versions.SevenZip } } # Synopsis: Install dependencies for compiling/building -task BuildDeps { +Task BuildDeps { # install dotnet + if (Test-PodeBuildIsWindows) { + $dotnet = 'dotnet' + } + else { + $dotnet = "dotnet-sdk-$($Versions.DotNet)" + } if (!(Test-PodeBuildCommand 'dotnet')) { - Invoke-PodeBuildInstall 'dotnet' $Versions.DotNet + Invoke-PodeBuildInstall $dotnet $Versions.DotNet } } # Synopsis: Install dependencies for running tests -task TestDeps { +Task TestDeps { # install pester Install-PodeBuildModule Pester @@ -168,7 +199,7 @@ task TestDeps { } # Synopsis: Install dependencies for documentation -task DocsDeps ChocoDeps, { +Task DocsDeps ChocoDeps, { # install mkdocs if (!(Test-PodeBuildCommand 'mkdocs')) { Invoke-PodeBuildInstall 'mkdocs' $Versions.MkDocs @@ -189,17 +220,19 @@ task DocsDeps ChocoDeps, { #> # Synopsis: Build the .NET Listener -task Build BuildDeps, { +Task Build BuildDeps, { if (Test-Path ./src/Libs) { Remove-Item -Path ./src/Libs -Recurse -Force | Out-Null } - + Write-Host 'Powershell Version:' + $PSVersionTable.PSVersion Push-Location ./src/Listener try { Invoke-PodeBuildDotnetBuild -target 'netstandard2.0' Invoke-PodeBuildDotnetBuild -target 'net6.0' Invoke-PodeBuildDotnetBuild -target 'net7.0' + Invoke-PodeBuildDotnetBuild -target 'net8.0' } finally { Pop-Location @@ -212,17 +245,39 @@ task Build BuildDeps, { #> # Synopsis: Creates a Zip of the Module -task 7Zip -If (Test-PodeBuildIsWindows) PackDeps, StampVersion, { +Task 7Zip -If (Test-PodeBuildIsWindows) PackDeps, StampVersion, { exec { & 7z -tzip a $Version-Binaries.zip ./pkg/* } }, PrintChecksum + +# Synopsis: Creates a Zip of the Module +Task Compress StampVersion, { + $path = './deliverable' + if (Test-Path $path) { + Remove-Item -Path $path -Recurse -Force | Out-Null + } + # create the pkg dir + New-Item -Path $path -ItemType Directory -Force | Out-Null + Compress-Archive -Path './pkg/*' -DestinationPath "$path/$Version-Binaries.zip" +}, PrintChecksum + # Synopsis: Creates a Chocolately package of the Module -task ChocoPack -If (Test-PodeBuildIsWindows) PackDeps, StampVersion, { +Task ChocoPack -If (Test-PodeBuildIsWindows) PackDeps, StampVersion, { exec { choco pack ./packers/choco/pode.nuspec } + Move-Item -Path "pode.$Version.nupkg" -Destination './deliverable' } # Synopsis: Create docker tags -task DockerPack -If ((Test-PodeBuildIsWindows) -or $IsLinux) { +Task DockerPack -If (((Test-PodeBuildIsWindows) -or $IsLinux) ) { + try { + # Try to get the Docker version to check if Docker is installed + docker --version + } + catch { + # If Docker is not available, exit the task + Write-Warning 'Docker is not installed or not available in the PATH. Exiting task.' + return + } docker build -t badgerati/pode:$Version -f ./Dockerfile . docker build -t badgerati/pode:latest -f ./Dockerfile . docker build -t badgerati/pode:$Version-alpine -f ./alpine.dockerfile . @@ -239,12 +294,11 @@ task DockerPack -If ((Test-PodeBuildIsWindows) -or $IsLinux) { } # Synopsis: Package up the Module -task Pack -If (Test-PodeBuildIsWindows) Build, { +Task Pack Build, { $path = './pkg' if (Test-Path $path) { Remove-Item -Path $path -Recurse -Force | Out-Null } - # create the pkg dir New-Item -Path $path -ItemType Directory -Force | Out-Null @@ -263,7 +317,7 @@ task Pack -If (Test-PodeBuildIsWindows) Build, { Copy-Item -Path ./src/Pode.Internal.psm1 -Destination $path -Force | Out-Null Copy-Item -Path ./src/Pode.Internal.psd1 -Destination $path -Force | Out-Null Copy-Item -Path ./LICENSE.txt -Destination $path -Force | Out-Null -}, StampVersion, 7Zip, ChocoPack, DockerPack +}, StampVersion, Compress, ChocoPack, DockerPack <# @@ -271,7 +325,7 @@ task Pack -If (Test-PodeBuildIsWindows) Build, { #> # Synopsis: Run the tests -task Test Build, TestDeps, { +Task TestNoBuild TestDeps, { $p = (Get-Command Invoke-Pester) if ($null -eq $p -or $p.Version -ine $Versions.Pester) { Remove-Module Pester -Force -ErrorAction Ignore @@ -279,26 +333,38 @@ task Test Build, TestDeps, { } $Script:TestResultFile = "$($pwd)/TestResults.xml" - + # get default from static property + $configuration = [PesterConfiguration]::Default + $configuration.run.path = @('./tests/unit', './tests/integration') + $configuration.run.PassThru = $true + $configuration.TestResult.OutputFormat = 'NUnitXml' + $configuration.Output.Verbosity = $PesterVerbosity + $configuration.TestResult.OutputPath = $Script:TestResultFile # if run code coverage if enabled if (Test-PodeBuildCanCodeCoverage) { $srcFiles = (Get-ChildItem "$($pwd)/src/*.ps1" -Recurse -Force).FullName - $Script:TestStatus = Invoke-Pester './tests/unit', './tests/integration' -OutputFormat NUnitXml -OutputFile $TestResultFile -CodeCoverage $srcFiles -PassThru + $configuration.CodeCoverage.Enabled = $true + $configuration.CodeCoverage.Path = $srcFiles + $Script:TestStatus = Invoke-Pester -Configuration $configuration } else { - $Script:TestStatus = Invoke-Pester './tests/unit', './tests/integration' -OutputFormat NUnitXml -OutputFile $TestResultFile -Show Failed -PassThru + $Script:TestStatus = Invoke-Pester -Configuration $configuration } }, PushCodeCoverage, CheckFailedTests +# Synopsis: Run tests after a build +Task Test Build, TestNoBuild + + # Synopsis: Check if any of the tests failed -task CheckFailedTests { +Task CheckFailedTests { if ($TestStatus.FailedCount -gt 0) { throw "$($TestStatus.FailedCount) tests failed" } } # Synopsis: If AppyVeyor or GitHub, push code coverage stats -task PushCodeCoverage -If (Test-PodeBuildCanCodeCoverage) { +Task PushCodeCoverage -If (Test-PodeBuildCanCodeCoverage) { try { $service = Get-PodeBuildService $branch = Get-PodeBuildBranch @@ -318,12 +384,12 @@ task PushCodeCoverage -If (Test-PodeBuildCanCodeCoverage) { #> # Synopsis: Run the documentation locally -task Docs DocsDeps, DocsHelpBuild, { +Task Docs DocsDeps, DocsHelpBuild, { mkdocs serve } # Synopsis: Build the function help documentation -task DocsHelpBuild DocsDeps, { +Task DocsHelpBuild DocsDeps, { # import the local module Remove-Module Pode -Force -ErrorAction Ignore | Out-Null Import-Module ./src/Pode.psm1 -Force | Out-Null @@ -367,6 +433,128 @@ task DocsHelpBuild DocsDeps, { } # Synopsis: Build the documentation -task DocsBuild DocsDeps, DocsHelpBuild, { +Task DocsBuild DocsDeps, DocsHelpBuild, { mkdocs build +} + +# Synopsis: Clean the build enviroment +Task Clean CleanPkg, CleanDeliverable, CleanLibs, CleanListener + +# Synopsis: Clean the Deliverable folder +Task CleanDeliverable { + $path = './deliverable' + if (Test-Path -Path $path -PathType Container) { + Write-Host 'Removing ./deliverable folder' + Remove-Item -Path $path -Recurse -Force | Out-Null + } + Write-Host "Cleanup $path done" +} + +# Synopsis: Clean the pkg directory +Task CleanPkg { + $path = './pkg' + if ((Test-Path -Path $path -PathType Container )) { + Write-Host 'Removing ./pkg folder' + Remove-Item -Path $path -Recurse -Force | Out-Null + } + + if ((Test-Path -Path .\packers\choco\tools\ChocolateyInstall.ps1 -PathType Leaf )) { + Write-Host 'Removing .\packers\choco\tools\ChocolateyInstall.ps1' + Remove-Item -Path .\packers\choco\tools\ChocolateyInstall.ps1 + } + if ((Test-Path -Path .\packers\choco\pode.nuspec -PathType Leaf )) { + Write-Host 'Removing .\packers\choco\pode.nuspec' + Remove-Item -Path .\packers\choco\pode.nuspec + } + Write-Host "Cleanup $path done" +} + +# Synopsis: Clean the libs folder +Task CleanLibs { + $path = './src/Libs' + if (Test-Path -Path $path -PathType Container) { + Write-Host "Removing $path contents" + Remove-Item -Path $path -Recurse -Force | Out-Null + } + Write-Host "Cleanup $path done" +} + +# Synopsis: Clean the Listener folder +Task CleanListener { + $path = './src/Listener/bin' + if (Test-Path -Path $path -PathType Container) { + Write-Host "Removing $path contents" + Remove-Item -Path $path -Recurse -Force | Out-Null + } + Write-Host "Cleanup $path done" +} + +# Synopsis: Install Pode Module locally +Task Install-Module { + $path = './pkg' + if ($Version) { + + if (! (Test-Path $path)) { + Invoke-Build Pack -Version $Version + } + if ($IsWindows -or (($PSVersionTable.Keys -contains 'PSEdition') -and ($PSVersionTable.PSEdition -eq 'Desktop'))) { + $PSPaths = $ENV:PSModulePath -split ';' + } + else { + $PSPaths = $ENV:PSModulePath -split ':' + } + $dest = join-path -Path $PSPaths[0] -ChildPath 'Pode' -AdditionalChildPath "$Version" + + if (Test-Path $dest) { + Remove-Item -Path $dest -Recurse -Force | Out-Null + } + + # create the dest dir + New-Item -Path $dest -ItemType Directory -Force | Out-Null + + Copy-Item -Path (Join-Path -Path $path -ChildPath 'Private' ) -Destination $dest -Force -Recurse | Out-Null + Copy-Item -Path (Join-Path -Path $path -ChildPath 'Public' ) -Destination $dest -Force -Recurse | Out-Null + Copy-Item -Path (Join-Path -Path $path -ChildPath 'Misc' ) -Destination $dest -Force -Recurse | Out-Null + Copy-Item -Path (Join-Path -Path $path -ChildPath 'Libs' ) -Destination $dest -Force -Recurse | Out-Null + + # copy general files + Copy-Item -Path $(Join-Path -Path $path -ChildPath 'Pode.psm1') -Destination $dest -Force | Out-Null + Copy-Item -Path $(Join-Path -Path $path -ChildPath 'Pode.psd1') -Destination $dest -Force | Out-Null + Copy-Item -Path $(Join-Path -Path $path -ChildPath 'Pode.Internal.psm1') -Destination $dest -Force | Out-Null + Copy-Item -Path $(Join-Path -Path $path -ChildPath 'Pode.Internal.psd1') -Destination $dest -Force | Out-Null + Copy-Item -Path $(Join-Path -Path $path -ChildPath 'LICENSE.txt') -Destination $dest -Force | Out-Null + + Write-Host "Deployed to $dest" + } + else { + Write-Error 'Parameter -Version is required' + } + +} + +# Synopsis: Remove the Pode Module from the local registry +Task Remove-Module { + + if ($Version) { + if ($IsWindows -or (($PSVersionTable.Keys -contains 'PSEdition') -and ($PSVersionTable.PSEdition -eq 'Desktop'))) { + $PSPaths = $ENV:PSModulePath -split ';' + } + else { + $PSPaths = $ENV:PSModulePath -split ':' + } + $dest = join-path -Path $PSPaths[0] -ChildPath 'Pode' -AdditionalChildPath "$Version" + + if (Test-Path $dest) { + Write-Host "Deleting module from $dest" + Remove-Item -Path $dest -Recurse -Force | Out-Null + } + else { + Write-Error "Directory $dest doesn't exist" + } + + } + else { + Write-Error 'Parameter -Version is required' + } + } \ No newline at end of file diff --git a/src/Listener/Pode.csproj b/src/Listener/Pode.csproj index f65cedc7f..ac6f33723 100644 --- a/src/Listener/Pode.csproj +++ b/src/Listener/Pode.csproj @@ -1,6 +1,6 @@ - netstandard2.0;net6.0;net7.0 + netstandard2.0;net6.0;net7.0;net8.0 $(NoWarn);SYSLIB0001 diff --git a/src/Listener/PodeContext.cs b/src/Listener/PodeContext.cs index 3c1bf95fc..ebc00fdca 100644 --- a/src/Listener/PodeContext.cs +++ b/src/Listener/PodeContext.cs @@ -15,10 +15,15 @@ public class PodeContext : PodeProtocol, IDisposable public PodeResponse Response { get; private set; } public PodeListener Listener { get; private set; } public Socket Socket { get; private set; } - public PodeSocket PodeSocket { get; private set;} + public PodeSocket PodeSocket { get; private set; } public DateTime Timestamp { get; private set; } public Hashtable Data { get; private set; } + public string EndpointName + { + get => PodeSocket.Name; + } + private object _lockable = new object(); private PodeContextState _state; @@ -79,7 +84,7 @@ public PodeSignalRequest SignalRequest public bool IsKeepAlive { - get => (Request.IsKeepAlive); + get => ((Request.IsKeepAlive && Response.SseScope != PodeSseScope.Local) || Response.SseScope == PodeSseScope.Global); } public bool IsErrored @@ -123,6 +128,11 @@ public PodeContext(Socket socket, PodeSocket podeSocket, PodeListener listener) private void TimeoutCallback(object state) { + if (Response.SseEnabled) + { + return; + } + ContextTimeoutToken.Cancel(); State = PodeContextState.Timeout; @@ -256,6 +266,11 @@ public void RenewTimeoutToken() ContextTimeoutToken = new CancellationTokenSource(); } + public void CancelTimeout() + { + TimeoutTimer.Dispose(); + } + public async void Receive() { try @@ -271,7 +286,7 @@ public async void Receive() SetContextType(); EndReceive(close); } - catch (OperationCanceledException) {} + catch (OperationCanceledException) { } } catch (Exception ex) { @@ -412,6 +427,12 @@ public void Dispose(bool force) if (!_awaitingBody && (!IsKeepAlive || force)) { State = PodeContextState.Closed; + + if (Response.SseEnabled) + { + Response.CloseSseConnection(); + } + Request.Dispose(); } @@ -420,10 +441,10 @@ public void Dispose(bool force) Response.Dispose(); } } - catch {} + catch { } // if keep-alive, or awaiting body, setup for re-receive - if ((_awaitingBody || (IsKeepAlive && !IsErrored && !IsTimeout)) && !force) + if ((_awaitingBody || (IsKeepAlive && !IsErrored && !IsTimeout && !Response.SseEnabled)) && !force) { StartReceive(); } diff --git a/src/Listener/PodeEndpoint.cs b/src/Listener/PodeEndpoint.cs new file mode 100644 index 000000000..917dfb643 --- /dev/null +++ b/src/Listener/PodeEndpoint.cs @@ -0,0 +1,78 @@ +using System; +using System.Net; +using System.Net.Sockets; + +namespace Pode +{ + public class PodeEndpoint : IDisposable + { + public IPAddress IPAddress { get; private set; } + public int Port { get; private set; } + public IPEndPoint Endpoint { get; private set; } + public Socket Socket { get; private set; } + public PodeSocket PodeSocket { get; private set; } + public bool DualMode { get; private set; } + public bool IsDisposed { get; private set; } + + public int ReceiveTimeout + { + get => Socket.ReceiveTimeout; + set => Socket.ReceiveTimeout = value; + } + + public PodeEndpoint(PodeSocket socket, IPAddress ipAddress, int port, bool dualMode) + { + IsDisposed = false; + PodeSocket = socket; + IPAddress = ipAddress; + Port = port; + Endpoint = new IPEndPoint(ipAddress, port); + + Socket = new Socket(Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) + { + ReceiveTimeout = 100, + NoDelay = true + }; + + if (dualMode && Endpoint.AddressFamily == AddressFamily.InterNetworkV6) + { + DualMode = true; + Socket.DualMode = true; + Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false); + } + else + { + DualMode = false; + } + } + + public void Listen() + { + Socket.Bind(Endpoint); + Socket.Listen(int.MaxValue); + } + + public bool AcceptAsync(SocketAsyncEventArgs args) + { + if (IsDisposed) + { + throw new ObjectDisposedException("PodeEndpoint disposed"); + } + + return Socket.AcceptAsync(args); + } + + public void Dispose() + { + IsDisposed = true; + PodeSocket.CloseSocket(Socket); + Socket = default(Socket); + } + + public new bool Equals(object obj) + { + var _endpoint = (PodeEndpoint)obj; + return Endpoint.ToString() == _endpoint.Endpoint.ToString() && Port == _endpoint.Port; + } + } +} \ No newline at end of file diff --git a/src/Listener/PodeFileWatcher.cs b/src/Listener/PodeFileWatcher.cs index 9a2d2f1e7..da1249cdb 100644 --- a/src/Listener/PodeFileWatcher.cs +++ b/src/Listener/PodeFileWatcher.cs @@ -10,7 +10,7 @@ public class PodeFileWatcher private RecoveringFileSystemWatcher FileWatcher; public string Name { get; private set; } - public ISet EventsRegistered {get; private set; } + public ISet EventsRegistered { get; private set; } public PodeFileWatcher(string name, string path, bool includeSubdirectories, int internalBufferSize, NotifyFilters notifyFilters) { diff --git a/src/Listener/PodeHttpRequest.cs b/src/Listener/PodeHttpRequest.cs index a78fcdb79..54b6ffbd4 100644 --- a/src/Listener/PodeHttpRequest.cs +++ b/src/Listener/PodeHttpRequest.cs @@ -34,6 +34,14 @@ public class PodeHttpRequest : PodeRequest private bool IsRequestLineValid; private MemoryStream BodyStream; + public string SseClientId { get; private set; } + public string SseClientName { get; private set; } + public string SseClientGroup { get; private set; } + public bool HasSseClientId + { + get => !string.IsNullOrEmpty(SseClientId); + } + private string _body = string.Empty; public string Body { @@ -292,6 +300,14 @@ private int ParseHeaders(string[] reqLines, string newline) Type = PodeProtocolType.Ws; } + // do we have an SSE ClientId? + SseClientId = $"{Headers["X-Pode-Sse-Client-Id"]}"; + if (HasSseClientId) + { + SseClientName = $"{Headers["X-Pode-Sse-Name"]}"; + SseClientGroup = $"{Headers["X-Pode-Sse-Group"]}"; + } + // keep-alive? IsKeepAlive = (IsWebSocket || (Headers.ContainsKey("Connection") diff --git a/src/Listener/PodeListener.cs b/src/Listener/PodeListener.cs index 9ad432b0f..f5a1dc655 100644 --- a/src/Listener/PodeListener.cs +++ b/src/Listener/PodeListener.cs @@ -11,6 +11,7 @@ public class PodeListener : PodeConnector private IList Sockets; public IDictionary Signals { get; private set; } + public IDictionary> ServerEvents { get; private set; } public PodeItemQueue Contexts { get; private set; } public PodeItemQueue ServerSignals { get; private set; } public PodeItemQueue ClientSignals { get; private set; } @@ -50,6 +51,7 @@ public bool ShowServerDetails { Sockets = new List(); Signals = new Dictionary(); + ServerEvents = new Dictionary>(); Contexts = new PodeItemQueue(); ServerSignals = new PodeItemQueue(); @@ -110,6 +112,105 @@ public void AddSignal(PodeSignal signal) } } + public void AddSseConnection(PodeServerEvent sse) + { + lock (ServerEvents) + { + // add sse name + if (!ServerEvents.ContainsKey(sse.Name)) + { + ServerEvents.Add(sse.Name, new Dictionary()); + } + + // add sse connection + if (ServerEvents[sse.Name].ContainsKey(sse.ClientId)) + { + ServerEvents[sse.Name][sse.ClientId]?.Dispose(); + ServerEvents[sse.Name][sse.ClientId] = sse; + } + else + { + ServerEvents[sse.Name].Add(sse.ClientId, sse); + } + } + } + + public void SendSseEvent(string name, string[] groups, string[] clientIds, string eventType, string data, string id = null) + { + Task.Factory.StartNew(() => + { + if (!ServerEvents.ContainsKey(name)) + { + return; + } + + if (clientIds == default(string[]) || clientIds.Length == 0) + { + clientIds = ServerEvents[name].Keys.ToArray(); + } + + foreach (var clientId in clientIds) + { + if (!ServerEvents[name].ContainsKey(clientId)) + { + continue; + } + + if (ServerEvents[name][clientId].IsForGroup(groups)) + { + ServerEvents[name][clientId].Context.Response.SendSseEvent(eventType, data, id); + } + } + }, CancellationToken); + } + + public void CloseSseConnection(string name, string[] groups, string[] clientIds) + { + Task.Factory.StartNew(() => + { + if (!ServerEvents.ContainsKey(name)) + { + return; + } + + if (clientIds == default(string[]) || clientIds.Length == 0) + { + clientIds = ServerEvents[name].Keys.ToArray(); + } + + foreach (var clientId in clientIds) + { + if (!ServerEvents[name].ContainsKey(clientId)) + { + continue; + } + + if (ServerEvents[name][clientId].IsForGroup(groups)) + { + ServerEvents[name][clientId].Context.Response.CloseSseConnection(); + } + } + }, CancellationToken); + } + + public bool TestSseConnectionExists(string name, string clientId) + { + // check name + if (!ServerEvents.ContainsKey(name)) + { + return false; + } + + // check clientId + if (!string.IsNullOrEmpty(clientId) && !ServerEvents[name].ContainsKey(clientId)) + { + return false; + } + + // exists + return true; + } + public PodeServerSignal GetServerSignal(CancellationToken cancellationToken = default(CancellationToken)) { return ServerSignals.Get(cancellationToken); @@ -187,11 +288,26 @@ protected override void Close() PodeHelpers.WriteErrorMessage($"Closing signals", this, PodeLoggingLevel.Verbose); foreach (var _signal in Signals.Values.ToArray()) { - _signal.Context.Dispose(true); + _signal.Dispose(); } Signals.Clear(); PodeHelpers.WriteErrorMessage($"Closed signals", this, PodeLoggingLevel.Verbose); + + // close connected server events + PodeHelpers.WriteErrorMessage($"Closing server events", this, PodeLoggingLevel.Verbose); + foreach (var _sseName in ServerEvents.Values.ToArray()) + { + foreach (var _sse in _sseName.Values.ToArray()) + { + _sse.Dispose(); + } + + _sseName.Clear(); + } + + ServerEvents.Clear(); + PodeHelpers.WriteErrorMessage($"Closed server events", this, PodeLoggingLevel.Verbose); } } } \ No newline at end of file diff --git a/src/Listener/PodeResponse.cs b/src/Listener/PodeResponse.cs index a56963c6b..3c42a9865 100644 --- a/src/Listener/PodeResponse.cs +++ b/src/Listener/PodeResponse.cs @@ -14,12 +14,24 @@ public class PodeResponse : IDisposable public int StatusCode = 200; public bool SendChunked = false; public MemoryStream OutputStream { get; private set; } - public bool Sent { get; private set; } public bool IsDisposed { get; private set; } private PodeContext Context; private PodeRequest Request { get => Context.Request; } + public PodeSseScope SseScope { get; private set; } = PodeSseScope.None; + public bool SseEnabled + { + get => SseScope != PodeSseScope.None; + } + + public bool SentHeaders { get; private set; } + public bool SentBody { get; private set; } + public bool Sent + { + get => SentHeaders && SentBody; + } + private string _statusDesc = string.Empty; public string StatusDescription { @@ -73,43 +85,17 @@ public PodeResponse() public void Send() { - if (Sent || IsDisposed) + if (Sent || IsDisposed || (SentHeaders && SseEnabled)) { return; } PodeHelpers.WriteErrorMessage($"Sending response", Context.Listener, PodeLoggingLevel.Verbose, Context); - Sent = true; try { - // start building the response message - var message = HttpResponseLine; - - // default headers - SetDefaultHeaders(); - - // write the response headers - if (!Context.IsTimeout) - { - message += BuildHeaders(Headers); - } - - var buffer = Encoding.GetBytes(message); - - // stream response output - if (Request.InputStream.CanWrite) - { - Request.InputStream.WriteAsync(buffer, 0, buffer.Length).Wait(Context.Listener.CancellationToken); - - if (!Context.IsTimeout && OutputStream.Length > 0) - { - OutputStream.WriteTo(Request.InputStream); - } - } - - message = string.Empty; - buffer = default(byte[]); + SendHeaders(Context.IsTimeout); + SendBody(Context.IsTimeout); PodeHelpers.WriteErrorMessage($"Response sent", Context.Listener, PodeLoggingLevel.Verbose, Context); } catch (OperationCanceledException) {} @@ -125,42 +111,23 @@ public void Send() } finally { - Request.InputStream.Flush(); + Flush(); } } public void SendTimeout() { - if (Sent || IsDisposed) + if (SentHeaders || IsDisposed) { return; } PodeHelpers.WriteErrorMessage($"Sending response timed-out", Context.Listener, PodeLoggingLevel.Verbose, Context); - Sent = true; StatusCode = 408; try { - // start building the response message - var message = HttpResponseLine; - - // default headers - Headers.Clear(); - SetDefaultHeaders(); - - // write the response headers - message += BuildHeaders(Headers); - var buffer = Encoding.GetBytes(message); - - // stream response output - if (Request.InputStream.CanWrite) - { - Request.InputStream.WriteAsync(buffer, 0, buffer.Length).Wait(Context.Listener.CancellationToken); - } - - message = string.Empty; - buffer = default(byte[]); + SendHeaders(true); PodeHelpers.WriteErrorMessage($"Response timed-out sent", Context.Listener, PodeLoggingLevel.Verbose, Context); } catch (OperationCanceledException) {} @@ -175,11 +142,139 @@ public void SendTimeout() throw; } finally + { + Flush(); + } + } + + private void SendHeaders(bool timeout) + { + if (SentHeaders || !Request.InputStream.CanWrite) + { + return; + } + + // default headers + if (timeout) + { + Headers.Clear(); + } + + SetDefaultHeaders(); + + // stream response output + var buffer = Encoding.GetBytes(BuildHeaders(Headers)); + Request.InputStream.WriteAsync(buffer, 0, buffer.Length).Wait(Context.Listener.CancellationToken); + buffer = default(byte[]); + SentHeaders = true; + } + + private void SendBody(bool timeout) + { + if (SentBody || SseEnabled || !Request.InputStream.CanWrite) + { + return; + } + + // stream response output + if (!timeout && OutputStream.Length > 0) + { + OutputStream.WriteTo(Request.InputStream); + } + + SentBody = true; + } + + public void Flush() + { + if (Request.InputStream.CanWrite) { Request.InputStream.Flush(); } } + public string SetSseConnection(PodeSseScope scope, string clientId, string name, string group, int retry, bool allowAllOrigins) + { + // do nothing for no scope + if (scope == PodeSseScope.None) + { + return null; + } + + // cancel timeout + Context.CancelTimeout(); + SseScope = scope; + + // set appropriate SSE headers + Headers.Clear(); + ContentType = "text/event-stream"; + Headers.Add("Cache-Control", "no-cache"); + Headers.Add("Connection", "keep-alive"); + + if (allowAllOrigins) + { + Headers.Add("Access-Control-Allow-Origin", "*"); + } + + // generate clientId + if (string.IsNullOrEmpty(clientId)) + { + clientId = PodeHelpers.NewGuid(); + } + + Headers.Set("X-Pode-Sse-Client-Id", clientId); + Headers.Set("X-Pode-Sse-Name", name); + + if (!string.IsNullOrEmpty(group)) + { + Headers.Set("X-Pode-Sse-Group", group); + } + + // send headers, and open event + Send(); + SendSseRetry(retry); + SendSseEvent("pode.open", $"{{\"clientId\":\"{clientId}\",\"group\":\"{group}\",\"name\":\"{name}\"}}"); + + // if global, cache connection in listener + if (scope == PodeSseScope.Global) + { + Context.Listener.AddSseConnection(new PodeServerEvent(Context, name, group, clientId)); + } + + // return clientId + return clientId; + } + + public void CloseSseConnection() + { + SendSseEvent("pode.close", string.Empty); + } + + public void SendSseEvent(string eventType, string data, string id = null) + { + if (!string.IsNullOrEmpty(id)) + { + WriteLine($"id: {id}"); + } + + if (!string.IsNullOrEmpty(eventType)) + { + WriteLine($"event: {eventType}"); + } + + WriteLine($"data: {data}{PodeHelpers.NEW_LINE}", true); + } + + public void SendSseRetry(int retry) + { + if (retry <= 0) + { + return; + } + + WriteLine($"retry: {retry}", true); + } + public void SendSignal(PodeServerSignal signal) { if (!string.IsNullOrEmpty(signal.Value)) @@ -242,13 +337,12 @@ public void WriteFrame(string message, PodeWsOpCode opCode = PodeWsOpCode.Text, public void WriteLine(string message, bool flush = false) { - var msgBytes = Encoding.GetBytes($"{message}{PodeHelpers.NEW_LINE}"); - Write(msgBytes, flush); + Write(Encoding.GetBytes($"{message}{PodeHelpers.NEW_LINE}"), flush); } public void Write(byte[] buffer, bool flush = false) { - if (IsDisposed) + if (Request.IsDisposed || !Request.InputStream.CanWrite) { return; } @@ -259,7 +353,7 @@ public void Write(byte[] buffer, bool flush = false) if (flush) { - Request.InputStream.Flush(); + Flush(); } } catch (OperationCanceledException) {} @@ -278,7 +372,7 @@ public void Write(byte[] buffer, bool flush = false) private void SetDefaultHeaders() { // ensure content length (remove for 1xx responses, ensure added otherwise) - if (StatusCode < 200) + if (StatusCode < 200 || SseEnabled) { Headers.Remove("Content-Length"); } @@ -323,7 +417,7 @@ private void SetDefaultHeaders() Headers.Add("X-Pode-ContextId", Context.ID); // close the connection, only if request didn't specify keep-alive - if (!Context.IsKeepAlive && !Context.IsWebSocket) + if (!Context.IsKeepAlive && !Context.IsWebSocket && !SseEnabled) { if (Headers.ContainsKey("Connection")) { @@ -336,24 +430,19 @@ private void SetDefaultHeaders() private string BuildHeaders(PodeResponseHeaders headers) { - if (headers.Count == 0) - { - return PodeHelpers.NEW_LINE; - } - - var str = string.Empty; + var builder = new StringBuilder(); + builder.Append(HttpResponseLine); foreach (var key in headers.Keys) { - var values = headers.Get(key); - foreach (var value in values) + foreach (var value in headers.Get(key)) { - str += $"{key}: {value}{PodeHelpers.NEW_LINE}"; + builder.Append($"{key}: {value}{PodeHelpers.NEW_LINE}"); } } - str += PodeHelpers.NEW_LINE; - return str; + builder.Append(PodeHelpers.NEW_LINE); + return builder.ToString(); } public void SetContext(PodeContext context) diff --git a/src/Listener/PodeServerEvent.cs b/src/Listener/PodeServerEvent.cs new file mode 100644 index 000000000..a251b27c5 --- /dev/null +++ b/src/Listener/PodeServerEvent.cs @@ -0,0 +1,43 @@ +using System; +using System.Linq; + +namespace Pode +{ + public class PodeServerEvent : IDisposable + { + public PodeContext Context { get; private set; } + public string Name { get; private set; } + public string Group { get; private set; } + public string ClientId { get; private set; } + public DateTime Timestamp { get; private set; } + + public PodeServerEvent(PodeContext context, string name, string group, string clientId) + { + Context = context; + Name = name; + Group = group; + ClientId = clientId; + Timestamp = DateTime.UtcNow; + } + + public bool IsForGroup(string[] groups) + { + if (groups == default(string[]) || groups.Length == 0) + { + return true; + } + + if (string.IsNullOrEmpty(Group)) + { + return false; + } + + return groups.Any(x => x.Equals(Group, StringComparison.OrdinalIgnoreCase)); + } + + public void Dispose() + { + Context.Dispose(true); + } + } +} \ No newline at end of file diff --git a/src/Listener/PodeSignal.cs b/src/Listener/PodeSignal.cs index 369e57547..6f653ac35 100644 --- a/src/Listener/PodeSignal.cs +++ b/src/Listener/PodeSignal.cs @@ -2,7 +2,7 @@ namespace Pode { - public class PodeSignal + public class PodeSignal : IDisposable { public PodeContext Context { get; private set; } public string Path { get; private set; } @@ -16,5 +16,10 @@ public PodeSignal(PodeContext context, string path, string clientId) ClientId = clientId; Timestamp = DateTime.UtcNow; } + + public void Dispose() + { + Context.Dispose(true); + } } } \ No newline at end of file diff --git a/src/Listener/PodeSmtpRequest.cs b/src/Listener/PodeSmtpRequest.cs index a2b49eadc..8039d45f3 100644 --- a/src/Listener/PodeSmtpRequest.cs +++ b/src/Listener/PodeSmtpRequest.cs @@ -398,7 +398,7 @@ private void ParseBoundary() var contentType = $"{headers["Content-Type"]}"; var contentEncoding = $"{headers["Content-Transfer-Encoding"]}"; - // get the boundary + // get the boundary var body = ParseBody(boundaryBody, Boundary); var bodyBytes = ConvertBodyEncoding(body, contentEncoding); diff --git a/src/Listener/PodeSocket.cs b/src/Listener/PodeSocket.cs index ac2588153..8f8b5fd7d 100644 --- a/src/Listener/PodeSocket.cs +++ b/src/Listener/PodeSocket.cs @@ -13,17 +13,16 @@ namespace Pode { public class PodeSocket : PodeProtocol, IDisposable { - public IPAddress IPAddress { get; private set; } + public string Name { get; private set; } public List Hostnames { get; private set; } - public int Port { get; private set; } - public IPEndPoint Endpoint { get; private set; } + public IList Endpoints { get; private set; } public X509Certificate Certificate { get; private set; } public bool AllowClientCertificate { get; private set; } public SslProtocols Protocols { get; private set; } public PodeTlsMode TlsMode { get; private set; } - public Socket Socket { get; private set; } public string AcknowledgeMessage { get; set; } public bool CRLFMessageEnd { get; set; } + public bool DualMode { get; private set; } private ConcurrentQueue AcceptConnections; private ConcurrentQueue ReceiveConnections; @@ -33,41 +32,50 @@ public class PodeSocket : PodeProtocol, IDisposable public bool IsSsl { - get => (Certificate != default(X509Certificate)); + get => Certificate != default(X509Certificate); } + private int _receiveTimeout; public int ReceiveTimeout { - get => Socket.ReceiveTimeout; - set => Socket.ReceiveTimeout = value; + get => _receiveTimeout; + set + { + _receiveTimeout = value; + foreach (var ep in Endpoints) + { + ep.ReceiveTimeout = value; + } + } } public bool HasHostnames => Hostnames.Any(); public string Hostname { - get => (HasHostnames ? Hostnames[0] : IPAddress.ToString()); + get => HasHostnames ? Hostnames[0] : Endpoints[0].IPAddress.ToString(); } - public PodeSocket(IPAddress ipAddress, int port, SslProtocols protocols, PodeProtocolType type, X509Certificate certificate = null, bool allowClientCertificate = false, PodeTlsMode tlsMode = PodeTlsMode.Implicit) + public PodeSocket(string name, IPAddress[] ipAddress, int port, SslProtocols protocols, PodeProtocolType type, X509Certificate certificate = null, bool allowClientCertificate = false, PodeTlsMode tlsMode = PodeTlsMode.Implicit, bool dualMode = false) : base(type) { - IPAddress = ipAddress; - Port = port; + Name = name; Certificate = certificate; AllowClientCertificate = allowClientCertificate; TlsMode = tlsMode; Protocols = protocols; Hostnames = new List(); - Endpoint = new IPEndPoint(ipAddress, port); + DualMode = dualMode; AcceptConnections = new ConcurrentQueue(); ReceiveConnections = new ConcurrentQueue(); PendingSockets = new Dictionary(); + Endpoints = new List(); - Socket = new Socket(Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); - Socket.ReceiveTimeout = 100; - Socket.NoDelay = true; + foreach (var addr in ipAddress) + { + Endpoints.Add(new PodeEndpoint(this, addr, port, dualMode)); + } } public void BindListener(PodeListener listener) @@ -77,25 +85,39 @@ public void BindListener(PodeListener listener) public void Listen() { - Socket.Bind(Endpoint); - Socket.Listen(int.MaxValue); + foreach (var ep in Endpoints) + { + ep.Listen(); + } } public void Start() { - var args = default(SocketAsyncEventArgs); - if (!AcceptConnections.TryDequeue(out args)) + foreach (var ep in Endpoints) + { + StartEndpoint(ep); + } + } + + private void StartEndpoint(PodeEndpoint endpoint) + { + if (endpoint.IsDisposed) + { + return; + } + + if (!AcceptConnections.TryDequeue(out SocketAsyncEventArgs args)) { args = NewAcceptConnection(); } - args.AcceptSocket = default(Socket); - args.UserToken = this; - var raised = false; + args.AcceptSocket = default; + args.UserToken = endpoint; + bool raised; try { - raised = Socket.AcceptAsync(args); + raised = endpoint.AcceptAsync(args); } catch (ObjectDisposedException) { @@ -131,7 +153,7 @@ public void StartReceive(PodeContext context) private void StartReceive(SocketAsyncEventArgs args) { args.SetBuffer(new byte[0], 0, 0); - var raised = false; + bool raised; try { @@ -158,11 +180,11 @@ private void ProcessAccept(SocketAsyncEventArgs args) { // get details var accepted = args.AcceptSocket; - var socket = (PodeSocket)args.UserToken; + var endpoint = (PodeEndpoint)args.UserToken; var error = args.SocketError; // start the socket again - socket.Start(); + StartEndpoint(endpoint); // close socket if not successful, or if listener is stopped - close now! if ((accepted == default(Socket)) || (error != SocketError.Success) || (!Listener.IsConnected)) @@ -229,8 +251,8 @@ private void ProcessReceive(SocketAsyncEventArgs args) context.RenewTimeoutToken(); Task.Factory.StartNew(() => context.Receive(), context.ContextTimeoutToken.Token); } - catch (OperationCanceledException) {} - catch (IOException) {} + catch (OperationCanceledException) { } + catch (IOException) { } catch (AggregateException aex) { PodeHelpers.HandleAggregateException(aex, Listener, PodeLoggingLevel.Error, true); @@ -340,9 +362,7 @@ private SocketAsyncEventArgs NewReceiveConnection() private SocketAsyncEventArgs GetReceiveConnection() { - var args = default(SocketAsyncEventArgs); - - if (!ReceiveConnections.TryDequeue(out args)) + if (!ReceiveConnections.TryDequeue(out SocketAsyncEventArgs args)) { args = NewReceiveConnection(); } @@ -397,7 +417,13 @@ public bool CheckHostname(string hostname) public void Dispose() { - CloseSocket(Socket); + // close endpoints + foreach (var ep in Endpoints) + { + ep.Dispose(); + } + + Endpoints.Clear(); // close receiving contexts/sockets try @@ -407,6 +433,8 @@ public void Dispose() { CloseSocket(_sockets[i]); } + + PendingSockets.Clear(); } catch (Exception ex) { @@ -436,7 +464,6 @@ public static void CloseSocket(Socket socket) // dispose socket.Close(); socket.Dispose(); - socket = default(Socket); } private void ClearSocketAsyncEvent(SocketAsyncEventArgs e) @@ -448,7 +475,18 @@ private void ClearSocketAsyncEvent(SocketAsyncEventArgs e) public new bool Equals(object obj) { var _socket = (PodeSocket)obj; - return (Endpoint.ToString() == _socket.Endpoint.ToString() && Port == _socket.Port); + foreach (var ep in Endpoints) + { + foreach (var _oEp in _socket.Endpoints) + { + if (!ep.Equals(_oEp)) + { + return false; + } + } + } + + return true; } } } \ No newline at end of file diff --git a/src/Listener/PodeSseScope.cs b/src/Listener/PodeSseScope.cs new file mode 100644 index 000000000..8e57cb611 --- /dev/null +++ b/src/Listener/PodeSseScope.cs @@ -0,0 +1,9 @@ +namespace Pode +{ + public enum PodeSseScope + { + None, + Local, + Global + } +} \ No newline at end of file diff --git a/src/Misc/default-doc-bookmarks.html.pode b/src/Misc/default-doc-bookmarks.html.pode new file mode 100644 index 000000000..d9418eacc --- /dev/null +++ b/src/Misc/default-doc-bookmarks.html.pode @@ -0,0 +1,280 @@ + + + + + OpenAPI Documentation Bookmarks + + + + + + + + + + + +

$($data.Title)

+

Documentation

+ + +
+

OpenAPI Definition

+ + +
+ +
+ + +
+ +
+
Loading JSON content...
+
+ +
+ 🧡 Powered by Pode +
+ + + + \ No newline at end of file diff --git a/src/Misc/default-explorer.html.pode b/src/Misc/default-explorer.html.pode new file mode 100644 index 000000000..7954646d5 --- /dev/null +++ b/src/Misc/default-explorer.html.pode @@ -0,0 +1,60 @@ + + + + + + + $($data.Title) + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Misc/default-file-browsing.html.pode b/src/Misc/default-file-browsing.html.pode new file mode 100644 index 000000000..2c5c6103b --- /dev/null +++ b/src/Misc/default-file-browsing.html.pode @@ -0,0 +1,221 @@ + + + + File Browser:$($Data.Path) + + + + + + + + + +
+
+
+ + + + $($Data.fileContent) +
+

+ 🧡 Powered by Pode +

+
+ + + + \ No newline at end of file diff --git a/src/Misc/default-rapidoc.html.pode b/src/Misc/default-rapidoc.html.pode new file mode 100644 index 000000000..a12aa9b62 --- /dev/null +++ b/src/Misc/default-rapidoc.html.pode @@ -0,0 +1,16 @@ + + + + + $($data.Title) + + + + + + + + + + \ No newline at end of file diff --git a/src/Misc/default-rapipdf.html.pode b/src/Misc/default-rapipdf.html.pode new file mode 100644 index 000000000..1268b051c --- /dev/null +++ b/src/Misc/default-rapipdf.html.pode @@ -0,0 +1,150 @@ + + + + + RapiPdf Web Page + + + + + + + + +
+

RapiPdf Configuration

+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
DescriptionValue
Colour used for headings of main sections in PDF
Colour used for sub-headings
Title of the generated PDF
Text to be printed at the bottom of every page
Include the info section in the generated PDF? + + +
Include a table of contents in the generated PDF? + + +
Include the security section in the generated PDF? + + +
Include all API details in the generated PDF? + + +
Include a list of all APIs and their summaries at the end of the generated PDF? + + +
Include OpenAPI specified examples in the generated PDF? + + +
+
+ +
+ +
+
+ + + + + + \ No newline at end of file diff --git a/src/Misc/default-redoc.html.pode b/src/Misc/default-redoc.html.pode index f179bf848..929975a08 100644 --- a/src/Misc/default-redoc.html.pode +++ b/src/Misc/default-redoc.html.pode @@ -1,20 +1,22 @@ - - - $($data.Title) - - - + + + $($data.Title) + + + + + + + + + + + - - - - - - \ No newline at end of file diff --git a/src/Misc/default-stoplight.html.pode b/src/Misc/default-stoplight.html.pode new file mode 100644 index 000000000..ce94f72ec --- /dev/null +++ b/src/Misc/default-stoplight.html.pode @@ -0,0 +1,19 @@ + + + + + + + $($data.Title) + + + + + + + + + + + + \ No newline at end of file diff --git a/src/Misc/default-swagger-editor.html.pode b/src/Misc/default-swagger-editor.html.pode new file mode 100644 index 000000000..31f52981b --- /dev/null +++ b/src/Misc/default-swagger-editor.html.pode @@ -0,0 +1,106 @@ + + + + + + Swagger Editor + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Misc/default-swagger.html.pode b/src/Misc/default-swagger.html.pode index 7cdd320f0..15b3ebefa 100644 --- a/src/Misc/default-swagger.html.pode +++ b/src/Misc/default-swagger.html.pode @@ -1,11 +1,11 @@ - - + + $($data.Title) - - + +