GitHub.psm1

[Cmdletbinding()]
param()

$scriptName = $MyInvocation.MyCommand.Name
Write-Verbose "[$scriptName] Importing subcomponents"

#region - Data import
Write-Verbose "[$scriptName] - [data] - Processing folder"
$dataFolder = (Join-Path $PSScriptRoot 'data')
Write-Verbose "[$scriptName] - [data] - [$dataFolder]"
Get-ChildItem -Path "$dataFolder" -Recurse -Force -Include '*.psd1' | ForEach-Object {
    Write-Verbose "[$scriptName] - [data] - [$($_.Name)] - Importing"
    New-Variable -Name $_.BaseName -Value (Import-PowerShellDataFile -Path $_.FullName) -Force
    Write-Verbose "[$scriptName] - [data] - [$($_.Name)] - Done"
}

Write-Verbose "[$scriptName] - [data] - Done"
#endregion - Data import

#region - From private
Write-Verbose "[$scriptName] - [private] - Processing folder"

#region - From private/Auth
Write-Verbose "[$scriptName] - [private/Auth] - Processing folder"

#region - From private/Auth/DeviceFlow
Write-Verbose "[$scriptName] - [private/Auth/DeviceFlow] - Processing folder"

#region - From private/Auth/DeviceFlow/Invoke-GitHubDeviceFlowLogin.ps1
Write-Verbose "[$scriptName] - [private/Auth/DeviceFlow/Invoke-GitHubDeviceFlowLogin.ps1] - Importing"

function Invoke-GitHubDeviceFlowLogin {
    <#
        .SYNOPSIS
        Starts the GitHub Device Flow login process.

        .DESCRIPTION
        Starts the GitHub Device Flow login process. This will prompt the user to visit a URL and enter a code.

        .EXAMPLE
        Invoke-GitHubDeviceFlowLogin

        This will start the GitHub Device Flow login process.
        The user gets prompted to visit a URL and enter a code.

        .NOTES
        For more info about the Device Flow visit:
        https://docs.github.com/en/apps/creating-github-apps/writing-code-for-a-github-app/building-a-cli-with-a-github-app
        https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#device-flow
    #>

    [OutputType([void])]
    [CmdletBinding()]
    param(
        # The Client ID of the GitHub App.
        [Parameter(Mandatory)]
        [string] $ClientID,

        # The scope of the access token, when using OAuth authentication.
        # Provide the list of scopes as space-separated values.
        # For more information on scopes visit:
        # https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
        [Parameter()]
        [string] $Scope,

        # The refresh token to use for re-authentication.
        [Parameter()]
        [securestring] $RefreshToken
    )

    do {
        if ($RefreshToken) {
            $tokenResponse = Wait-GitHubAccessToken -ClientID $ClientID -RefreshToken $RefreshToken
        } else {
            $deviceCodeResponse = Request-GitHubDeviceCode -ClientID $ClientID -Scope $Scope

            $deviceCode = $deviceCodeResponse.device_code
            $interval = $deviceCodeResponse.interval
            $userCode = $deviceCodeResponse.user_code
            $verificationUri = $deviceCodeResponse.verification_uri

            Write-Host '! ' -ForegroundColor DarkYellow -NoNewline
            Write-Host "We added the code to your clipboard: [$userCode]"
            $userCode | Set-Clipboard
            Read-Host 'Press Enter to open github.com in your browser...'
            Start-Process $verificationUri

            $tokenResponse = Wait-GitHubAccessToken -DeviceCode $deviceCode -ClientID $ClientID -Interval $interval
        }
    } while ($tokenResponse.error)
    $tokenResponse
}

Write-Verbose "[$scriptName] - [private/Auth/DeviceFlow/Invoke-GitHubDeviceFlowLogin.ps1] - Done"
#endregion - From private/Auth/DeviceFlow/Invoke-GitHubDeviceFlowLogin.ps1
#region - From private/Auth/DeviceFlow/Request-GitHubAccessToken.ps1
Write-Verbose "[$scriptName] - [private/Auth/DeviceFlow/Request-GitHubAccessToken.ps1] - Importing"

function Request-GitHubAccessToken {
    <#
        .SYNOPSIS
        Request a GitHub token using the Device Flow.

        .DESCRIPTION
        Request a GitHub token using the Device Flow.
        This will poll the GitHub API until the user has entered the code.

        .EXAMPLE
        Request-GitHubAccessToken -DeviceCode $deviceCode -ClientID $ClientID

        This will poll the GitHub API until the user has entered the code.

        .NOTES
        For more info about the Device Flow visit:
        https://docs.github.com/en/apps/creating-github-apps/writing-code-for-a-github-app/building-a-cli-with-a-github-app
    #>

    [OutputType([PSCustomObject])]
    [CmdletBinding(DefaultParameterSetName = 'DeviceFlow')]
    param(
        # The Client ID of the GitHub App.
        [Parameter(Mandatory)]
        [string] $ClientID,

        # The 'device_code' used to request the access token.
        [Parameter(
            Mandatory,
            ParameterSetName = 'DeviceFlow'
        )]
        [string] $DeviceCode,

        # The refresh token used create a new access token.
        [Parameter(
            Mandatory,
            ParameterSetName = 'RefreshToken'
        )]
        [securestring] $RefreshToken
    )

    $body = @{
        'client_id' = $ClientID
    }

    if ($PSBoundParameters.ContainsKey('RefreshToken')) {
        $body += @{
            'refresh_token' = (ConvertFrom-SecureString $RefreshToken -AsPlainText)
            'grant_type'    = 'refresh_token'
        }
    }

    if ($PSBoundParameters.ContainsKey('DeviceCode')) {
        $body += @{
            'device_code' = $DeviceCode
            'grant_type'  = 'urn:ietf:params:oauth:grant-type:device_code'
        }
    }

    $RESTParams = @{
        Uri     = 'https://github.com/login/oauth/access_token'
        Method  = 'POST'
        Body    = $body
        Headers = @{ 'Accept' = 'application/json' }
    }

    try {
        Write-Verbose ($RESTParams.GetEnumerator() | Out-String)

        $tokenResponse = Invoke-RestMethod @RESTParams -Verbose:$false

        Write-Verbose ($tokenResponse | ConvertTo-Json | Out-String)
        return $tokenResponse
    } catch {
        Write-Error $_
        throw $_
    }
}

Write-Verbose "[$scriptName] - [private/Auth/DeviceFlow/Request-GitHubAccessToken.ps1] - Done"
#endregion - From private/Auth/DeviceFlow/Request-GitHubAccessToken.ps1
#region - From private/Auth/DeviceFlow/Request-GitHubDeviceCode.ps1
Write-Verbose "[$scriptName] - [private/Auth/DeviceFlow/Request-GitHubDeviceCode.ps1] - Importing"

function Request-GitHubDeviceCode {
    <#
        .SYNOPSIS
        Request a GitHub Device Code.

        .DESCRIPTION
        Request a GitHub Device Code.

        .EXAMPLE
        Request-GitHubDeviceCode -ClientID $ClientID -Mode $Mode

        This will request a GitHub Device Code.

        .NOTES
        For more info about the Device Flow visit:
        https://docs.github.com/en/apps/creating-github-apps/writing-code-for-a-github-app/building-a-cli-with-a-github-app
    #>

    [OutputType([PSCustomObject])]
    [CmdletBinding()]
    param(
        # The Client ID of the GitHub App.
        [Parameter(Mandatory)]
        [string] $ClientID,

        # The scope of the access token, when using OAuth authentication.
        # Provide the list of scopes as space-separated values.
        # For more information on scopes visit:
        # https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
        [Parameter()]
        [string] $Scope = 'gist, read:org, repo, workflow'
    )

    $headers = @{
        Accept = 'application/json'
    }

    $body = @{
        client_id = $ClientID
        scope     = $Scope
    }

    $RESTParams = @{
        Uri     = 'https://github.com/login/device/code'
        Method  = 'POST'
        Body    = $body
        Headers = $headers
    }

    try {
        Write-Verbose ($RESTParams.GetEnumerator() | Out-String)

        $deviceCodeResponse = Invoke-RestMethod @RESTParams -Verbose:$false
        return $deviceCodeResponse
    } catch {
        Write-Error $_
        throw $_
    }
}

Write-Verbose "[$scriptName] - [private/Auth/DeviceFlow/Request-GitHubDeviceCode.ps1] - Done"
#endregion - From private/Auth/DeviceFlow/Request-GitHubDeviceCode.ps1
#region - From private/Auth/DeviceFlow/Wait-GitHubAccessToken.ps1
Write-Verbose "[$scriptName] - [private/Auth/DeviceFlow/Wait-GitHubAccessToken.ps1] - Importing"

function Wait-GitHubAccessToken {
    <#
        .SYNOPSIS
        Waits for the GitHub Device Flow to complete.

        .DESCRIPTION
        Waits for the GitHub Device Flow to complete.
        This will poll the GitHub API until the user has entered the code.

        .EXAMPLE
        Wait-GitHubAccessToken -DeviceCode $deviceCode -ClientID $ClientID -Interval $interval

        This will poll the GitHub API until the user has entered the code.

        .EXAMPLE
        Wait-GitHubAccessToken -Refresh -ClientID $ClientID

        .NOTES
        For more info about the Device Flow visit:
        https://docs.github.com/en/apps/creating-github-apps/writing-code-for-a-github-app/building-a-cli-with-a-github-app
    #>

    [OutputType([PSCustomObject])]
    [CmdletBinding(DefaultParameterSetName = 'DeviceFlow')]
    param(
        # The Client ID of the GitHub App.
        [Parameter(Mandatory)]
        [string] $ClientID,

        # The device code used to request the access token.
        [Parameter(
            Mandatory,
            ParameterSetName = 'DeviceFlow'
        )]
        [string] $DeviceCode,

        # The refresh token used to request a new access token.
        [Parameter(
            Mandatory,
            ParameterSetName = 'RefreshToken'
        )]
        [securestring] $RefreshToken,

        # The interval to wait between polling for the token.
        [Parameter()]
        [int] $Interval = 5

    )

    do {
        if ($RefreshToken) {
            $response = Request-GitHubAccessToken -ClientID $ClientID -RefreshToken $RefreshToken
        } else {
            $response = Request-GitHubAccessToken -ClientID $ClientID -DeviceCode $DeviceCode
        }
        if ($response.error) {
            switch ($response.error) {
                'authorization_pending' {
                    # The user has not yet entered the code.
                    # Wait, then poll again.
                    Write-Verbose $response.error_description
                    Start-Sleep -Seconds $interval
                    continue
                }
                'slow_down' {
                    # The app polled too fast.
                    # Wait for the interval plus 5 seconds, then poll again.
                    Write-Verbose $response.error_description
                    Start-Sleep -Seconds ($interval + 5)
                    continue
                }
                'expired_token' {
                    # The 'device_code' expired, and the process needs to restart.
                    Write-Error $response.error_description
                    exit 1
                }
                'unsupported_grant_type' {
                    # The 'grant_type' is not supported.
                    Write-Error $response.error_description
                    exit 1
                }
                'incorrect_client_credentials' {
                    # The 'client_id' is not valid.
                    Write-Error $response.error_description
                    exit 1
                }
                'incorrect_device_code' {
                    # The 'device_code' is not valid.
                    Write-Error $response.error_description
                    exit 2
                }
                'access_denied' {
                    # The user cancelled the process. Stop polling.
                    Write-Error $response.error_description
                    exit 1
                }
                'device_flow_disabled' {
                    # The GitHub App does not support the Device Flow.
                    Write-Error $response.error_description
                    exit 1
                }
                default {
                    # The response contains an access token. Stop polling.
                    Write-Error 'Unknown error:'
                    Write-Error $response.error
                    Write-Error $response.error_description
                    Write-Error $response.error_uri
                    break
                }
            }
        }
    } until ($response.access_token)
    $response
}

Write-Verbose "[$scriptName] - [private/Auth/DeviceFlow/Wait-GitHubAccessToken.ps1] - Done"
#endregion - From private/Auth/DeviceFlow/Wait-GitHubAccessToken.ps1

Write-Verbose "[$scriptName] - [private/Auth/DeviceFlow] - Done"
#endregion - From private/Auth/DeviceFlow

Write-Verbose "[$scriptName] - [private/Auth] - Done"
#endregion - From private/Auth
#region - From private/Config
Write-Verbose "[$scriptName] - [private/Config] - Processing folder"

#region - From private/Config/Initialize-SecretVault.ps1
Write-Verbose "[$scriptName] - [private/Config/Initialize-SecretVault.ps1] - Importing"

#Requires -Version 7.0
#Requires -Modules Microsoft.PowerShell.SecretManagement
#Requires -Modules Microsoft.PowerShell.SecretStore

function Initialize-SecretVault {
    <#
    .SYNOPSIS
    Initialize a secret vault.

    .DESCRIPTION
    Initialize a secret vault. If the vault does not exist, it will be created.

    .EXAMPLE
    Initialize-SecretVault -Name 'SecretStore' -Type 'Microsoft.PowerShell.SecretStore'

    Initializes a secret vault named 'SecretStore' using the 'Microsoft.PowerShell.SecretStore' module.

    .NOTES
    For more information about secret vaults, see https://learn.microsoft.com/en-us/powershell/utility-modules/secretmanagement/overview?view=ps-modules
    #>


    [OutputType([void])]
    [CmdletBinding()]
    param (
        # The name of the secret vault.
        [Parameter()]
        [string] $Name = 'SecretStore',

        # The type of the secret vault.
        [Parameter()]
        [Alias('ModuleName')]
        [string] $Type = 'Microsoft.PowerShell.SecretStore'
    )

    $functionName = $MyInvocation.MyCommand.Name

    $vault = Get-SecretVault | Where-Object { $_.ModuleName -eq $Type }
    if (-not $vault) {
        Write-Verbose "[$functionName] - [$Type] - Registering"

        switch ($Type) {
            'Microsoft.PowerShell.SecretStore' {
                $vaultParameters = @{
                    Authentication  = 'None'
                    PasswordTimeout = -1
                    Interaction     = 'None'
                    Scope           = 'CurrentUser'
                    WarningAction   = 'SilentlyContinue'
                    Confirm         = $false
                    Force           = $true
                }
                Reset-SecretStore @vaultParameters
            }
        }
        Write-Verbose "[$functionName] - [$Type] - Done"
    } else {
        Write-Verbose "[$functionName] - [$Type] - already registered"
    }

    $secretStore = Get-SecretVault | Where-Object { $_.Name -eq $Name }
    if (-not $secretStore) {
        Write-Verbose "[$functionName] - [$Name] - Registering"
        $secretVault = @{
            Name         = $Name
            ModuleName   = $Type
            DefaultVault = $true
            Description  = 'SecretStore'
        }
        Register-SecretVault @secretVault
        Write-Verbose "[$functionName] - [$Name] - Done"
    } else {
        Write-Verbose "[$functionName] - [$Name] - already registered"
    }
}

Write-Verbose "[$scriptName] - [private/Config/Initialize-SecretVault.ps1] - Done"
#endregion - From private/Config/Initialize-SecretVault.ps1
#region - From private/Config/Reset-GitHubConfig.ps1
Write-Verbose "[$scriptName] - [private/Config/Reset-GitHubConfig.ps1] - Importing"

function Reset-GitHubConfig {
    <#
        .SYNOPSIS
        Reset the GitHub configuration.

        .DESCRIPTION
        Reset the GitHub configuration. Specific scopes can be reset by using the Scope parameter.

        .EXAMPLE
        Reset-GitHubConfig

        Resets the entire GitHub configuration.

        .EXAMPLE
        Reset-GitHubConfig -Scope 'Auth'

        Resets the Auth related variables of the GitHub configuration.
    #>

    [Alias('Reset-GHConfig')]
    [OutputType([void])]
    [CmdletBinding()]
    param(
        # Reset the GitHub configuration for a specific scope.
        [Parameter()]
        [ValidateSet('Auth', 'All')]
        [string] $Scope = 'All'
    )

    Write-Verbose "Resetting GitHub configuration for scope '$Scope'..."
    switch ($Scope) {
        'Auth' {
            $Settings = @{
                AccessToken                = [securestring]::new()
                AccessTokenExpirationDate  = [datetime]::MinValue
                AccessTokenType            = ''
                AuthType                   = ''
                DeviceFlowType             = ''
                RefreshToken               = [securestring]::new()
                RefreshTokenExpirationDate = [datetime]::MinValue
                Scope                      = ''
            }
        }
        'All' {
            $Settings = @{
                AccessToken                = [securestring]::new()
                AccessTokenExpirationDate  = [datetime]::MinValue
                AccessTokenType            = ''
                ApiBaseUri                 = 'https://api.github.com'
                ApiVersion                 = '2022-11-28'
                AuthType                   = ''
                DeviceFlowType             = ''
                Owner                      = ''
                RefreshToken               = [securestring]::new()
                RefreshTokenExpirationDate = [datetime]::MinValue
                Repo                       = ''
                Scope                      = ''
                UserName                   = ''
            }
        }
    }
    Set-GitHubConfig @Settings
}

Write-Verbose "[$scriptName] - [private/Config/Reset-GitHubConfig.ps1] - Done"
#endregion - From private/Config/Reset-GitHubConfig.ps1

Write-Verbose "[$scriptName] - [private/Config] - Done"
#endregion - From private/Config

Write-Verbose "[$scriptName] - [private] - Done"
#endregion - From private
#region - From public
Write-Verbose "[$scriptName] - [public] - Processing folder"

#region - From public/API
Write-Verbose "[$scriptName] - [public/API] - Processing folder"

#region - From public/API/Invoke-GitHubAPI.ps1
Write-Verbose "[$scriptName] - [public/API/Invoke-GitHubAPI.ps1] - Importing"

function Invoke-GitHubAPI {
    <#
    .SYNOPSIS
    Calls the GitHub API using the provided parameters.

    .DESCRIPTION
    This function is a wrapper around Invoke-RestMethod tailored for calling GitHub's API.
    It automatically handles the endpoint URI construction, headers, and token authentication.

    .EXAMPLE
    Invoke-GitHubAPI -ApiEndpoint '/repos/user/repo/pulls' -Method GET

    Gets all open pull requests for the specified repository.

    .EXAMPLE
    Invoke-GitHubAPI -ApiEndpoint '/repos/user/repo/pulls' -Method GET -Body @{ state = 'open' }

    Gets all open pull requests for the specified repository, filtered by the 'state' parameter.

    .EXAMPLE
    Invoke-GitHubAPI -ApiEndpoint '/repos/user/repo/pulls' -Method GET -Body @{ state = 'open' } -Accept 'application/vnd.github.v3+json'

    Gets all open pull requests for the specified repository, filtered by the 'state' parameter, and using the specified 'Accept' header.
#>

    [CmdletBinding()]
    param (
        # The HTTP method to be used for the API request. It can be one of the following: GET, POST, PUT, DELETE, or PATCH.
        [Parameter()]
        [Microsoft.PowerShell.Commands.WebRequestMethod] $Method = 'GET',

        # The base URI for the GitHub API. This is usually 'https://api.github.com', but can be adjusted if necessary.
        [Parameter()]
        [string] $ApiBaseUri = (Get-GitHubConfig -Name ApiBaseUri -AsPlainText),

        # The specific endpoint for the API call, e.g., '/repos/user/repo/pulls'.
        [Parameter(Mandatory)]
        [string] $ApiEndpoint,

        # The body of the API request. This can be a hashtable or a string. If a hashtable is provided, it will be converted to JSON.
        [Parameter()]
        [Object] $Body,

        # The 'Accept' header for the API request. If not provided, the default will be used by GitHub's API.
        [Parameter()]
        [string] $Accept,

        # The secure token used for authentication in the GitHub API. It should be stored as a SecureString to ensure it's kept safe in memory.
        [Parameter()]
        [SecureString] $AccessToken = (Get-GitHubConfig -Name AccessToken),

        # The 'Content-Type' header for the API request. The default is 'application/vnd.github+json'.
        [Parameter()]
        [string] $ContentType = 'application/vnd.github+json',

        # The GitHub API version to be used. By default, it pulls from a configuration script variable.
        [Parameter()]
        [string] $Version = (Get-GitHubConfig -Name ApiVersion -AsPlainText)
    )

    $functionName = $MyInvocation.MyCommand.Name

    $headers = @{
        'Content-Type'         = $ContentType
        'X-GitHub-Api-Version' = $Version
        'Accept'               = $Accept
    }

    # Filter out null or empty headers
    $headers = $headers.GetEnumerator() | Where-Object { -not [string]::IsNullOrEmpty($_.Value) } | ForEach-Object {
        @{ $_.Key = $_.Value }
    }

    $AccessTokenAsPlainText = ConvertFrom-SecureString $AccessToken -AsPlainText
    $authorization = switch -Regex ($AccessTokenAsPlainText) {
        '^ghp_|^github_pat_' { "token $AccessTokenAsPlainText" }
        '^ghu_|^gho_' { "Bearer $AccessTokenAsPlainText" }
        default {
            $tokenPrefix = $AccessTokenAsPlainText -replace '_.*$', '_*'
            $errorMessage = "Unexpected AccessToken format: $tokenPrefix"
            Write-Error $errorMessage
            throw $errorMessage
        }
    }
    $headers['Authorization'] = $authorization

    $URI = ("$ApiBaseUri/" -replace '/$', '') + ("/$ApiEndpoint" -replace '^/', '')

    $APICall = @{
        Uri     = $URI
        Method  = $Method
        Headers = $Headers
    }

    if ($Body) {
        if ($Body -is [string]) {
            $APICall['Body'] = $Body
        } else {
            $APICall['Body'] = $Body | ConvertTo-Json -Depth 100
        }
    }

    try {
        do {
            $response = Invoke-RestMethod @APICall

            # Parse Data
            if ($response -is [System.Array]) {
                $response | ForEach-Object {
                    Write-Output $_
                }
            } elseif ($response) {
                $response.PSObject.Properties | Where-Object {
                    $_.Name -notin @('incomplete_results', 'repository_selection', 'total_count')
                } | ForEach-Object {
                    Write-Output $_.Value
                }
            }

            # Extract next page's URL from Link header if exists
            $nextLink = $null
            if ($response.Headers.Link -match '<(?<url>[^>]+)>;\s*rel="next"') {
                $nextLink = $matches['url']
            }

            if ($nextLink) {
                $APICall.Uri = $nextLink
            }

        } while ($nextLink)

    } catch [System.Net.WebException] {
        Write-Error "[$functionName] - WebException - $($_.Exception.Message)"
        throw $_
    } catch {
        Write-Error "[$functionName] - GeneralException - $($_.Exception.Message)"
        throw $_
    }
}

Write-Verbose "[$scriptName] - [public/API/Invoke-GitHubAPI.ps1] - Done"
#endregion - From public/API/Invoke-GitHubAPI.ps1

Write-Verbose "[$scriptName] - [public/API] - Done"
#endregion - From public/API
#region - From public/Auth
Write-Verbose "[$scriptName] - [public/Auth] - Processing folder"

#region - From public/Auth/Connect-GitHubAccount.ps1
Write-Verbose "[$scriptName] - [public/Auth/Connect-GitHubAccount.ps1] - Importing"

function Connect-GitHubAccount {
    <#
        .SYNOPSIS
        Connects to GitHub using a personal access token or device code login.

        .DESCRIPTION
        Connects to GitHub using a personal access token or device code login.

        For device flow / device code login:
        PowerShell requests device and user verification codes and gets the authorization URL where you will enter the user verification code.
        In GitHub you will be asked to enter a user verification code at https://github.com/login/device.
        PowerShell will keep polling GitHub for the user authentication status. Once you have authorized the device,
        the app will be able to make API calls with a new access token.

        .EXAMPLE
        Connect-GitHubAccount

        Connects to GitHub using a device flow login.
        If the user has already logged in, the access token will be refreshed.

        .EXAMPLE
        Connect-GitHubAccount -AccessToken
        ! Enter your personal access token: *************

        User gets prompted for the access token and stores it in the secret store.
        The token is used when connecting to GitHub.

        .EXAMPLE
        Connect-GitHubAccount -Mode 'OAuthApp' -Scope 'gist read:org repo workflow'

        Connects to GitHub using a device flow login and sets the scope of the access token.

        .NOTES
        https://docs.github.com/en/rest/overview/other-authentication-methods#authenticating-for-saml-sso
    #>

    [Alias('Connect-GHAccount')]
    [Alias('Connect-GitHub')]
    [Alias('Connect-GH')]
    [Alias('Login-GitHubAccount')]
    [Alias('Login-GHAccount')]
    [Alias('Login-GitHub')]
    [Alias('Login-GH')]
    [OutputType([void])]
    [CmdletBinding(DefaultParameterSetName = 'DeviceFlow')]
    param (
        # Choose between authentication methods, either OAuthApp or GitHubApp.
        # For more info about the types of authentication visit:
        # https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/differences-between-github-apps-and-oauth-apps
        [Parameter(ParameterSetName = 'DeviceFlow')]
        [ValidateSet('OAuthApp', 'GitHubApp')]
        [string] $Mode = 'GitHubApp',

        # The scope of the access token, when using OAuth authentication.
        # Provide the list of scopes as space-separated values.
        # For more information on scopes visit:
        # https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/scopes-for-oauth-apps
        [Parameter(ParameterSetName = 'DeviceFlow')]
        [string] $Scope = 'gist read:org repo workflow',

        # The personal access token to use for authentication.
        [Parameter(
            Mandatory,
            ParameterSetName = 'PAT'
        )]
        [switch] $AccessToken
    )

    $envVar = Get-ChildItem -Path 'Env:' | Where-Object Name -In 'GH_TOKEN', 'GITHUB_TOKEN' | Select-Object -First 1
    $envVarPresent = $envVar.count -gt 0
    $AuthType = $envVarPresent ? 'sPAT' : $PSCmdlet.ParameterSetName

    switch ($AuthType) {
        'DeviceFlow' {
            Write-Verbose 'Logging in using device flow...'
            $clientID = $script:Auth.$Mode.ClientID
            if ($Mode -ne (Get-GitHubConfig -Name DeviceFlowType -AsPlainText -ea SilentlyContinue)) {
                Write-Verbose "Using $Mode authentication..."
                $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $clientID -Scope $Scope
            } else {
                $accessTokenValidity = [datetime](Get-GitHubConfig -Name 'AccessTokenExpirationDate' -AsPlainText) - (Get-Date)
                $accessTokenIsValid = $accessTokenValidity.Seconds -gt 0
                $accessTokenValidityText = "$($accessTokenValidity.Hours):$($accessTokenValidity.Minutes):$($accessTokenValidity.Seconds)"
                if ($accessTokenIsValid) {
                    if ($accessTokenValidity -gt 4) {
                        Write-Host '✓ ' -ForegroundColor Green -NoNewline
                        Write-Host "Access token is still valid for $accessTokenValidityText ..."
                        return
                    } else {
                        Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline
                        Write-Host "Access token remaining validity $accessTokenValidityText. Refreshing access token..."
                        $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $clientID -RefreshToken (Get-GitHubConfig -Name RefreshToken)
                    }
                } else {
                    $refreshTokenValidity = [datetime](Get-GitHubConfig -Name 'RefreshTokenExpirationDate' -AsPlainText) - (Get-Date)
                    $refreshTokenIsValid = $refreshTokenValidity.Seconds -gt 0
                    if ($refreshTokenIsValid) {
                        Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline
                        Write-Verbose 'Access token expired. Refreshing access token...'
                        $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $clientID -RefreshToken (Get-GitHubConfig -Name RefreshToken)
                    } else {
                        Write-Verbose "Using $Mode authentication..."
                        $tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $clientID -Scope $Scope
                    }
                }
            }
            Reset-GitHubConfig -Scope 'Auth'
            switch ($Mode) {
                'GitHubApp' {
                    $settings = @{
                        AccessToken                = ConvertTo-SecureString -AsPlainText $tokenResponse.access_token
                        AccessTokenExpirationDate  = (Get-Date).AddSeconds($tokenResponse.expires_in)
                        RefreshToken               = ConvertTo-SecureString -AsPlainText $tokenResponse.refresh_token
                        RefreshTokenExpirationDate = (Get-Date).AddSeconds($tokenResponse.refresh_token_expires_in)
                        Scope                      = $tokenResponse.scope
                        AuthType                   = $AuthType
                        AccessTokenType            = $tokenResponse.access_token -replace '_.*$', '_*'
                        DeviceFlowType             = $Mode
                    }
                }
                'OAuthApp' {
                    $settings = @{
                        AccessToken                = ConvertTo-SecureString -AsPlainText $tokenResponse.access_token
                        Scope                      = $tokenResponse.scope
                        AuthType                   = $AuthType
                        AccessTokenType            = $tokenResponse.access_token -replace '_.*$', '_*'
                        DeviceFlowType             = $Mode
                    }
                }
            }
            Set-GitHubConfig @settings
            break
        }
        'PAT' {
            Write-Verbose 'Logging in using personal access token...'
            Reset-GitHubConfig -Scope 'Auth'
            Write-Host '! ' -ForegroundColor DarkYellow -NoNewline
            $accessToken = Read-Host -Prompt 'Enter your personal access token' -AsSecureString
            $prefix = (ConvertFrom-SecureString $accessToken -AsPlainText) -replace '_.*$', '_*'
            if ($prefix -notmatch '^ghp_|^github_pat_') {
                Write-Host '⚠ ' -ForegroundColor Yellow -NoNewline
                Write-Host "Unexpected access token format: $prefix"
            }
            $settings = @{
                AuthType        = $AuthType
                AccessToken     = $accessToken
                AccessTokenType = $prefix
            }
            Set-GitHubConfig @settings
            break
        }
        'sPAT' {
            Write-Verbose 'Logging in using system access token...'
            Reset-GitHubConfig -Scope 'Auth'
            $prefix = $envVar.Value -replace '_.*$', '_*'
            $settings = @{
                AuthType        = 'sPAT'
                AccessToken     = ConvertTo-SecureString -AsPlainText $envVar.Value
                AccessTokenType = $prefix
            }
            Set-GitHubConfig @settings
        }
    }

    Write-Host '✓ ' -ForegroundColor Green -NoNewline
    Write-Host 'Logged in to GitHub!'
}

Write-Verbose "[$scriptName] - [public/Auth/Connect-GitHubAccount.ps1] - Done"
#endregion - From public/Auth/Connect-GitHubAccount.ps1
#region - From public/Auth/Disconnect-GitHubAccount.ps1
Write-Verbose "[$scriptName] - [public/Auth/Disconnect-GitHubAccount.ps1] - Importing"

function Disconnect-GitHubAccount {
    <#
        .SYNOPSIS
        Disconnects from GitHub and removes the current GitHub configuration.

        .DESCRIPTION
        Disconnects from GitHub and removes the current GitHub configuration.

        .EXAMPLE
        Disconnect-GitHubAccount

        Disconnects from GitHub and removes the current GitHub configuration.
    #>

    [Alias('Disconnect-GHAccount')]
    [Alias('Disconnect-GitHub')]
    [Alias('Disconnect-GH')]
    [Alias('Logout-GitHubAccount')]
    [Alias('Logout-GHAccount')]
    [Alias('Logout-GitHub')]
    [Alias('Logout-GH')]
    [Alias('Logoff-GitHubAccount')]
    [Alias('Logoff-GHAccount')]
    [Alias('Logoff-GitHub')]
    [Alias('Logoff-GH')]
    [OutputType([void])]
    [CmdletBinding()]
    param ()

    Reset-GitHubConfig -Scope 'All'

    Write-Host '✓ ' -ForegroundColor Green -NoNewline
    Write-Host 'Logged out of GitHub!'
}

Write-Verbose "[$scriptName] - [public/Auth/Disconnect-GitHubAccount.ps1] - Done"
#endregion - From public/Auth/Disconnect-GitHubAccount.ps1

Write-Verbose "[$scriptName] - [public/Auth] - Done"
#endregion - From public/Auth
#region - From public/Config
Write-Verbose "[$scriptName] - [public/Config] - Processing folder"

#region - From public/Config/Get-GitHubConfig.ps1
Write-Verbose "[$scriptName] - [public/Config/Get-GitHubConfig.ps1] - Importing"

function Get-GitHubConfig {
    <#
        .SYNOPSIS
        Get the current GitHub configuration.

        .DESCRIPTION
        Get the current GitHub configuration.
        The configuration is first loaded from the configuration file.

        .EXAMPLE
        Get-GitHubConfig

        Returns the current GitHub configuration.

    #>

    [Alias('Get-GHConfig')]
    [Alias('GGHC')]
    [OutputType([object])]
    [CmdletBinding()]
    param (
        [string] $Name,
        [switch] $AsPlainText
    )
    $prefix = $script:SecretVault.Prefix
    $Name = "$prefix$Name"
    Get-Secret -Name $Name -Vault $script:SecretVault.Name -AsPlainText:$AsPlainText
}

Write-Verbose "[$scriptName] - [public/Config/Get-GitHubConfig.ps1] - Done"
#endregion - From public/Config/Get-GitHubConfig.ps1
#region - From public/Config/Set-GitHubConfig.ps1
Write-Verbose "[$scriptName] - [public/Config/Set-GitHubConfig.ps1] - Importing"

function Set-GitHubConfig {
    <#
        .SYNOPSIS
        Set the GitHub configuration.

        .DESCRIPTION
        Set the GitHub configuration. Specific scopes can be set by using the parameters.

        .EXAMPLE
        Set-GitHubConfig -APIBaseURI 'https://api.github.com" -APIVersion '2022-11-28'

        Sets the App.API scope of the GitHub configuration.

        .EXAMPLE
        Set-GitHubConfig -Name "MyFavouriteRepo" -Value 'https://github.com/PSModule/GitHub'

        Sets a item called 'MyFavouriteRepo' in the GitHub configuration.
    #>

    [Alias('Set-GHConfig')]
    [CmdletBinding()]
    param (
        # Set the access token type.
        [Parameter()]
        [string] $AccessTokenType = '',

        # Set the access token.
        [Parameter()]
        [securestring] $AccessToken = '',

        # Set the access token expiration date.
        [Parameter()]
        [datetime] $AccessTokenExpirationDate,

        # Set the API Base URI.
        [Parameter()]
        [string] $ApiBaseUri,

        # Set the GitHub API Version.
        [Parameter()]
        [string] $ApiVersion,

        # Set the authentication type.
        [Parameter()]
        [string] $AuthType,

        # Set the device flow type.
        [Parameter()]
        [string] $DeviceFlowType,

        # Set the default for the Owner parameter.
        [Parameter()]
        [string] $Owner,

        # Set the refresh token.
        [Parameter()]
        [securestring] $RefreshToken,

        # Set the refresh token expiration date.
        [Parameter()]
        [datetime] $RefreshTokenExpirationDate,

        # Set the default for the Repo parameter.
        [Parameter()]
        [string] $Repo,

        # Set the scope.
        [Parameter()]
        [string] $Scope,

        # Set the GitHub username.
        [Parameter()]
        [string] $UserName,

        # Choose a custom name to set.
        [Parameter()]
        [string] $Name,

        # Choose a custom value to set.
        [Parameter()]
        [string] $Value = ''
    )

    $prefix = $script:SecretVault.Prefix

    switch ($PSBoundParameters.Keys) {
        'AccessToken' {
            Set-Secret -Name "$prefix`AccessToken" -SecureStringSecret $AccessToken -Vault $script:SecretVault.Name
        }
        'AccessTokenExpirationDate' {
            Set-Secret -Name "$prefix`AccessTokenExpirationDate" -Secret $AccessTokenExpirationDate.ToString() -Vault $script:SecretVault.Name
        }
        'AccessTokenType' {
            Set-Secret -Name "$prefix`AccessTokenType" -Secret $AccessTokenType -Vault $script:SecretVault.Name
        }
        'ApiBaseUri' {
            Set-Secret -Name "$prefix`ApiBaseUri" -Secret $ApiBaseUri -Vault $script:SecretVault.Name
        }
        'ApiVersion' {
            Set-Secret -Name "$prefix`ApiVersion" -Secret $ApiVersion -Vault $script:SecretVault.Name
        }
        'AuthType' {
            Set-Secret -Name "$prefix`AuthType" -Secret $AuthType -Vault $script:SecretVault.Name
        }
        'DeviceFlowType' {
            Set-Secret -Name "$prefix`DeviceFlowType" -Secret $DeviceFlowType -Vault $script:SecretVault.Name
        }
        'Owner' {
            Set-Secret -Name "$prefix`Owner" -Secret $Owner -Vault $script:SecretVault.Name
        }
        'RefreshToken' {
            Set-Secret -Name "$prefix`RefreshToken" -SecureStringSecret $RefreshToken -Vault $script:SecretVault.Name
        }
        'RefreshTokenExpirationDate' {
            Set-Secret -Name "$prefix`RefreshTokenExpirationDate" -Secret $RefreshTokenExpirationDate.ToString() -Vault $script:SecretVault.Name
        }
        'Repo' {
            Set-Secret -Name "$prefix`Repo" -Secret $Repo -Vault $script:SecretVault.Name
        }
        'Scope' {
            Set-Secret -Name "$prefix`Scope" -Secret $Scope -Vault $script:SecretVault.Name
        }
        'UserName' {
            Set-Secret -Name "$prefix`UserName" -Secret $UserName -Vault $script:SecretVault.Name
        }
        'Name' {
            Set-Secret -Name "$prefix$Name" -Secret $Value -Vault $script:SecretVault.Name
        }
    }
}

Write-Verbose "[$scriptName] - [public/Config/Set-GitHubConfig.ps1] - Done"
#endregion - From public/Config/Set-GitHubConfig.ps1

Write-Verbose "[$scriptName] - [public/Config] - Done"
#endregion - From public/Config

Write-Verbose "[$scriptName] - [public] - Done"
#endregion - From public
#region - From GitHub.ps1
Write-Verbose "[$scriptName] - [GitHub.ps1] - Importing"

$scriptFilePath = $MyInvocation.MyCommand.Path

Write-Verbose "[$scriptFilePath] - Initializing GitHub module..." -Verbose

Initialize-SecretVault -Name $script:SecretVault.Name -Type $script:SecretVault.Type

# Autologon if a token is present in environment variables
$envVar = Get-ChildItem -Path 'Env:' | Where-Object Name -In 'GH_TOKEN', 'GITHUB_TOKEN' | Select-Object -First 1
$envVarPresent = $envVar.count -gt 0
if ($envVarPresent) {
    Connect-GitHubAccount
}
Write-Verbose "[$scriptName] - [GitHub.ps1] - Done"
#endregion - From GitHub.ps1

Export-ModuleMember -Function 'Invoke-GitHubAPI','Connect-GitHubAccount','Disconnect-GitHubAccount','Get-GitHubConfig','Set-GitHubConfig' -Cmdlet '' -Variable '' -Alias '*'